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
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Pure Python implementation of a binary search algorithm. For doctests run following command: python3 -m doctest -v simple_binary_search.py For manual testing run: python3 simple_binary_search.py """ from __future__ import annotations def binary_search(a_list: list[int], item: int) -> bool: """ >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> print(binary_search(test_list, 3)) False >>> print(binary_search(test_list, 13)) True >>> print(binary_search([4, 4, 5, 6, 7], 4)) True >>> print(binary_search([4, 4, 5, 6, 7], -10)) False >>> print(binary_search([-18, 2], -18)) True >>> print(binary_search([5], 5)) True >>> print(binary_search(['a', 'c', 'd'], 'c')) True >>> print(binary_search(['a', 'c', 'd'], 'f')) False >>> print(binary_search([], 1)) False >>> print(binary_search([-.1, .1 , .8], .1)) True >>> binary_search(range(-5000, 5000, 10), 80) True >>> binary_search(range(-5000, 5000, 10), 1255) False >>> binary_search(range(0, 10000, 5), 2) False """ if len(a_list) == 0: return False midpoint = len(a_list) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint], item) else: return binary_search(a_list[midpoint + 1 :], item) if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item.strip()) for item in user_input.split(",")] target = int(input("Enter the number to be found in the list:\n").strip()) not_str = "" if binary_search(sequence, target) else "not " print(f"{target} was {not_str}found in {sequence}")
""" Pure Python implementation of a binary search algorithm. For doctests run following command: python3 -m doctest -v simple_binary_search.py For manual testing run: python3 simple_binary_search.py """ from __future__ import annotations def binary_search(a_list: list[int], item: int) -> bool: """ >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> print(binary_search(test_list, 3)) False >>> print(binary_search(test_list, 13)) True >>> print(binary_search([4, 4, 5, 6, 7], 4)) True >>> print(binary_search([4, 4, 5, 6, 7], -10)) False >>> print(binary_search([-18, 2], -18)) True >>> print(binary_search([5], 5)) True >>> print(binary_search(['a', 'c', 'd'], 'c')) True >>> print(binary_search(['a', 'c', 'd'], 'f')) False >>> print(binary_search([], 1)) False >>> print(binary_search([-.1, .1 , .8], .1)) True >>> binary_search(range(-5000, 5000, 10), 80) True >>> binary_search(range(-5000, 5000, 10), 1255) False >>> binary_search(range(0, 10000, 5), 2) False """ if len(a_list) == 0: return False midpoint = len(a_list) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint], item) else: return binary_search(a_list[midpoint + 1 :], item) if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item.strip()) for item in user_input.split(",")] target = int(input("Enter the number to be found in the list:\n").strip()) not_str = "" if binary_search(sequence, target) else "not " print(f"{target} was {not_str}found in {sequence}")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import math from numpy import inf from scipy.integrate import quad def gamma(num: float) -> float: """ https://en.wikipedia.org/wiki/Gamma_function In mathematics, the gamma function is one commonly used extension of the factorial function to complex numbers. The gamma function is defined for all complex numbers except the non-positive integers >>> gamma(-1) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(0) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(9) 40320.0 >>> from math import gamma as math_gamma >>> all(.99999999 < gamma(i) / math_gamma(i) <= 1.000000001 ... for i in range(1, 50)) True >>> from math import gamma as math_gamma >>> gamma(-1)/math_gamma(-1) <= 1.000000001 Traceback (most recent call last): ... ValueError: math domain error >>> from math import gamma as math_gamma >>> gamma(3.3) - math_gamma(3.3) <= 0.00000001 True """ if num <= 0: raise ValueError("math domain error") return quad(integrand, 0, inf, args=(num))[0] def integrand(x: float, z: float) -> float: return math.pow(x, z - 1) * math.exp(-x) if __name__ == "__main__": from doctest import testmod testmod()
import math from numpy import inf from scipy.integrate import quad def gamma(num: float) -> float: """ https://en.wikipedia.org/wiki/Gamma_function In mathematics, the gamma function is one commonly used extension of the factorial function to complex numbers. The gamma function is defined for all complex numbers except the non-positive integers >>> gamma(-1) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(0) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(9) 40320.0 >>> from math import gamma as math_gamma >>> all(.99999999 < gamma(i) / math_gamma(i) <= 1.000000001 ... for i in range(1, 50)) True >>> from math import gamma as math_gamma >>> gamma(-1)/math_gamma(-1) <= 1.000000001 Traceback (most recent call last): ... ValueError: math domain error >>> from math import gamma as math_gamma >>> gamma(3.3) - math_gamma(3.3) <= 0.00000001 True """ if num <= 0: raise ValueError("math domain error") return quad(integrand, 0, inf, args=(num))[0] def integrand(x: float, z: float) -> float: return math.pow(x, z - 1) * math.exp(-x) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
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 ): if 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 != 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 ): if 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
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import numpy as np from sklearn.utils import shuffle import input_data random_numer = 42 np.random.seed(random_numer) def ReLu(x): mask = (x > 0) * 1.0 return mask * x def d_ReLu(x): mask = (x > 0) * 1.0 return mask def arctan(x): return np.arctan(x) def d_arctan(x): return 1 / (1 + x ** 2) def log(x): return 1 / (1 + np.exp(-1 * x)) def d_log(x): return log(x) * (1 - log(x)) def tanh(x): return np.tanh(x) def d_tanh(x): return 1 - np.tanh(x) ** 2 def plot(samples): fig = plt.figure(figsize=(4, 4)) gs = gridspec.GridSpec(4, 4) gs.update(wspace=0.05, hspace=0.05) for i, sample in enumerate(samples): ax = plt.subplot(gs[i]) plt.axis("off") ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect("equal") plt.imshow(sample.reshape(28, 28), cmap="Greys_r") return fig if __name__ == "__main__": # 1. Load Data and declare hyper print("--------- Load Data ----------") mnist = input_data.read_data_sets("MNIST_data", one_hot=False) temp = mnist.test images, labels = temp.images, temp.labels images, labels = shuffle(np.asarray(images), np.asarray(labels)) num_epoch = 10 learing_rate = 0.00009 G_input = 100 hidden_input, hidden_input2, hidden_input3 = 128, 256, 346 hidden_input4, hidden_input5, hidden_input6 = 480, 560, 686 print("--------- Declare Hyper Parameters ----------") # 2. Declare Weights D_W1 = ( np.random.normal(size=(784, hidden_input), scale=(1.0 / np.sqrt(784 / 2.0))) * 0.002 ) # D_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 D_b1 = np.zeros(hidden_input) D_W2 = ( np.random.normal( size=(hidden_input, 1), scale=(1.0 / np.sqrt(hidden_input / 2.0)) ) * 0.002 ) # D_b2 = np.random.normal(size=(1),scale=(1. / np.sqrt(1 / 2.))) *0.002 D_b2 = np.zeros(1) G_W1 = ( np.random.normal( size=(G_input, hidden_input), scale=(1.0 / np.sqrt(G_input / 2.0)) ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b1 = np.zeros(hidden_input) G_W2 = ( np.random.normal( size=(hidden_input, hidden_input2), scale=(1.0 / np.sqrt(hidden_input / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b2 = np.zeros(hidden_input2) G_W3 = ( np.random.normal( size=(hidden_input2, hidden_input3), scale=(1.0 / np.sqrt(hidden_input2 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b3 = np.zeros(hidden_input3) G_W4 = ( np.random.normal( size=(hidden_input3, hidden_input4), scale=(1.0 / np.sqrt(hidden_input3 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b4 = np.zeros(hidden_input4) G_W5 = ( np.random.normal( size=(hidden_input4, hidden_input5), scale=(1.0 / np.sqrt(hidden_input4 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b5 = np.zeros(hidden_input5) G_W6 = ( np.random.normal( size=(hidden_input5, hidden_input6), scale=(1.0 / np.sqrt(hidden_input5 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b6 = np.zeros(hidden_input6) G_W7 = ( np.random.normal( size=(hidden_input6, 784), scale=(1.0 / np.sqrt(hidden_input6 / 2.0)) ) * 0.002 ) # G_b2 = np.random.normal(size=(784),scale=(1. / np.sqrt(784 / 2.))) *0.002 G_b7 = np.zeros(784) # 3. For Adam Optimzier v1, m1 = 0, 0 v2, m2 = 0, 0 v3, m3 = 0, 0 v4, m4 = 0, 0 v5, m5 = 0, 0 v6, m6 = 0, 0 v7, m7 = 0, 0 v8, m8 = 0, 0 v9, m9 = 0, 0 v10, m10 = 0, 0 v11, m11 = 0, 0 v12, m12 = 0, 0 v13, m13 = 0, 0 v14, m14 = 0, 0 v15, m15 = 0, 0 v16, m16 = 0, 0 v17, m17 = 0, 0 v18, m18 = 0, 0 beta_1, beta_2, eps = 0.9, 0.999, 0.00000001 print("--------- Started Training ----------") for iter in range(num_epoch): random_int = np.random.randint(len(images) - 5) current_image = np.expand_dims(images[random_int], axis=0) # Func: Generate The first Fake Data Z = np.random.uniform(-1.0, 1.0, size=[1, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) # Func: Forward Feed for Real data Dl1_r = current_image.dot(D_W1) + D_b1 Dl1_rA = ReLu(Dl1_r) Dl2_r = Dl1_rA.dot(D_W2) + D_b2 Dl2_rA = log(Dl2_r) # Func: Forward Feed for Fake Data Dl1_f = current_fake_data.dot(D_W1) + D_b1 Dl1_fA = ReLu(Dl1_f) Dl2_f = Dl1_fA.dot(D_W2) + D_b2 Dl2_fA = log(Dl2_f) # Func: Cost D D_cost = -np.log(Dl2_rA) + np.log(1.0 - Dl2_fA) # Func: Gradient grad_f_w2_part_1 = 1 / (1.0 - Dl2_fA) grad_f_w2_part_2 = d_log(Dl2_f) grad_f_w2_part_3 = Dl1_fA grad_f_w2 = grad_f_w2_part_3.T.dot(grad_f_w2_part_1 * grad_f_w2_part_2) grad_f_b2 = grad_f_w2_part_1 * grad_f_w2_part_2 grad_f_w1_part_1 = (grad_f_w2_part_1 * grad_f_w2_part_2).dot(D_W2.T) grad_f_w1_part_2 = d_ReLu(Dl1_f) grad_f_w1_part_3 = current_fake_data grad_f_w1 = grad_f_w1_part_3.T.dot(grad_f_w1_part_1 * grad_f_w1_part_2) grad_f_b1 = grad_f_w1_part_1 * grad_f_w1_part_2 grad_r_w2_part_1 = -1 / Dl2_rA grad_r_w2_part_2 = d_log(Dl2_r) grad_r_w2_part_3 = Dl1_rA grad_r_w2 = grad_r_w2_part_3.T.dot(grad_r_w2_part_1 * grad_r_w2_part_2) grad_r_b2 = grad_r_w2_part_1 * grad_r_w2_part_2 grad_r_w1_part_1 = (grad_r_w2_part_1 * grad_r_w2_part_2).dot(D_W2.T) grad_r_w1_part_2 = d_ReLu(Dl1_r) grad_r_w1_part_3 = current_image grad_r_w1 = grad_r_w1_part_3.T.dot(grad_r_w1_part_1 * grad_r_w1_part_2) grad_r_b1 = grad_r_w1_part_1 * grad_r_w1_part_2 grad_w1 = grad_f_w1 + grad_r_w1 grad_b1 = grad_f_b1 + grad_r_b1 grad_w2 = grad_f_w2 + grad_r_w2 grad_b2 = grad_f_b2 + grad_r_b2 # ---- Update Gradient ---- m1 = beta_1 * m1 + (1 - beta_1) * grad_w1 v1 = beta_2 * v1 + (1 - beta_2) * grad_w1 ** 2 m2 = beta_1 * m2 + (1 - beta_1) * grad_b1 v2 = beta_2 * v2 + (1 - beta_2) * grad_b1 ** 2 m3 = beta_1 * m3 + (1 - beta_1) * grad_w2 v3 = beta_2 * v3 + (1 - beta_2) * grad_w2 ** 2 m4 = beta_1 * m4 + (1 - beta_1) * grad_b2 v4 = beta_2 * v4 + (1 - beta_2) * grad_b2 ** 2 D_W1 = D_W1 - (learing_rate / (np.sqrt(v1 / (1 - beta_2)) + eps)) * ( m1 / (1 - beta_1) ) D_b1 = D_b1 - (learing_rate / (np.sqrt(v2 / (1 - beta_2)) + eps)) * ( m2 / (1 - beta_1) ) D_W2 = D_W2 - (learing_rate / (np.sqrt(v3 / (1 - beta_2)) + eps)) * ( m3 / (1 - beta_1) ) D_b2 = D_b2 - (learing_rate / (np.sqrt(v4 / (1 - beta_2)) + eps)) * ( m4 / (1 - beta_1) ) # Func: Forward Feed for G Z = np.random.uniform(-1.0, 1.0, size=[1, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) Dl1 = current_fake_data.dot(D_W1) + D_b1 Dl1_A = ReLu(Dl1) Dl2 = Dl1_A.dot(D_W2) + D_b2 Dl2_A = log(Dl2) # Func: Cost G G_cost = -np.log(Dl2_A) # Func: Gradient grad_G_w7_part_1 = ((-1 / Dl2_A) * d_log(Dl2).dot(D_W2.T) * (d_ReLu(Dl1))).dot( D_W1.T ) grad_G_w7_part_2 = d_log(Gl7) grad_G_w7_part_3 = Gl6A grad_G_w7 = grad_G_w7_part_3.T.dot(grad_G_w7_part_1 * grad_G_w7_part_1) grad_G_b7 = grad_G_w7_part_1 * grad_G_w7_part_2 grad_G_w6_part_1 = (grad_G_w7_part_1 * grad_G_w7_part_2).dot(G_W7.T) grad_G_w6_part_2 = d_ReLu(Gl6) grad_G_w6_part_3 = Gl5A grad_G_w6 = grad_G_w6_part_3.T.dot(grad_G_w6_part_1 * grad_G_w6_part_2) grad_G_b6 = grad_G_w6_part_1 * grad_G_w6_part_2 grad_G_w5_part_1 = (grad_G_w6_part_1 * grad_G_w6_part_2).dot(G_W6.T) grad_G_w5_part_2 = d_tanh(Gl5) grad_G_w5_part_3 = Gl4A grad_G_w5 = grad_G_w5_part_3.T.dot(grad_G_w5_part_1 * grad_G_w5_part_2) grad_G_b5 = grad_G_w5_part_1 * grad_G_w5_part_2 grad_G_w4_part_1 = (grad_G_w5_part_1 * grad_G_w5_part_2).dot(G_W5.T) grad_G_w4_part_2 = d_ReLu(Gl4) grad_G_w4_part_3 = Gl3A grad_G_w4 = grad_G_w4_part_3.T.dot(grad_G_w4_part_1 * grad_G_w4_part_2) grad_G_b4 = grad_G_w4_part_1 * grad_G_w4_part_2 grad_G_w3_part_1 = (grad_G_w4_part_1 * grad_G_w4_part_2).dot(G_W4.T) grad_G_w3_part_2 = d_arctan(Gl3) grad_G_w3_part_3 = Gl2A grad_G_w3 = grad_G_w3_part_3.T.dot(grad_G_w3_part_1 * grad_G_w3_part_2) grad_G_b3 = grad_G_w3_part_1 * grad_G_w3_part_2 grad_G_w2_part_1 = (grad_G_w3_part_1 * grad_G_w3_part_2).dot(G_W3.T) grad_G_w2_part_2 = d_ReLu(Gl2) grad_G_w2_part_3 = Gl1A grad_G_w2 = grad_G_w2_part_3.T.dot(grad_G_w2_part_1 * grad_G_w2_part_2) grad_G_b2 = grad_G_w2_part_1 * grad_G_w2_part_2 grad_G_w1_part_1 = (grad_G_w2_part_1 * grad_G_w2_part_2).dot(G_W2.T) grad_G_w1_part_2 = d_arctan(Gl1) grad_G_w1_part_3 = Z grad_G_w1 = grad_G_w1_part_3.T.dot(grad_G_w1_part_1 * grad_G_w1_part_2) grad_G_b1 = grad_G_w1_part_1 * grad_G_w1_part_2 # ---- Update Gradient ---- m5 = beta_1 * m5 + (1 - beta_1) * grad_G_w1 v5 = beta_2 * v5 + (1 - beta_2) * grad_G_w1 ** 2 m6 = beta_1 * m6 + (1 - beta_1) * grad_G_b1 v6 = beta_2 * v6 + (1 - beta_2) * grad_G_b1 ** 2 m7 = beta_1 * m7 + (1 - beta_1) * grad_G_w2 v7 = beta_2 * v7 + (1 - beta_2) * grad_G_w2 ** 2 m8 = beta_1 * m8 + (1 - beta_1) * grad_G_b2 v8 = beta_2 * v8 + (1 - beta_2) * grad_G_b2 ** 2 m9 = beta_1 * m9 + (1 - beta_1) * grad_G_w3 v9 = beta_2 * v9 + (1 - beta_2) * grad_G_w3 ** 2 m10 = beta_1 * m10 + (1 - beta_1) * grad_G_b3 v10 = beta_2 * v10 + (1 - beta_2) * grad_G_b3 ** 2 m11 = beta_1 * m11 + (1 - beta_1) * grad_G_w4 v11 = beta_2 * v11 + (1 - beta_2) * grad_G_w4 ** 2 m12 = beta_1 * m12 + (1 - beta_1) * grad_G_b4 v12 = beta_2 * v12 + (1 - beta_2) * grad_G_b4 ** 2 m13 = beta_1 * m13 + (1 - beta_1) * grad_G_w5 v13 = beta_2 * v13 + (1 - beta_2) * grad_G_w5 ** 2 m14 = beta_1 * m14 + (1 - beta_1) * grad_G_b5 v14 = beta_2 * v14 + (1 - beta_2) * grad_G_b5 ** 2 m15 = beta_1 * m15 + (1 - beta_1) * grad_G_w6 v15 = beta_2 * v15 + (1 - beta_2) * grad_G_w6 ** 2 m16 = beta_1 * m16 + (1 - beta_1) * grad_G_b6 v16 = beta_2 * v16 + (1 - beta_2) * grad_G_b6 ** 2 m17 = beta_1 * m17 + (1 - beta_1) * grad_G_w7 v17 = beta_2 * v17 + (1 - beta_2) * grad_G_w7 ** 2 m18 = beta_1 * m18 + (1 - beta_1) * grad_G_b7 v18 = beta_2 * v18 + (1 - beta_2) * grad_G_b7 ** 2 G_W1 = G_W1 - (learing_rate / (np.sqrt(v5 / (1 - beta_2)) + eps)) * ( m5 / (1 - beta_1) ) G_b1 = G_b1 - (learing_rate / (np.sqrt(v6 / (1 - beta_2)) + eps)) * ( m6 / (1 - beta_1) ) G_W2 = G_W2 - (learing_rate / (np.sqrt(v7 / (1 - beta_2)) + eps)) * ( m7 / (1 - beta_1) ) G_b2 = G_b2 - (learing_rate / (np.sqrt(v8 / (1 - beta_2)) + eps)) * ( m8 / (1 - beta_1) ) G_W3 = G_W3 - (learing_rate / (np.sqrt(v9 / (1 - beta_2)) + eps)) * ( m9 / (1 - beta_1) ) G_b3 = G_b3 - (learing_rate / (np.sqrt(v10 / (1 - beta_2)) + eps)) * ( m10 / (1 - beta_1) ) G_W4 = G_W4 - (learing_rate / (np.sqrt(v11 / (1 - beta_2)) + eps)) * ( m11 / (1 - beta_1) ) G_b4 = G_b4 - (learing_rate / (np.sqrt(v12 / (1 - beta_2)) + eps)) * ( m12 / (1 - beta_1) ) G_W5 = G_W5 - (learing_rate / (np.sqrt(v13 / (1 - beta_2)) + eps)) * ( m13 / (1 - beta_1) ) G_b5 = G_b5 - (learing_rate / (np.sqrt(v14 / (1 - beta_2)) + eps)) * ( m14 / (1 - beta_1) ) G_W6 = G_W6 - (learing_rate / (np.sqrt(v15 / (1 - beta_2)) + eps)) * ( m15 / (1 - beta_1) ) G_b6 = G_b6 - (learing_rate / (np.sqrt(v16 / (1 - beta_2)) + eps)) * ( m16 / (1 - beta_1) ) G_W7 = G_W7 - (learing_rate / (np.sqrt(v17 / (1 - beta_2)) + eps)) * ( m17 / (1 - beta_1) ) G_b7 = G_b7 - (learing_rate / (np.sqrt(v18 / (1 - beta_2)) + eps)) * ( m18 / (1 - beta_1) ) # --- Print Error ---- # print("Current Iter: ",iter, " Current D cost:",D_cost, " Current G cost: ", G_cost,end='\r') if iter == 0: learing_rate = learing_rate * 0.01 if iter == 40: learing_rate = learing_rate * 0.01 # ---- Print to Out put ---- if iter % 10 == 0: print( "Current Iter: ", iter, " Current D cost:", D_cost, " Current G cost: ", G_cost, end="\r", ) print("--------- Show Example Result See Tab Above ----------") print("--------- Wait for the image to load ---------") Z = np.random.uniform(-1.0, 1.0, size=[16, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) fig = plot(current_fake_data) fig.savefig( "Click_Me_{}.png".format( str(iter).zfill(3) + "_Ginput_" + str(G_input) + "_hiddenone" + str(hidden_input) + "_hiddentwo" + str(hidden_input2) + "_LR_" + str(learing_rate) ), bbox_inches="tight", ) # for complete explanation visit https://towardsdatascience.com/only-numpy-implementing-gan-general-adversarial-networks-and-adam-optimizer-using-numpy-with-2a7e4e032021 # -- end code --
import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import numpy as np from sklearn.utils import shuffle import input_data random_numer = 42 np.random.seed(random_numer) def ReLu(x): mask = (x > 0) * 1.0 return mask * x def d_ReLu(x): mask = (x > 0) * 1.0 return mask def arctan(x): return np.arctan(x) def d_arctan(x): return 1 / (1 + x ** 2) def log(x): return 1 / (1 + np.exp(-1 * x)) def d_log(x): return log(x) * (1 - log(x)) def tanh(x): return np.tanh(x) def d_tanh(x): return 1 - np.tanh(x) ** 2 def plot(samples): fig = plt.figure(figsize=(4, 4)) gs = gridspec.GridSpec(4, 4) gs.update(wspace=0.05, hspace=0.05) for i, sample in enumerate(samples): ax = plt.subplot(gs[i]) plt.axis("off") ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect("equal") plt.imshow(sample.reshape(28, 28), cmap="Greys_r") return fig if __name__ == "__main__": # 1. Load Data and declare hyper print("--------- Load Data ----------") mnist = input_data.read_data_sets("MNIST_data", one_hot=False) temp = mnist.test images, labels = temp.images, temp.labels images, labels = shuffle(np.asarray(images), np.asarray(labels)) num_epoch = 10 learing_rate = 0.00009 G_input = 100 hidden_input, hidden_input2, hidden_input3 = 128, 256, 346 hidden_input4, hidden_input5, hidden_input6 = 480, 560, 686 print("--------- Declare Hyper Parameters ----------") # 2. Declare Weights D_W1 = ( np.random.normal(size=(784, hidden_input), scale=(1.0 / np.sqrt(784 / 2.0))) * 0.002 ) # D_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 D_b1 = np.zeros(hidden_input) D_W2 = ( np.random.normal( size=(hidden_input, 1), scale=(1.0 / np.sqrt(hidden_input / 2.0)) ) * 0.002 ) # D_b2 = np.random.normal(size=(1),scale=(1. / np.sqrt(1 / 2.))) *0.002 D_b2 = np.zeros(1) G_W1 = ( np.random.normal( size=(G_input, hidden_input), scale=(1.0 / np.sqrt(G_input / 2.0)) ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b1 = np.zeros(hidden_input) G_W2 = ( np.random.normal( size=(hidden_input, hidden_input2), scale=(1.0 / np.sqrt(hidden_input / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b2 = np.zeros(hidden_input2) G_W3 = ( np.random.normal( size=(hidden_input2, hidden_input3), scale=(1.0 / np.sqrt(hidden_input2 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b3 = np.zeros(hidden_input3) G_W4 = ( np.random.normal( size=(hidden_input3, hidden_input4), scale=(1.0 / np.sqrt(hidden_input3 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b4 = np.zeros(hidden_input4) G_W5 = ( np.random.normal( size=(hidden_input4, hidden_input5), scale=(1.0 / np.sqrt(hidden_input4 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b5 = np.zeros(hidden_input5) G_W6 = ( np.random.normal( size=(hidden_input5, hidden_input6), scale=(1.0 / np.sqrt(hidden_input5 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b6 = np.zeros(hidden_input6) G_W7 = ( np.random.normal( size=(hidden_input6, 784), scale=(1.0 / np.sqrt(hidden_input6 / 2.0)) ) * 0.002 ) # G_b2 = np.random.normal(size=(784),scale=(1. / np.sqrt(784 / 2.))) *0.002 G_b7 = np.zeros(784) # 3. For Adam Optimzier v1, m1 = 0, 0 v2, m2 = 0, 0 v3, m3 = 0, 0 v4, m4 = 0, 0 v5, m5 = 0, 0 v6, m6 = 0, 0 v7, m7 = 0, 0 v8, m8 = 0, 0 v9, m9 = 0, 0 v10, m10 = 0, 0 v11, m11 = 0, 0 v12, m12 = 0, 0 v13, m13 = 0, 0 v14, m14 = 0, 0 v15, m15 = 0, 0 v16, m16 = 0, 0 v17, m17 = 0, 0 v18, m18 = 0, 0 beta_1, beta_2, eps = 0.9, 0.999, 0.00000001 print("--------- Started Training ----------") for iter in range(num_epoch): random_int = np.random.randint(len(images) - 5) current_image = np.expand_dims(images[random_int], axis=0) # Func: Generate The first Fake Data Z = np.random.uniform(-1.0, 1.0, size=[1, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) # Func: Forward Feed for Real data Dl1_r = current_image.dot(D_W1) + D_b1 Dl1_rA = ReLu(Dl1_r) Dl2_r = Dl1_rA.dot(D_W2) + D_b2 Dl2_rA = log(Dl2_r) # Func: Forward Feed for Fake Data Dl1_f = current_fake_data.dot(D_W1) + D_b1 Dl1_fA = ReLu(Dl1_f) Dl2_f = Dl1_fA.dot(D_W2) + D_b2 Dl2_fA = log(Dl2_f) # Func: Cost D D_cost = -np.log(Dl2_rA) + np.log(1.0 - Dl2_fA) # Func: Gradient grad_f_w2_part_1 = 1 / (1.0 - Dl2_fA) grad_f_w2_part_2 = d_log(Dl2_f) grad_f_w2_part_3 = Dl1_fA grad_f_w2 = grad_f_w2_part_3.T.dot(grad_f_w2_part_1 * grad_f_w2_part_2) grad_f_b2 = grad_f_w2_part_1 * grad_f_w2_part_2 grad_f_w1_part_1 = (grad_f_w2_part_1 * grad_f_w2_part_2).dot(D_W2.T) grad_f_w1_part_2 = d_ReLu(Dl1_f) grad_f_w1_part_3 = current_fake_data grad_f_w1 = grad_f_w1_part_3.T.dot(grad_f_w1_part_1 * grad_f_w1_part_2) grad_f_b1 = grad_f_w1_part_1 * grad_f_w1_part_2 grad_r_w2_part_1 = -1 / Dl2_rA grad_r_w2_part_2 = d_log(Dl2_r) grad_r_w2_part_3 = Dl1_rA grad_r_w2 = grad_r_w2_part_3.T.dot(grad_r_w2_part_1 * grad_r_w2_part_2) grad_r_b2 = grad_r_w2_part_1 * grad_r_w2_part_2 grad_r_w1_part_1 = (grad_r_w2_part_1 * grad_r_w2_part_2).dot(D_W2.T) grad_r_w1_part_2 = d_ReLu(Dl1_r) grad_r_w1_part_3 = current_image grad_r_w1 = grad_r_w1_part_3.T.dot(grad_r_w1_part_1 * grad_r_w1_part_2) grad_r_b1 = grad_r_w1_part_1 * grad_r_w1_part_2 grad_w1 = grad_f_w1 + grad_r_w1 grad_b1 = grad_f_b1 + grad_r_b1 grad_w2 = grad_f_w2 + grad_r_w2 grad_b2 = grad_f_b2 + grad_r_b2 # ---- Update Gradient ---- m1 = beta_1 * m1 + (1 - beta_1) * grad_w1 v1 = beta_2 * v1 + (1 - beta_2) * grad_w1 ** 2 m2 = beta_1 * m2 + (1 - beta_1) * grad_b1 v2 = beta_2 * v2 + (1 - beta_2) * grad_b1 ** 2 m3 = beta_1 * m3 + (1 - beta_1) * grad_w2 v3 = beta_2 * v3 + (1 - beta_2) * grad_w2 ** 2 m4 = beta_1 * m4 + (1 - beta_1) * grad_b2 v4 = beta_2 * v4 + (1 - beta_2) * grad_b2 ** 2 D_W1 = D_W1 - (learing_rate / (np.sqrt(v1 / (1 - beta_2)) + eps)) * ( m1 / (1 - beta_1) ) D_b1 = D_b1 - (learing_rate / (np.sqrt(v2 / (1 - beta_2)) + eps)) * ( m2 / (1 - beta_1) ) D_W2 = D_W2 - (learing_rate / (np.sqrt(v3 / (1 - beta_2)) + eps)) * ( m3 / (1 - beta_1) ) D_b2 = D_b2 - (learing_rate / (np.sqrt(v4 / (1 - beta_2)) + eps)) * ( m4 / (1 - beta_1) ) # Func: Forward Feed for G Z = np.random.uniform(-1.0, 1.0, size=[1, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) Dl1 = current_fake_data.dot(D_W1) + D_b1 Dl1_A = ReLu(Dl1) Dl2 = Dl1_A.dot(D_W2) + D_b2 Dl2_A = log(Dl2) # Func: Cost G G_cost = -np.log(Dl2_A) # Func: Gradient grad_G_w7_part_1 = ((-1 / Dl2_A) * d_log(Dl2).dot(D_W2.T) * (d_ReLu(Dl1))).dot( D_W1.T ) grad_G_w7_part_2 = d_log(Gl7) grad_G_w7_part_3 = Gl6A grad_G_w7 = grad_G_w7_part_3.T.dot(grad_G_w7_part_1 * grad_G_w7_part_1) grad_G_b7 = grad_G_w7_part_1 * grad_G_w7_part_2 grad_G_w6_part_1 = (grad_G_w7_part_1 * grad_G_w7_part_2).dot(G_W7.T) grad_G_w6_part_2 = d_ReLu(Gl6) grad_G_w6_part_3 = Gl5A grad_G_w6 = grad_G_w6_part_3.T.dot(grad_G_w6_part_1 * grad_G_w6_part_2) grad_G_b6 = grad_G_w6_part_1 * grad_G_w6_part_2 grad_G_w5_part_1 = (grad_G_w6_part_1 * grad_G_w6_part_2).dot(G_W6.T) grad_G_w5_part_2 = d_tanh(Gl5) grad_G_w5_part_3 = Gl4A grad_G_w5 = grad_G_w5_part_3.T.dot(grad_G_w5_part_1 * grad_G_w5_part_2) grad_G_b5 = grad_G_w5_part_1 * grad_G_w5_part_2 grad_G_w4_part_1 = (grad_G_w5_part_1 * grad_G_w5_part_2).dot(G_W5.T) grad_G_w4_part_2 = d_ReLu(Gl4) grad_G_w4_part_3 = Gl3A grad_G_w4 = grad_G_w4_part_3.T.dot(grad_G_w4_part_1 * grad_G_w4_part_2) grad_G_b4 = grad_G_w4_part_1 * grad_G_w4_part_2 grad_G_w3_part_1 = (grad_G_w4_part_1 * grad_G_w4_part_2).dot(G_W4.T) grad_G_w3_part_2 = d_arctan(Gl3) grad_G_w3_part_3 = Gl2A grad_G_w3 = grad_G_w3_part_3.T.dot(grad_G_w3_part_1 * grad_G_w3_part_2) grad_G_b3 = grad_G_w3_part_1 * grad_G_w3_part_2 grad_G_w2_part_1 = (grad_G_w3_part_1 * grad_G_w3_part_2).dot(G_W3.T) grad_G_w2_part_2 = d_ReLu(Gl2) grad_G_w2_part_3 = Gl1A grad_G_w2 = grad_G_w2_part_3.T.dot(grad_G_w2_part_1 * grad_G_w2_part_2) grad_G_b2 = grad_G_w2_part_1 * grad_G_w2_part_2 grad_G_w1_part_1 = (grad_G_w2_part_1 * grad_G_w2_part_2).dot(G_W2.T) grad_G_w1_part_2 = d_arctan(Gl1) grad_G_w1_part_3 = Z grad_G_w1 = grad_G_w1_part_3.T.dot(grad_G_w1_part_1 * grad_G_w1_part_2) grad_G_b1 = grad_G_w1_part_1 * grad_G_w1_part_2 # ---- Update Gradient ---- m5 = beta_1 * m5 + (1 - beta_1) * grad_G_w1 v5 = beta_2 * v5 + (1 - beta_2) * grad_G_w1 ** 2 m6 = beta_1 * m6 + (1 - beta_1) * grad_G_b1 v6 = beta_2 * v6 + (1 - beta_2) * grad_G_b1 ** 2 m7 = beta_1 * m7 + (1 - beta_1) * grad_G_w2 v7 = beta_2 * v7 + (1 - beta_2) * grad_G_w2 ** 2 m8 = beta_1 * m8 + (1 - beta_1) * grad_G_b2 v8 = beta_2 * v8 + (1 - beta_2) * grad_G_b2 ** 2 m9 = beta_1 * m9 + (1 - beta_1) * grad_G_w3 v9 = beta_2 * v9 + (1 - beta_2) * grad_G_w3 ** 2 m10 = beta_1 * m10 + (1 - beta_1) * grad_G_b3 v10 = beta_2 * v10 + (1 - beta_2) * grad_G_b3 ** 2 m11 = beta_1 * m11 + (1 - beta_1) * grad_G_w4 v11 = beta_2 * v11 + (1 - beta_2) * grad_G_w4 ** 2 m12 = beta_1 * m12 + (1 - beta_1) * grad_G_b4 v12 = beta_2 * v12 + (1 - beta_2) * grad_G_b4 ** 2 m13 = beta_1 * m13 + (1 - beta_1) * grad_G_w5 v13 = beta_2 * v13 + (1 - beta_2) * grad_G_w5 ** 2 m14 = beta_1 * m14 + (1 - beta_1) * grad_G_b5 v14 = beta_2 * v14 + (1 - beta_2) * grad_G_b5 ** 2 m15 = beta_1 * m15 + (1 - beta_1) * grad_G_w6 v15 = beta_2 * v15 + (1 - beta_2) * grad_G_w6 ** 2 m16 = beta_1 * m16 + (1 - beta_1) * grad_G_b6 v16 = beta_2 * v16 + (1 - beta_2) * grad_G_b6 ** 2 m17 = beta_1 * m17 + (1 - beta_1) * grad_G_w7 v17 = beta_2 * v17 + (1 - beta_2) * grad_G_w7 ** 2 m18 = beta_1 * m18 + (1 - beta_1) * grad_G_b7 v18 = beta_2 * v18 + (1 - beta_2) * grad_G_b7 ** 2 G_W1 = G_W1 - (learing_rate / (np.sqrt(v5 / (1 - beta_2)) + eps)) * ( m5 / (1 - beta_1) ) G_b1 = G_b1 - (learing_rate / (np.sqrt(v6 / (1 - beta_2)) + eps)) * ( m6 / (1 - beta_1) ) G_W2 = G_W2 - (learing_rate / (np.sqrt(v7 / (1 - beta_2)) + eps)) * ( m7 / (1 - beta_1) ) G_b2 = G_b2 - (learing_rate / (np.sqrt(v8 / (1 - beta_2)) + eps)) * ( m8 / (1 - beta_1) ) G_W3 = G_W3 - (learing_rate / (np.sqrt(v9 / (1 - beta_2)) + eps)) * ( m9 / (1 - beta_1) ) G_b3 = G_b3 - (learing_rate / (np.sqrt(v10 / (1 - beta_2)) + eps)) * ( m10 / (1 - beta_1) ) G_W4 = G_W4 - (learing_rate / (np.sqrt(v11 / (1 - beta_2)) + eps)) * ( m11 / (1 - beta_1) ) G_b4 = G_b4 - (learing_rate / (np.sqrt(v12 / (1 - beta_2)) + eps)) * ( m12 / (1 - beta_1) ) G_W5 = G_W5 - (learing_rate / (np.sqrt(v13 / (1 - beta_2)) + eps)) * ( m13 / (1 - beta_1) ) G_b5 = G_b5 - (learing_rate / (np.sqrt(v14 / (1 - beta_2)) + eps)) * ( m14 / (1 - beta_1) ) G_W6 = G_W6 - (learing_rate / (np.sqrt(v15 / (1 - beta_2)) + eps)) * ( m15 / (1 - beta_1) ) G_b6 = G_b6 - (learing_rate / (np.sqrt(v16 / (1 - beta_2)) + eps)) * ( m16 / (1 - beta_1) ) G_W7 = G_W7 - (learing_rate / (np.sqrt(v17 / (1 - beta_2)) + eps)) * ( m17 / (1 - beta_1) ) G_b7 = G_b7 - (learing_rate / (np.sqrt(v18 / (1 - beta_2)) + eps)) * ( m18 / (1 - beta_1) ) # --- Print Error ---- # print("Current Iter: ",iter, " Current D cost:",D_cost, " Current G cost: ", G_cost,end='\r') if iter == 0: learing_rate = learing_rate * 0.01 if iter == 40: learing_rate = learing_rate * 0.01 # ---- Print to Out put ---- if iter % 10 == 0: print( "Current Iter: ", iter, " Current D cost:", D_cost, " Current G cost: ", G_cost, end="\r", ) print("--------- Show Example Result See Tab Above ----------") print("--------- Wait for the image to load ---------") Z = np.random.uniform(-1.0, 1.0, size=[16, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) fig = plot(current_fake_data) fig.savefig( "Click_Me_{}.png".format( str(iter).zfill(3) + "_Ginput_" + str(G_input) + "_hiddenone" + str(hidden_input) + "_hiddentwo" + str(hidden_input2) + "_LR_" + str(learing_rate) ), bbox_inches="tight", ) # for complete explanation visit https://towardsdatascience.com/only-numpy-implementing-gan-general-adversarial-networks-and-adam-optimizer-using-numpy-with-2a7e4e032021 # -- end code --
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 115: https://projecteuler.net/problem=115 NOTE: This is a more difficult version of Problem 114 (https://projecteuler.net/problem=114). A row measuring n units in length has red blocks with a minimum length of m units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one black square. Let the fill-count function, F(m, n), represent the number of ways that a row can be filled. For example, F(3, 29) = 673135 and F(3, 30) = 1089155. That is, for m = 3, it can be seen that n = 30 is the smallest value for which the fill-count function first exceeds one million. In the same way, for m = 10, it can be verified that F(10, 56) = 880711 and F(10, 57) = 1148904, so n = 57 is the least value for which the fill-count function first exceeds one million. For m = 50, find the least value of n for which the fill-count function first exceeds one million. """ from itertools import count def solution(min_block_length: int = 50) -> int: """ Returns for given minimum block length the least value of n for which the fill-count function first exceeds one million >>> solution(3) 30 >>> solution(10) 57 """ fill_count_functions = [1] * min_block_length for n in count(min_block_length): fill_count_functions.append(1) for block_length in range(min_block_length, n + 1): for block_start in range(n - block_length): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_000_000: break return n if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 115: https://projecteuler.net/problem=115 NOTE: This is a more difficult version of Problem 114 (https://projecteuler.net/problem=114). A row measuring n units in length has red blocks with a minimum length of m units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one black square. Let the fill-count function, F(m, n), represent the number of ways that a row can be filled. For example, F(3, 29) = 673135 and F(3, 30) = 1089155. That is, for m = 3, it can be seen that n = 30 is the smallest value for which the fill-count function first exceeds one million. In the same way, for m = 10, it can be verified that F(10, 56) = 880711 and F(10, 57) = 1148904, so n = 57 is the least value for which the fill-count function first exceeds one million. For m = 50, find the least value of n for which the fill-count function first exceeds one million. """ from itertools import count def solution(min_block_length: int = 50) -> int: """ Returns for given minimum block length the least value of n for which the fill-count function first exceeds one million >>> solution(3) 30 >>> solution(10) 57 """ fill_count_functions = [1] * min_block_length for n in count(min_block_length): fill_count_functions.append(1) for block_length in range(min_block_length, n + 1): for block_start in range(n - block_length): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_000_000: break return n if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Finding the peak of a unimodal list using divide and conquer. A unimodal array is defined as follows: array is increasing up to index p, then decreasing afterwards. (for p >= 1) An obvious solution can be performed in O(n), to find the maximum of the array. (From Kleinberg and Tardos. Algorithm Design. Addison Wesley 2006: Chapter 5 Solved Exercise 1) """ from __future__ import annotations def peak(lst: list[int]) -> int: """ Return the peak value of `lst`. >>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1]) 5 >>> peak([1, 10, 9, 8, 7, 6, 5, 4]) 10 >>> peak([1, 9, 8, 7]) 9 >>> peak([1, 2, 3, 4, 5, 6, 7, 0]) 7 >>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2]) 4 """ # middle index m = len(lst) // 2 # choose the middle 3 elements three = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m]) == 2: m -= 1 return peak(lst[m:]) # decreasing else: if len(lst[:m]) == 2: m += 1 return peak(lst[:m]) if __name__ == "__main__": import doctest doctest.testmod()
""" Finding the peak of a unimodal list using divide and conquer. A unimodal array is defined as follows: array is increasing up to index p, then decreasing afterwards. (for p >= 1) An obvious solution can be performed in O(n), to find the maximum of the array. (From Kleinberg and Tardos. Algorithm Design. Addison Wesley 2006: Chapter 5 Solved Exercise 1) """ from __future__ import annotations def peak(lst: list[int]) -> int: """ Return the peak value of `lst`. >>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1]) 5 >>> peak([1, 10, 9, 8, 7, 6, 5, 4]) 10 >>> peak([1, 9, 8, 7]) 9 >>> peak([1, 2, 3, 4, 5, 6, 7, 0]) 7 >>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2]) 4 """ # middle index m = len(lst) // 2 # choose the middle 3 elements three = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m]) == 2: m -= 1 return peak(lst[m:]) # decreasing else: if len(lst[:m]) == 2: m += 1 return peak(lst[:m]) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
8C TS KC 9H 4S 7D 2S 5D 3S AC 5C AD 5D AC 9C 7C 5H 8D TD KS 3H 7H 6S KC JS QH TD JC 2D 8S TH 8H 5C QS TC 9H 4D JC KS JS 7C 5H KC QH JD AS KH 4C AD 4S 5H KS 9C 7D 9H 8D 3S 5D 5C AH 6H 4H 5C 3H 2H 3S QH 5S 6S AS TD 8C 4H 7C TC KC 4C 3H 7S KS 7C 9C 6D KD 3H 4C QS QC AC KH JC 6S 5H 2H 2D KD 9D 7C AS JS AD QH TH 9D 8H TS 6D 3S AS AC 2H 4S 5C 5S TC KC JD 6C TS 3C QD AS 6H JS 2C 3D 9H KC 4H 8S KD 8S 9S 7C 2S 3S 6D 6S 4H KC 3C 8C 2D 7D 4D 9S 4S QH 4H JD 8C KC 7S TC 2D TS 8H QD AC 5C 3D KH QD 6C 6S AD AS 8H 2H QS 6S 8D 4C 8S 6C QH TC 6D 7D 9D 2S 8D 8C 4C TS 9S 9D 9C AC 3D 3C QS 2S 4H JH 3D 2D TD 8S 9H 5H QS 8S 6D 3C 8C JD AS 7H 7D 6H TD 9D AS JH 6C QC 9S KD JC AH 8S QS 4D TH AC TS 3C 3D 5C 5S 4D JS 3D 8H 6C TS 3S AD 8C 6D 7C 5D 5H 3S 5C JC 2H 5S 3D 5H 6H 2S KS 3D 5D JD 7H JS 8H KH 4H AS JS QS QC TC 6D 7C KS 3D QS TS 2H JS 4D AS 9S JC KD QD 5H 4D 5D KH 7H 3D JS KD 4H 2C 9H 6H 5C 9D 6C JC 2D TH 9S 7D 6D AS QD JH 4D JS 7C QS 5C 3H KH QD AD 8C 8H 3S TH 9D 5S AH 9S 4D 9D 8S 4H JS 3C TC 8D 2C KS 5H QD 3S TS 9H AH AD 8S 5C 7H 5D KD 9H 4D 3D 2D KS AD KS KC 9S 6D 2C QH 9D 9H TS TC 9C 6H 5D QH 4D AD 6D QC JS KH 9S 3H 9D JD 5C 4D 9H AS TC QH 2C 6D JC 9C 3C AD 9S KH 9D 7D KC 9C 7C JC JS KD 3H AS 3C 7D QD KH QS 2C 3S 8S 8H 9H 9C JC QH 8D 3C KC 4C 4H 6D AD 9H 9D 3S KS QS 7H KH 7D 5H 5D JD AD 2H 2C 6H TH TC 7D 8D 4H 8C AS 4S 2H AC QC 3S 6D TH 4D 4C KH 4D TC KS AS 7C 3C 6D 2D 9H 6C 8C TD 5D QS 2C 7H 4C 9C 3H 9H 5H JH TS 7S TD 6H AD QD 8H 8S 5S AD 9C 8C 7C 8D 5H 9D 8S 2S 4H KH KS 9S 2S KC 5S AD 4S 7D QS 9C QD 6H JS 5D AC 8D 2S AS KH AC JC 3S 9D 9S 3C 9C 5S JS AD 3C 3D KS 3S 5C 9C 8C TS 4S JH 8D 5D 6H KD QS QD 3D 6C KC 8S JD 6C 3S 8C TC QC 3C QH JS KC JC 8H 2S 9H 9C JH 8S 8C 9S 8S 2H QH 4D QC 9D KC AS TH 3C 8S 6H TH 7C 2H 6S 3C 3H AS 7S QH 5S JS 4H 5H TS 8H AH AC JC 9D 8H 2S 4S TC JC 3C 7H 3H 5C 3D AD 3C 3S 4C QC AS 5D TH 8C 6S 9D 4C JS KH AH TS JD 8H AD 4C 6S 9D 7S AC 4D 3D 3S TC JD AD 7H 6H 4H JH KC TD TS 7D 6S 8H JH TC 3S 8D 8C 9S 2C 5C 4D 2C 9D KC QH TH QS JC 9C 4H TS QS 3C QD 8H KH 4H 8D TD 8S AC 7C 3C TH 5S 8H 8C 9C JD TC KD QC TC JD TS 8C 3H 6H KD 7C TD JH QS KS 9C 6D 6S AS 9H KH 6H 2H 4D AH 2D JH 6H TD 5D 4H JD KD 8C 9S JH QD JS 2C QS 5C 7C 4S TC 7H 8D 2S 6H 7S 9C 7C KC 8C 5D 7H 4S TD QC 8S JS 4H KS AD 8S JH 6D TD KD 7C 6C 2D 7D JC 6H 6S JS 4H QH 9H AH 4C 3C 6H 5H AS 7C 7S 3D KH KC 5D 5C JC 3D TD AS 4D 6D 6S QH JD KS 8C 7S 8S QH 2S JD 5C 7H AH QD 8S 3C 6H 6C 2C 8D TD 7D 4C 4D 5D QH KH 7C 2S 7H JS 6D QC QD AD 6C 6S 7D TH 6H 2H 8H KH 4H KS JS KD 5D 2D KH 7D 9C 8C 3D 9C 6D QD 3C KS 3S 7S AH JD 2D AH QH AS JC 8S 8H 4C KC TH 7D JC 5H TD 7C 5D KD 4C AD 8H JS KC 2H AC AH 7D JH KH 5D 7S 6D 9S 5S 9C 6H 8S TD JD 9H 6C AC 7D 8S 6D TS KD 7H AC 5S 7C 5D AH QC JC 4C TC 8C 2H TS 2C 7D KD KC 6S 3D 7D 2S 8S 3H 5S 5C 8S 5D 8H 4C 6H KC 3H 7C 5S KD JH 8C 3D 3C 6C KC TD 7H 7C 4C JC KC 6H TS QS TD KS 8H 8C 9S 6C 5S 9C QH 7D AH KS KC 9S 2C 4D 4S 8H TD 9C 3S 7D 9D AS TH 6S 7D 3C 6H 5D KD 2C 5C 9D 9C 2H KC 3D AD 3H QD QS 8D JC 4S 8C 3H 9C 7C AD 5D JC 9D JS AS 5D 9H 5C 7H 6S 6C QC JC QD 9S JC QS JH 2C 6S 9C QC 3D 4S TC 4H 5S 8D 3D 4D 2S KC 2H JS 2C TD 3S TH KD 4D 7H JH JS KS AC 7S 8C 9S 2D 8S 7D 5C AD 9D AS 8C 7H 2S 6C TH 3H 4C 3S 8H AC KD 5H JC 8H JD 2D 4H TD JH 5C 3D AS QH KS 7H JD 8S 5S 6D 5H 9S 6S TC QS JC 5C 5D 9C TH 8C 5H 3S JH 9H 2S 2C 6S 7S AS KS 8C QD JC QS TC QC 4H AC KH 6C TC 5H 7D JH 4H 2H 8D JC KS 4D 5S 9C KH KD 9H 5C TS 3D 7D 2D 5H AS TC 4D 8C 2C TS 9D 3H 8D 6H 8D 2D 9H JD 6C 4S 5H 5S 6D AD 9C JC 7D 6H 9S 6D JS 9H 3C AD JH TC QS 4C 5D 9S 7C 9C AH KD 6H 2H TH 8S QD KS 9D 9H AS 4H 8H 8D 5H 6C AH 5S AS AD 8S QS 5D 4S 2H TD KS 5H AC 3H JC 9C 7D QD KD AC 6D 5H QH 6H 5S KC AH QH 2H 7D QS 3H KS 7S JD 6C 8S 3H 6D KS QD 5D 5C 8H TC 9H 4D 4S 6S 9D KH QC 4H 6C JD TD 2D QH 4S 6H JH KD 3C QD 8C 4S 6H 7C QD 9D AS AH 6S AD 3C 2C KC TH 6H 8D AH 5C 6D 8S 5D TD TS 7C AD JC QD 9H 3C KC 7H 5D 4D 5S 8H 4H 7D 3H JD KD 2D JH TD 6H QS 4S KD 5C 8S 7D 8H AC 3D AS 8C TD 7H KH 5D 6C JD 9D KS 7C 6D QH TC JD KD AS KC JH 8S 5S 7S 7D AS 2D 3D AD 2H 2H 5D AS 3C QD KC 6H 9H 9S 2C 9D 5D TH 4C JH 3H 8D TC 8H 9H 6H KD 2C TD 2H 6C 9D 2D JS 8C KD 7S 3C 7C AS QH TS AD 8C 2S QS 8H 6C JS 4C 9S QC AD TD TS 2H 7C TS TC 8C 3C 9H 2D 6D JC TC 2H 8D JH KS 6D 3H TD TH 8H 9D TD 9H QC 5D 6C 8H 8C KC TS 2H 8C 3D AH 4D TH TC 7D 8H KC TS 5C 2D 8C 6S KH AH 5H 6H KC 5S 5D AH TC 4C JD 8D 6H 8C 6C KC QD 3D 8H 2D JC 9H 4H AD 2S TD 6S 7D JS KD 4H QS 2S 3S 8C 4C 9H JH TS 3S 4H QC 5S 9S 9C 2C KD 9H JS 9S 3H JC TS 5D AC AS 2H 5D AD 5H JC 7S TD JS 4C 2D 4S 8H 3D 7D 2C AD KD 9C TS 7H QD JH 5H JS AC 3D TH 4C 8H 6D KH KC QD 5C AD 7C 2D 4H AC 3D 9D TC 8S QD 2C JC 4H JD AH 6C TD 5S TC 8S AH 2C 5D AS AC TH 7S 3D AS 6C 4C 7H 7D 4H AH 5C 2H KS 6H 7S 4H 5H 3D 3C 7H 3C 9S AC 7S QH 2H 3D 6S 3S 3H 2D 3H AS 2C 6H TC JS 6S 9C 6C QH KD QD 6D AC 6H KH 2C TS 8C 8H 7D 3S 9H 5D 3H 4S QC 9S 5H 2D 9D 7H 6H 3C 8S 5H 4D 3S 4S KD 9S 4S TC 7S QC 3S 8S 2H 7H TC 3D 8C 3H 6C 2H 6H KS KD 4D KC 3D 9S 3H JS 4S 8H 2D 6C 8S 6H QS 6C TC QD 9H 7D 7C 5H 4D TD 9D 8D 6S 6C TC 5D TS JS 8H 4H KC JD 9H TC 2C 6S 5H 8H AS JS 9C 5C 6S 9D JD 8H KC 4C 6D 4D 8D 8S 6C 7C 6H 7H 8H 5C KC TC 3D JC 6D KS 9S 6H 7S 9C 2C 6C 3S KD 5H TS 7D 9H 9S 6H KH 3D QD 4C 6H TS AC 3S 5C 2H KD 4C AS JS 9S 7C TS 7H 9H JC KS 4H 8C JD 3H 6H AD 9S 4S 5S KS 4C 2C 7D 3D AS 9C 2S QS KC 6C 8S 5H 3D 2S AC 9D 6S 3S 4D TD QD TH 7S TS 3D AC 7H 6C 5D QC TC QD AD 9C QS 5C 8D KD 3D 3C 9D 8H AS 3S 7C 8S JD 2D 8D KC 4C TH AC QH JS 8D 7D 7S 9C KH 9D 8D 4C JH 2C 2S QD KD TS 4H 4D 6D 5D 2D JH 3S 8S 3H TC KH AD 4D 2C QS 8C KD JH JD AH 5C 5C 6C 5H 2H JH 4H KS 7C TC 3H 3C 4C QC 5D JH 9C QD KH 8D TC 3H 9C JS 7H QH AS 7C 9H 5H JC 2D 5S QD 4S 3C KC 6S 6C 5C 4C 5D KH 2D TS 8S 9C AS 9S 7C 4C 7C AH 8C 8D 5S KD QH QS JH 2C 8C 9D AH 2H AC QC 5S 8H 7H 2C QD 9H 5S QS QC 9C 5H JC TH 4H 6C 6S 3H 5H 3S 6H KS 8D AC 7S AC QH 7H 8C 4S KC 6C 3D 3S TC 9D 3D JS TH AC 5H 3H 8S 3S TC QD KH JS KS 9S QC 8D AH 3C AC 5H 6C KH 3S 9S JH 2D QD AS 8C 6C 4D 7S 7H 5S JC 6S 9H 4H JH AH 5S 6H 9S AD 3S TH 2H 9D 8C 4C 8D 9H 7C QC AD 4S 9C KC 5S 9D 6H 4D TC 4C JH 2S 5D 3S AS 2H 6C 7C KH 5C AD QS TH JD 8S 3S 4S 7S AH AS KC JS 2S AD TH JS KC 2S 7D 8C 5C 9C TS 5H 9D 7S 9S 4D TD JH JS KH 6H 5D 2C JD JS JC TH 2D 3D QD 8C AC 5H 7S KH 5S 9D 5D TD 4S 6H 3C 2D 4S 5D AC 8D 4D 7C AD AS AH 9C 6S TH TS KS 2C QC AH AS 3C 4S 2H 8C 3S JC 5C 7C 3H 3C KH JH 7S 3H JC 5S 6H 4C 2S 4D KC 7H 4D 7C 4H 9S 8S 6S AD TC 6C JC KH QS 3S TC 4C 8H 8S AC 3C TS QD QS TH 3C TS 7H 7D AH TD JC TD JD QC 4D 9S 7S TS AD 7D AC AH 7H 4S 6D 7C 2H 9D KS JC TD 7C AH JD 4H 6D QS TS 2H 2C 5C TC KC 8C 9S 4C JS 3C JC 6S AH AS 7D QC 3D 5S JC JD 9D TD KH TH 3C 2S 6H AH AC 5H 5C 7S 8H QC 2D AC QD 2S 3S JD QS 6S 8H KC 4H 3C 9D JS 6H 3S 8S AS 8C 7H KC 7D JD 2H JC QH 5S 3H QS 9H TD 3S 8H 7S AC 5C 6C AH 7C 8D 9H AH JD TD QS 7D 3S 9C 8S AH QH 3C JD KC 4S 5S 5D TD KS 9H 7H 6S JH TH 4C 7C AD 5C 2D 7C KD 5S TC 9D 6S 6C 5D 2S TH KC 9H 8D 5H 7H 4H QC 3D 7C AS 6S 8S QC TD 4S 5C TH QS QD 2S 8S 5H TH QC 9H 6S KC 7D 7C 5C 7H KD AH 4D KH 5C 4S 2D KC QH 6S 2C TD JC AS 4D 6C 8C 4H 5S JC TC JD 5S 6S 8D AS 9D AD 3S 6D 6H 5D 5S TC 3D 7D QS 9D QD 4S 6C 8S 3S 7S AD KS 2D 7D 7C KC QH JC AC QD 5D 8D QS 7H 7D JS AH 8S 5H 3D TD 3H 4S 6C JH 4S QS 7D AS 9H JS KS 6D TC 5C 2D 5C 6H TC 4D QH 3D 9H 8S 6C 6D 7H TC TH 5S JD 5C 9C KS KD 8D TD QH 6S 4S 6C 8S KC 5C TC 5S 3D KS AC 4S 7D QD 4C TH 2S TS 8H 9S 6S 7S QH 3C AH 7H 8C 4C 8C TS JS QC 3D 7D 5D 7S JH 8S 7S 9D QC AC 7C 6D 2H JH KC JS KD 3C 6S 4S 7C AH QC KS 5H KS 6S 4H JD QS TC 8H KC 6H AS KH 7C TC 6S TD JC 5C 7D AH 3S 3H 4C 4H TC TH 6S 7H 6D 9C QH 7D 5H 4S 8C JS 4D 3D 8S QH KC 3H 6S AD 7H 3S QC 8S 4S 7S JS 3S JD KH TH 6H QS 9C 6C 2D QD 4S QH 4D 5H KC 7D 6D 8D TH 5S TD AD 6S 7H KD KH 9H 5S KC JC 3H QC AS TS 4S QD KS 9C 7S KC TS 6S QC 6C TH TC 9D 5C 5D KD JS 3S 4H KD 4C QD 6D 9S JC 9D 8S JS 6D 4H JH 6H 6S 6C KS KH AC 7D 5D TC 9S KH 6S QD 6H AS AS 7H 6D QH 8D TH 2S KH 5C 5H 4C 7C 3D QC TC 4S KH 8C 2D JS 6H 5D 7S 5H 9C 9H JH 8S TH 7H AS JS 2S QD KH 8H 4S AC 8D 8S 3H 4C TD KD 8C JC 5C QS 2D JD TS 7D 5D 6C 2C QS 2H 3C AH KS 4S 7C 9C 7D JH 6C 5C 8H 9D QD 2S TD 7S 6D 9C 9S QS KH QH 5C JC 6S 9C QH JH 8D 7S JS KH 2H 8D 5H TH KC 4D 4S 3S 6S 3D QS 2D JD 4C TD 7C 6D TH 7S JC AH QS 7S 4C TH 9D TS AD 4D 3H 6H 2D 3H 7D JD 3D AS 2S 9C QC 8S 4H 9H 9C 2C 7S JH KD 5C 5D 6H TC 9H 8H JC 3C 9S 8D KS AD KC TS 5H JD QS QH QC 8D 5D KH AH 5D AS 8S 6S 4C AH QC QD TH 7H 3H 4H 7D 6S 4S 9H AS 8H JS 9D JD 8C 2C 9D 7D 5H 5S 9S JC KD KD 9C 4S QD AH 7C AD 9D AC TD 6S 4H 4S 9C 8D KS TC 9D JH 7C 5S JC 5H 4S QH AC 2C JS 2S 9S 8C 5H AS QD AD 5C 7D 8S QC TD JC 4C 8D 5C KH QS 4D 6H 2H 2C TH 4S 2D KC 3H QD AC 7H AD 9D KH QD AS 8H TH KC 8D 7S QH 8C JC 6C 7D 8C KH AD QS 2H 6S 2D JC KH 2D 7D JS QC 5H 4C 5D AD TS 3S AD 4S TD 2D TH 6S 9H JH 9H 2D QS 2C 4S 3D KH AS AC 9D KH 6S 8H 4S KD 7D 9D TS QD QC JH 5H AH KS AS AD JC QC 5S KH 5D 7D 6D KS KD 3D 7C 4D JD 3S AC JS 8D 5H 9C 3H 4H 4D TS 2C 6H KS KH 9D 7C 2S 6S 8S 2H 3D 6H AC JS 7S 3S TD 8H 3H 4H TH 9H TC QC KC 5C KS 6H 4H AC 8S TC 7D QH 4S JC TS 6D 6C AC KH QH 7D 7C JH QS QD TH 3H 5D KS 3D 5S 8D JS 4C 2C KS 7H 9C 4H 5H 8S 4H TD 2C 3S QD QC 3H KC QC JS KD 9C AD 5S 9D 7D 7H TS 8C JC KH 7C 7S 6C TS 2C QD TH 5S 9D TH 3C 7S QH 8S 9C 2H 5H 5D 9H 6H 2S JS KH 3H 7C 2H 5S JD 5D 5S 2C TC 2S 6S 6C 3C 8S 4D KH 8H 4H 2D KS 3H 5C 2S 9H 3S 2D TD 7H 8S 6H JD KC 9C 8D 6S QD JH 7C 9H 5H 8S 8H TH TD QS 7S TD 7D TS JC KD 7C 3C 2C 3C JD 8S 4H 2D 2S TD AS 4D AC AH KS 6C 4C 4S 7D 8C 9H 6H AS 5S 3C 9S 2C QS KD 4D 4S AC 5D 2D TS 2C JS KH QH 5D 8C AS KC KD 3H 6C TH 8S 7S KH 6H 9S AC 6H 7S 6C QS AH 2S 2H 4H 5D 5H 5H JC QD 2C 2S JD AS QC 6S 7D 6C TC AS KD 8H 9D 2C 7D JH 9S 2H 4C 6C AH 8S TD 3H TH 7C TS KD 4S TS 6C QH 8D 9D 9C AH 7D 6D JS 5C QD QC 9C 5D 8C 2H KD 3C QH JH AD 6S AH KC 8S 6D 6H 3D 7C 4C 7S 5S 3S 6S 5H JC 3C QH 7C 5H 3C 3S 8C TS 4C KD 9C QD 3S 7S 5H 7H QH JC 7C 8C KD 3C KD KH 2S 4C TS AC 6S 2C 7C 2C KH 3C 4C 6H 4D 5H 5S 7S QD 4D 7C 8S QD TS 9D KS 6H KD 3C QS 4D TS 7S 4C 3H QD 8D 9S TC TS QH AC 6S 3C 9H 9D QS 8S 6H 3S 7S 5D 4S JS 2D 6C QH 6S TH 4C 4H AS JS 5D 3D TS 9C AC 8S 6S 9C 7C 3S 5C QS AD AS 6H 3C 9S 8C 7H 3H 6S 7C AS 9H JD KH 3D 3H 7S 4D 6C 7C AC 2H 9C TH 4H 5S 3H AC TC TH 9C 9H 9S 8D 8D 9H 5H 4D 6C 2H QD 6S 5D 3S 4C 5C JD QS 4D 3H TH AC QH 8C QC 5S 3C 7H AD 4C KS 4H JD 6D QS AH 3H KS 9H 2S JS JH 5H 2H 2H 5S TH 6S TS 3S KS 3C 5H JS 2D 9S 7H 3D KC JH 6D 7D JS TD AC JS 8H 2C 8C JH JC 2D TH 7S 5D 9S 8H 2H 3D TC AH JC KD 9C 9D QD JC 2H 6D KH TS 9S QH TH 2C 8D 4S JD 5H 3H TH TC 9C KC AS 3D 9H 7D 4D TH KH 2H 7S 3H 4H 7S KS 2S JS TS 8S 2H QD 8D 5S 6H JH KS 8H 2S QC AC 6S 3S JC AS AD QS 8H 6C KH 4C 4D QD 2S 3D TS TD 9S KS 6S QS 5C 8D 3C 6D 4S QC KC JH QD TH KH AD 9H AH 4D KS 2S 8D JH JC 7C QS 2D 6C TH 3C 8H QD QH 2S 3S KS 6H 5D 9S 4C TS TD JS QD 9D JD 5H 8H KH 8S KS 7C TD AD 4S KD 2C 7C JC 5S AS 6C 7D 8S 5H 9C 6S QD 9S TS KH QS 5S QH 3C KC 7D 3H 3C KD 5C AS JH 7H 6H JD 9D 5C 9H KC 8H KS 4S AD 4D 2S 3S JD QD 8D 2S 7C 5S 6S 5H TS 6D 9S KC TD 3S 6H QD JD 5C 8D 5H 9D TS KD 8D 6H TD QC 4C 7D 6D 4S JD 9D AH 9S AS TD 9H QD 2D 5S 2H 9C 6H 9S TD QC 7D TC 3S 2H KS TS 2C 9C 8S JS 9D 7D 3C KC 6D 5D 6C 6H 8S AS 7S QS JH 9S 2H 8D 4C 8H 9H AD TH KH QC AS 2S JS 5C 6H KD 3H 7H 2C QD 8H 2S 8D 3S 6D AH 2C TC 5C JD JS TS 8S 3H 5D TD KC JC 6H 6S QS TC 3H 5D AH JC 7C 7D 4H 7C 5D 8H 9C 2H 9H JH KH 5S 2C 9C 7H 6S TH 3S QC QD 4C AC JD 2H 5D 9S 7D KC 3S QS 2D AS KH 2S 4S 2H 7D 5C TD TH QH 9S 4D 6D 3S TS 6H 4H KS 9D 8H 5S 2D 9H KS 4H 3S 5C 5D KH 6H 6S JS KC AS 8C 4C JC KH QC TH QD AH 6S KH 9S 2C 5H TC 3C 7H JC 4D JD 4S 6S 5S 8D 7H 7S 4D 4C 2H 7H 9H 5D KH 9C 7C TS TC 7S 5H 4C 8D QC TS 4S 9H 3D AD JS 7C 8C QS 5C 5D 3H JS AH KC 4S 9D TS JD 8S QS TH JH KH 2D QD JS JD QC 5D 6S 9H 3S 2C 8H 9S TS 2S 4C AD 7H JC 5C 2D 6D 4H 3D 7S JS 2C 4H 8C AD QD 9C 3S TD JD TS 4C 6H 9H 7D QD 6D 3C AS AS 7C 4C 6S 5D 5S 5C JS QC 4S KD 6S 9S 7C 3C 5S 7D JH QD JS 4S 7S JH 2C 8S 5D 7H 3D QH AD TD 6H 2H 8D 4H 2D 7C AD KH 5D TS 3S 5H 2C QD AH 2S 5C KH TD KC 4D 8C 5D AS 6C 2H 2S 9H 7C KD JS QC TS QS KH JH 2C 5D AD 3S 5H KC 6C 9H 3H 2H AD 7D 7S 7S JS JH KD 8S 7D 2S 9H 7C 2H 9H 2D 8D QC 6S AD AS 8H 5H 6C 2S 7H 6C 6D 7D 8C 5D 9D JC 3C 7C 9C 7H JD 2H KD 3S KH AD 4S QH AS 9H 4D JD KS KD TS KH 5H 4C 8H 5S 3S 3D 7D TD AD 7S KC JS 8S 5S JC 8H TH 9C 4D 5D KC 7C 5S 9C QD 2C QH JS 5H 8D KH TD 2S KS 3D AD KC 7S TC 3C 5D 4C 2S AD QS 6C 9S QD TH QH 5C 8C AD QS 2D 2S KC JD KS 6C JC 8D 4D JS 2H 5D QD 7S 7D QH TS 6S 7H 3S 8C 8S 9D QS 8H 6C 9S 4S TC 2S 5C QD 4D QS 6D TH 6S 3S 5C 9D 6H 8D 4C 7D TC 7C TD AH 6S AS 7H 5S KD 3H 5H AC 4C 8D 8S AH KS QS 2C AD 6H 7D 5D 6H 9H 9S 2H QS 8S 9C 5D 2D KD TS QC 5S JH 7D 7S TH 9S 9H AC 7H 3H 6S KC 4D 6D 5C 4S QD TS TD 2S 7C QD 3H JH 9D 4H 7S 7H KS 3D 4H 5H TC 2S AS 2D 6D 7D 8H 3C 7H TD 3H AD KC TH 9C KH TC 4C 2C 9S 9D 9C 5C 2H JD 3C 3H AC TS 5D AD 8D 6H QC 6S 8C 2S TS 3S JD 7H 8S QH 4C 5S 8D AC 4S 6C 3C KH 3D 7C 2D 8S 2H 4H 6C 8S TH 2H 4S 8H 9S 3H 7S 7C 4C 9C 2C 5C AS 5D KD 4D QH 9H 4H TS AS 7D 8D 5D 9S 8C 2H QC KD AC AD 2H 7S AS 3S 2D 9S 2H QC 8H TC 6D QD QS 5D KH 3C TH JD QS 4C 2S 5S AD 7H 3S AS 7H JS 3D 6C 3S 6D AS 9S AC QS 9C TS AS 8C TC 8S 6H 9D 8D 6C 4D JD 9C KC 7C 6D KS 3S 8C AS 3H 6S TC 8D TS 3S KC 9S 7C AS 8C QC 4H 4S 8S 6C 3S TC AH AC 4D 7D 5C AS 2H 6S TS QC AD TC QD QC 8S 4S TH 3D AH TS JH 4H 5C 2D 9S 2C 3H 3C 9D QD QH 7D KC 9H 6C KD 7S 3C 4D AS TC 2D 3D JS 4D 9D KS 7D TH QC 3H 3C 8D 5S 2H 9D 3H 8C 4C 4H 3C TH JC TH 4S 6S JD 2D 4D 6C 3D 4C TS 3S 2D 4H AC 2C 6S 2H JH 6H TD 8S AD TC AH AC JH 9S 6S 7S 6C KC 4S JD 8D 9H 5S 7H QH AH KD 8D TS JH 5C 5H 3H AD AS JS 2D 4H 3D 6C 8C 7S AD 5D 5C 8S TD 5D 7S 9C 4S 5H 6C 8C 4C 8S JS QH 9C AS 5C QS JC 3D QC 7C JC 9C KH JH QS QC 2C TS 3D AD 5D JH AC 5C 9S TS 4C JD 8C KS KC AS 2D KH 9H 2C 5S 4D 3D 6H TH AH 2D 8S JC 3D 8C QH 7S 3S 8H QD 4H JC AS KH KS 3C 9S 6D 9S QH 7D 9C 4S AC 7H KH 4D KD AH AD TH 6D 9C 9S KD KS QH 4H QD 6H 9C 7C QS 6D 6S 9D 5S JH AH 8D 5H QD 2H JC KS 4H KH 5S 5C 2S JS 8D 9C 8C 3D AS KC AH JD 9S 2H QS 8H 5S 8C TH 5C 4C QC QS 8C 2S 2C 3S 9C 4C KS KH 2D 5D 8S AH AD TD 2C JS KS 8C TC 5S 5H 8H QC 9H 6H JD 4H 9S 3C JH 4H 9H AH 4S 2H 4C 8D AC 8S TH 4D 7D 6D QD QS 7S TC 7C KH 6D 2D JD 5H JS QD JH 4H 4S 9C 7S JH 4S 3S TS QC 8C TC 4H QH 9D 4D JH QS 3S 2C 7C 6C 2D 4H 9S JD 5C 5H AH 9D TS 2D 4C KS JH TS 5D 2D AH JS 7H AS 8D JS AH 8C AD KS 5S 8H 2C 6C TH 2H 5D AD AC KS 3D 8H TS 6H QC 6D 4H TS 9C 5H JS JH 6S JD 4C JH QH 4H 2C 6D 3C 5D 4C QS KC 6H 4H 6C 7H 6S 2S 8S KH QC 8C 3H 3D 5D KS 4H TD AD 3S 4D TS 5S 7C 8S 7D 2C KS 7S 6C 8C JS 5D 2H 3S 7C 5C QD 5H 6D 9C 9H JS 2S KD 9S 8D TD TS AC 8C 9D 5H QD 2S AC 8C 9H KS 7C 4S 3C KH AS 3H 8S 9C JS QS 4S AD 4D AS 2S TD AD 4D 9H JC 4C 5H QS 5D 7C 4H TC 2D 6C JS 4S KC 3S 4C 2C 5D AC 9H 3D JD 8S QS QH 2C 8S 6H 3C QH 6D TC KD AC AH QC 6C 3S QS 4S AC 8D 5C AD KH 5S 4C AC KH AS QC 2C 5C 8D 9C 8H JD 3C KH 8D 5C 9C QD QH 9D 7H TS 2C 8C 4S TD JC 9C 5H QH JS 4S 2C 7C TH 6C AS KS 7S JD JH 7C 9H 7H TC 5H 3D 6D 5D 4D 2C QD JH 2H 9D 5S 3D TD AD KS JD QH 3S 4D TH 7D 6S QS KS 4H TC KS 5S 8D 8H AD 2S 2D 4C JH 5S JH TC 3S 2D QS 9D 4C KD 9S AC KH 3H AS 9D KC 9H QD 6C 6S 9H 7S 3D 5C 7D KC TD 8H 4H 6S 3C 7H 8H TC QD 4D 7S 6S QH 6C 6D AD 4C QD 6C 5D 7D 9D KS TS JH 2H JD 9S 7S TS KH 8D 5D 8H 2D 9S 4C 7D 9D 5H QD 6D AC 6S 7S 6D JC QD JH 4C 6S QS 2H 7D 8C TD JH KD 2H 5C QS 2C JS 7S TC 5H 4H JH QD 3S 5S 5D 8S KH KS KH 7C 2C 5D JH 6S 9C 6D JC 5H AH JD 9C JS KC 2H 6H 4D 5S AS 3C TH QC 6H 9C 8S 8C TD 7C KC 2C QD 9C KH 4D 7S 3C TS 9H 9C QC 2S TS 8C TD 9S QD 3S 3C 4D 9D TH JH AH 6S 2S JD QH JS QD 9H 6C KD 7D 7H 5D 6S 8H AH 8H 3C 4S 2H 5H QS QH 7S 4H AC QS 3C 7S 9S 4H 3S AH KS 9D 7C AD 5S 6S 2H 2D 5H TC 4S 3C 8C QH TS 6S 4D JS KS JH AS 8S 6D 2C 8S 2S TD 5H AS TC TS 6C KC KC TS 8H 2H 3H 7C 4C 5S TH TD KD AD KH 7H 7S 5D 5H 5S 2D 9C AD 9S 3D 7S 8C QC 7C 9C KD KS 3C QC 9S 8C 4D 5C AS QD 6C 2C 2H KC 8S JD 7S AC 8D 5C 2S 4D 9D QH 3D 2S TC 3S KS 3C 9H TD KD 6S AC 2C 7H 5H 3S 6C 6H 8C QH TC 8S 6S KH TH 4H 5D TS 4D 8C JS 4H 6H 2C 2H 7D AC QD 3D QS KC 6S 2D 5S 4H TD 3H JH 4C 7S 5H 7H 8H KH 6H QS TH KD 7D 5H AD KD 7C KH 5S TD 6D 3C 6C 8C 9C 5H JD 7C KC KH 7H 2H 3S 7S 4H AD 4D 8S QS TH 3D 7H 5S 8D TC KS KD 9S 6D AD JD 5C 2S 7H 8H 6C QD 2H 6H 9D TC 9S 7C 8D 6D 4C 7C 6C 3C TH KH JS JH 5S 3S 8S JS 9H AS AD 8H 7S KD JH 7C 2C KC 5H AS AD 9C 9S JS AD AC 2C 6S QD 7C 3H TH KS KD 9D JD 4H 8H 4C KH 7S TS 8C KC 3S 5S 2H 7S 6H 7D KS 5C 6D AD 5S 8C 9H QS 7H 7S 2H 6C 7D TD QS 5S TD AC 9D KC 3D TC 2D 4D TD 2H 7D JD QD 4C 7H 5D KC 3D 4C 3H 8S KD QH 5S QC 9H TC 5H 9C QD TH 5H TS 5C 9H AH QH 2C 4D 6S 3C AC 6C 3D 2C 2H TD TH AC 9C 5D QC 4D AD 8D 6D 8C KC AD 3C 4H AC 8D 8H 7S 9S TD JC 4H 9H QH JS 2D TH TD TC KD KS 5S 6S 9S 8D TH AS KH 5H 5C 8S JD 2S 9S 6S 5S 8S 5D 7S 7H 9D 5D 8C 4C 9D AD TS 2C 7D KD TC 8S QS 4D KC 5C 8D 4S KH JD KD AS 5C AD QH 7D 2H 9S 7H 7C TC 2S 8S JD KH 7S 6C 6D AD 5D QC 9H 6H 3S 8C 8H AH TC 4H JS TD 2C TS 4D 7H 2D QC 9C 5D TH 7C 6C 8H QC 5D TS JH 5C 5H 9H 4S 2D QC 7H AS JS 8S 2H 4C 4H 8D JS 6S AC KD 3D 3C 4S 7H TH KC QH KH 6S QS 5S 4H 3C QD 3S 3H 7H AS KH 8C 4H 9C 5S 3D 6S TS 9C 7C 3H 5S QD 2C 3D AD AC 5H JH TD 2D 4C TS 3H KH AD 3S 7S AS 4C 5H 4D 6S KD JC 3C 6H 2D 3H 6S 8C 2D TH 4S AH QH AD 5H 7C 2S 9H 7H KC 5C 6D 5S 3H JC 3C TC 9C 4H QD TD JH 6D 9H 5S 7C 6S 5C 5D 6C 4S 7H 9H 6H AH AD 2H 7D KC 2C 4C 2S 9S 7H 3S TH 4C 8S 6S 3S AD KS AS JH TD 5C TD 4S 4D AD 6S 5D TC 9C 7D 8H 3S 4D 4S 5S 6H 5C AC 3H 3D 9H 3C AC 4S QS 8S 9D QH 5H 4D JC 6C 5H TS AC 9C JD 8C 7C QD 8S 8H 9C JD 2D QC QH 6H 3C 8D KS JS 2H 6H 5H QH QS 3H 7C 6D TC 3H 4S 7H QC 2H 3S 8C JS KH AH 8H 5S 4C 9H JD 3H 7S JC AC 3C 2D 4C 5S 6C 4S QS 3S JD 3D 5H 2D TC AH KS 6D 7H AD 8C 6H 6C 7S 3C JD 7C 8H KS KH AH 6D AH 7D 3H 8H 8S 7H QS 5H 9D 2D JD AC 4H 7S 8S 9S KS AS 9D QH 7S 2C 8S 5S JH QS JC AH KD 4C AH 2S 9H 4H 8D TS TD 6H QH JD 4H JC 3H QS 6D 7S 9C 8S 9D 8D 5H TD 4S 9S 4C 8C 8D 7H 3H 3D QS KH 3S 2C 2S 3C 7S TD 4S QD 7C TD 4D 5S KH AC AS 7H 4C 6C 2S 5H 6D JD 9H QS 8S 2C 2H TD 2S TS 6H 9H 7S 4H JC 4C 5D 5S 2C 5H 7D 4H 3S QH JC JS 6D 8H 4C QH 7C QD 3S AD TH 8S 5S TS 9H TC 2S TD JC 7D 3S 3D TH QH 7D 4C 8S 5C JH 8H 6S 3S KC 3H JC 3H KH TC QH TH 6H 2C AC 5H QS 2H 9D 2C AS 6S 6C 2S 8C 8S 9H 7D QC TH 4H KD QS AC 7S 3C 4D JH 6S 5S 8H KS 9S QC 3S AS JD 2D 6S 7S TC 9H KC 3H 7D KD 2H KH 7C 4D 4S 3H JS QD 7D KC 4C JC AS 9D 3C JS 6C 8H QD 4D AH JS 3S 6C 4C 3D JH 6D 9C 9H 9H 2D 8C 7H 5S KS 6H 9C 2S TC 6C 8C AD 7H 6H 3D KH AS 5D TH KS 8C 3S TS 8S 4D 5S 9S 6C 4H 9H 4S 4H 5C 7D KC 2D 2H 9D JH 5C JS TC 9D 9H 5H 7S KH JC 6S 7C 9H 8H 4D JC KH JD 2H TD TC 8H 6C 2H 2C KH 6H 9D QS QH 5H AC 7D 2S 3D QD JC 2D 8D JD JH 2H JC 2D 7H 2C 3C 8D KD TD 4H 3S 4H 6D 8D TS 3H TD 3D 6H TH JH JC 3S AC QH 9H 7H 8S QC 2C 7H TD QS 4S 8S 9C 2S 5D 4D 2H 3D TS 3H 2S QC 8H 6H KC JC KS 5D JD 7D TC 8C 6C 9S 3D 8D AC 8H 6H JH 6C 5D 8D 8S 4H AD 2C 9D 4H 2D 2C 3S TS AS TC 3C 5D 4D TH 5H KS QS 6C 4S 2H 3D AD 5C KC 6H 2C 5S 3C 4D 2D 9H 9S JD 4C 3H TH QH 9H 5S AH 8S AC 7D 9S 6S 2H TD 9C 4H 8H QS 4C 3C 6H 5D 4H 8C 9C KC 6S QD QS 3S 9H KD TC 2D JS 8C 6S 4H 4S 2S 4C 8S QS 6H KH 3H TH 8C 5D 2C KH 5S 3S 7S 7H 6C 9D QD 8D 8H KS AC 2D KH TS 6C JS KC 7H 9C KS 5C TD QC AH 6C 5H 9S 7C 5D 4D 3H 4H 6S 7C 7S AH QD TD 2H 7D QC 6S TC TS AH 7S 9D 3H TH 5H QD 9S KS 7S 7C 6H 8C TD TH 2D 4D QC 5C 7D JD AH 9C 4H 4H 3H AH 8D 6H QC QH 9H 2H 2C 2D AD 4C TS 6H 7S TH 4H QS TD 3C KD 2H 3H QS JD TC QC 5D 8H KS JC QD TH 9S KD 8D 8C 2D 9C 3C QD KD 6D 4D 8D AH AD QC 8S 8H 3S 9D 2S 3H KS 6H 4C 7C KC TH 9S 5C 3D 7D 6H AC 7S 4D 2C 5C 3D JD 4D 2D 6D 5H 9H 4C KH AS 7H TD 6C 2H 3D QD KS 4C 4S JC 3C AC 7C JD JS 8H 9S QC 5D JD 6S 5S 2H AS 8C 7D 5H JH 3D 8D TC 5S 9S 8S 3H JC 5H 7S AS 5C TD 3D 7D 4H 8D 7H 4D 5D JS QS 9C KS TD 2S 8S 5C 2H 4H AS TH 7S 4H 7D 3H JD KD 5D 2S KC JD 7H 4S 8H 4C JS 6H QH 5S 4H 2C QS 8C 5S 3H QC 2S 6C QD AD 8C 3D JD TC 4H 2H AD 5S AC 2S 5D 2C JS 2D AD 9D 3D 4C 4S JH 8D 5H 5D 6H 7S 4D KS 9D TD JD 3D 6D 9C 2S AS 7D 5S 5C 8H JD 7C 8S 3S 6S 5H JD TC AD 7H 7S 2S 9D TS 4D AC 8D 6C QD JD 3H 9S KH 2C 3C AC 3D 5H 6H 8D 5D KS 3D 2D 6S AS 4C 2S 7C 7H KH AC 2H 3S JC 5C QH 4D 2D 5H 7S TS AS JD 8C 6H JC 8S 5S 2C 5D 7S QH 7H 6C QC 8H 2D 7C JD 2S 2C QD 2S 2H JC 9C 5D 2D JD JH 7C 5C 9C 8S 7D 6D 8D 6C 9S JH 2C AD 6S 5H 3S KS 7S 9D KH 4C 7H 6C 2C 5C TH 9D 8D 3S QC AH 5S KC 6H TC 5H 8S TH 6D 3C AH 9C KD 4H AD TD 9S 4S 7D 6H 5D 7H 5C 5H 6D AS 4C KD KH 4H 9D 3C 2S 5C 6C JD QS 2H 9D 7D 3H AC 2S 6S 7S JS QD 5C QS 6H AD 5H TH QC 7H TC 3S 7C 6D KC 3D 4H 3D QC 9S 8H 2C 3S JC KS 5C 4S 6S 2C 6H 8S 3S 3D 9H 3H JS 4S 8C 4D 2D 8H 9H 7D 9D AH TS 9S 2C 9H 4C 8D AS 7D 3D 6D 5S 6S 4C 7H 8C 3H 5H JC AH 9D 9C 2S 7C 5S JD 8C 3S 3D 4D 7D 6S 3C KC 4S 5D 7D 3D JD 7H 3H 4H 9C 9H 4H 4D TH 6D QD 8S 9S 7S 2H AC 8S 4S AD 8C 2C AH 7D TC TS 9H 3C AD KS TC 3D 8C 8H JD QC 8D 2C 3C 7D 7C JD 9H 9C 6C AH 6S JS JH 5D AS QC 2C JD TD 9H KD 2H 5D 2D 3S 7D TC AH TS TD 8H AS 5D AH QC AC 6S TC 5H KS 4S 7H 4D 8D 9C TC 2H 6H 3H 3H KD 4S QD QH 3D 8H 8C TD 7S 8S JD TC AH JS QS 2D KH KS 4D 3C AD JC KD JS KH 4S TH 9H 2C QC 5S JS 9S KS AS 7C QD 2S JD KC 5S QS 3S 2D AC 5D 9H 8H KS 6H 9C TC AD 2C 6D 5S JD 6C 7C QS KH TD QD 2C 3H 8S 2S QC AH 9D 9H JH TC QH 3C 2S JS 5C 7H 6C 3S 3D 2S 4S QD 2D TH 5D 2C 2D 6H 6D 2S JC QH AS 7H 4H KH 5H 6S KS AD TC TS 7C AC 4S 4H AD 3C 4H QS 8C 9D KS 2H 2D 4D 4S 9D 6C 6D 9C AC 8D 3H 7H KD JC AH 6C TS JD 6D AD 3S 5D QD JC JH JD 3S 7S 8S JS QC 3H 4S JD TH 5C 2C AD JS 7H 9S 2H 7S 8D 3S JH 4D QC AS JD 2C KC 6H 2C AC 5H KD 5S 7H QD JH AH 2D JC QH 8D 8S TC 5H 5C AH 8C 6C 3H JS 8S QD JH 3C 4H 6D 5C 3S 6D 4S 4C AH 5H 5S 3H JD 7C 8D 8H AH 2H 3H JS 3C 7D QC 4H KD 6S 2H KD 5H 8H 2D 3C 8S 7S QD 2S 7S KC QC AH TC QS 6D 4C 8D 5S 9H 2C 3S QD 7S 6C 2H 7C 9D 3C 6C 5C 5S JD JC KS 3S 5D TS 7C KS 6S 5S 2S 2D TC 2H 5H QS AS 7H 6S TS 5H 9S 9D 3C KD 2H 4S JS QS 3S 4H 7C 2S AC 6S 9D 8C JH 2H 5H 7C 5D QH QS KH QC 3S TD 3H 7C KC 8D 5H 8S KH 8C 4H KH JD TS 3C 7H AS QC JS 5S AH 9D 2C 8D 4D 2D 6H 6C KC 6S 2S 6H 9D 3S 7H 4D KH 8H KD 3D 9C TC AC JH KH 4D JD 5H TD 3S 7S 4H 9D AS 4C 7D QS 9S 2S KH 3S 8D 8S KS 8C JC 5C KH 2H 5D 8S QH 2C 4D KC JS QC 9D AC 6H 8S 8C 7C JS JD 6S 4C 9C AC 4S QH 5D 2C 7D JC 8S 2D JS JH 4C JS 4C 7S TS JH KC KH 5H QD 4S QD 8C 8D 2D 6S TD 9D AC QH 5S QH QC JS 3D 3C 5C 4H KH 8S 7H 7C 2C 5S JC 8S 3H QC 5D 2H KC 5S 8D KD 6H 4H QD QH 6D AH 3D 7S KS 6C 2S 4D AC QS 5H TS JD 7C 2D TC 5D QS AC JS QC 6C KC 2C KS 4D 3H TS 8S AD 4H 7S 9S QD 9H QH 5H 4H 4D KH 3S JC AD 4D AC KC 8D 6D 4C 2D KH 2C JD 2C 9H 2D AH 3H 6D 9C 7D TC KS 8C 3H KD 7C 5C 2S 4S 5H AS AH TH JD 4H KD 3H TC 5C 3S AC KH 6D 7H AH 7S QC 6H 2D TD JD AS JH 5D 7H TC 9S 7D JC AS 5S KH 2H 8C AD TH 6H QD KD 9H 6S 6C QH KC 9D 4D 3S JS JH 4H 2C 9H TC 7H KH 4H JC 7D 9S 3H QS 7S AD 7D JH 6C 7H 4H 3S 3H 4D QH JD 2H 5C AS 6C QC 4D 3C TC JH AC JD 3H 6H 4C JC AD 7D 7H 9H 4H TC TS 2C 8C 6S KS 2H JD 9S 4C 3H QS QC 9S 9H 6D KC 9D 9C 5C AD 8C 2C QH TH QD JC 8D 8H QC 2C 2S QD 9C 4D 3S 8D JH QS 9D 3S 2C 7S 7C JC TD 3C TC 9H 3C TS 8H 5C 4C 2C 6S 8D 7C 4H KS 7H 2H TC 4H 2C 3S AS AH QS 8C 2D 2H 2C 4S 4C 6S 7D 5S 3S TH QC 5D TD 3C QS KD KC KS AS 4D AH KD 9H KS 5C 4C 6H JC 7S KC 4H 5C QS TC 2H JC 9S AH QH 4S 9H 3H 5H 3C QD 2H QC JH 8H 5D AS 7H 2C 3D JH 6H 4C 6S 7D 9C JD 9H AH JS 8S QH 3H KS 8H 3S AC QC TS 4D AD 3D AH 8S 9H 7H 3H QS 9C 9S 5H JH JS AH AC 8D 3C JD 2H AC 9C 7H 5S 4D 8H 7C JH 9H 6C JS 9S 7H 8C 9D 4H 2D AS 9S 6H 4D JS JH 9H AD QD 6H 7S JH KH AH 7H TD 5S 6S 2C 8H JH 6S 5H 5S 9D TC 4C QC 9S 7D 2C KD 3H 5H AS QD 7H JS 4D TS QH 6C 8H TH 5H 3C 3H 9C 9D AD KH JS 5D 3H AS AC 9S 5C KC 2C KH 8C JC QS 6D AH 2D KC TC 9D 3H 2S 7C 4D 6D KH KS 8D 7D 9H 2S TC JH AC QC 3H 5S 3S 8H 3S AS KD 8H 4C 3H 7C JH QH TS 7S 6D 7H 9D JH 4C 3D 3S 6C AS 4S 2H 2C 4C 8S 5H KC 8C QC QD 3H 3S 6C QS QC 2D 6S 5D 2C 9D 2H 8D JH 2S 3H 2D 6C 5C 7S AD 9H JS 5D QH 8S TS 2H 7S 6S AD 6D QC 9S 7H 5H 5C 7D KC JD 4H QC 5S 9H 9C 4D 6S KS 2S 4C 7C 9H 7C 4H 8D 3S 6H 5C 8H JS 7S 2D 6H JS TD 4H 4D JC TH 5H KC AC 7C 8D TH 3H 9S 2D 4C KC 4D KD QS 9C 7S 3D KS AD TS 4C 4H QH 9C 8H 2S 7D KS 7H 5D KD 4C 9C 2S 2H JC 6S 6C TC QC JH 5C 7S AC 8H KC 8S 6H QS JC 3D 6S JS 2D JH 8C 4S 6H 8H 6D 5D AD 6H 7D 2S 4H 9H 7C AS AC 8H 5S 3C JS 4S 6D 5H 2S QH 6S 9C 2C 3D 5S 6S 9S 4C QS 8D QD 8S TC 9C 3D AH 9H 5S 2C 7D AD JC 3S 7H TC AS 3C 6S 6D 7S KH KC 9H 3S TC 8H 6S 5H JH 8C 7D AC 2S QD 9D 9C 3S JC 8C KS 8H 5D 4D JS AH JD 6D 9D 8C 9H 9S 8H 3H 2D 6S 4C 4D 8S AD 4S TC AH 9H TS AC QC TH KC 6D 4H 7S 8C 2H 3C QD JS 9D 5S JC AH 2H TS 9H 3H 4D QH 5D 9C 5H 7D 4S JC 3S 8S TH 3H 7C 2H JD JS TS AC 8D 9C 2H TD KC JD 2S 8C 5S AD 2C 3D KD 7C 5H 4D QH QD TC 6H 7D 7H 2C KC 5S KD 6H AH QC 7S QH 6H 5C AC 5H 2C 9C 2D 7C TD 2S 4D 9D AH 3D 7C JD 4H 8C 4C KS TH 3C JS QH 8H 4C AS 3D QS QC 4D 7S 5H JH 6D 7D 6H JS KH 3C QD 8S 7D 2H 2C 7C JC 2S 5H 8C QH 8S 9D TC 2H AD 7C 8D QD 6S 3S 7C AD 9H 2H 9S JD TS 4C 2D 3S AS 4H QC 2C 8H 8S 7S TD TC JH TH TD 3S 4D 4H 5S 5D QS 2C 8C QD QH TC 6D 4S 9S 9D 4H QC 8C JS 9D 6H JD 3H AD 6S TD QC KC 8S 3D 7C TD 7D 8D 9H 4S 3S 6C 4S 3D 9D KD TC KC KS AC 5S 7C 6S QH 3D JS KD 6H 6D 2D 8C JD 2S 5S 4H 8S AC 2D 6S TS 5C 5H 8C 5S 3C 4S 3D 7C 8D AS 3H AS TS 7C 3H AD 7D JC QS 6C 6H 3S 9S 4C AC QH 5H 5D 9H TS 4H 6C 5C 7H 7S TD AD JD 5S 2H 2S 7D 6C KC 3S JD 8D 8S TS QS KH 8S QS 8D 6C TH AC AH 2C 8H 9S 7H TD KH QH 8S 3D 4D AH JD AS TS 3D 2H JC 2S JH KH 6C QC JS KC TH 2D 6H 7S 2S TC 8C 9D QS 3C 9D 6S KH 8H 6D 5D TH 2C 2H 6H TC 7D AD 4D 8S TS 9H TD 7S JS 6D JD JC 2H AC 6C 3D KH 8D KH JD 9S 5D 4H 4C 3H 7S QS 5C 4H JD 5D 3S 3C 4D KH QH QS 7S JD TS 8S QD AH 4C 6H 3S 5S 2C QS 3D JD AS 8D TH 7C 6S QC KS 7S 2H 8C QC 7H AC 6D 2D TH KH 5S 6C 7H KH 7D AH 8C 5C 7S 3D 3C KD AD 7D 6C 4D KS 2D 8C 4S 7C 8D 5S 2D 2S AH AD 2C 9D TD 3C AD 4S KS JH 7C 5C 8C 9C TH AS TD 4D 7C JD 8C QH 3C 5H 9S 3H 9C 8S 9S 6S QD KS AH 5H JH QC 9C 5S 4H 2H TD 7D AS 8C 9D 8C 2C 9D KD TC 7S 3D KH QC 3C 4D AS 4C QS 5S 9D 6S JD QH KS 6D AH 6C 4C 5H TS 9H 7D 3D 5S QS JD 7C 8D 9C AC 3S 6S 6C KH 8H JH 5D 9S 6D AS 6S 3S QC 7H QD AD 5C JH 2H AH 4H AS KC 2C JH 9C 2C 6H 2D JS 5D 9H KC 6D 7D 9D KD TH 3H AS 6S QC 6H AD JD 4H 7D KC 3H JS 3C TH 3D QS 4C 3H 8C QD 5H 6H AS 8H AD JD TH 8S KD 5D QC 7D JS 5S 5H TS 7D KC 9D QS 3H 3C 6D TS 7S AH 7C 4H 7H AH QC AC 4D 5D 6D TH 3C 4H 2S KD 8H 5H JH TC 6C JD 4S 8C 3D 4H JS TD 7S JH QS KD 7C QC KD 4D 7H 6S AD TD TC KH 5H 9H KC 3H 4D 3D AD 6S QD 6H TH 7C 6H TS QH 5S 2C KC TD 6S 7C 4D 5S JD JH 7D AC KD KH 4H 7D 6C 8D 8H 5C JH 8S QD TH JD 8D 7D 6C 7C 9D KD AS 5C QH JH 9S 2C 8C 3C 4C KS JH 2D 8D 4H 7S 6C JH KH 8H 3H 9D 2D AH 6D 4D TC 9C 8D 7H TD KS TH KD 3C JD 9H 8D QD AS KD 9D 2C 2S 9C 8D 3H 5C 7H KS 5H QH 2D 8C 9H 2D TH 6D QD 6C KC 3H 3S AD 4C 4H 3H JS 9D 3C TC 5H QH QC JC 3D 5C 6H 3S 3C JC 5S 7S 2S QH AC 5C 8C 4D 5D 4H 2S QD 3C 3H 2C TD AH 9C KD JS 6S QD 4C QC QS 8C 3S 4H TC JS 3H 7C JC AD 5H 4D 9C KS JC TD 9S TS 8S 9H QD TS 7D AS AC 2C TD 6H 8H AH 6S AD 8C 4S 9H 8D 9D KH 8S 3C QS 4D 2D 7S KH JS JC AD 4C 3C QS 9S 7H KC TD TH 5H JS AC JH 6D AC 2S QS 7C AS KS 6S KH 5S 6D 8H KH 3C QS 2H 5C 9C 9D 6C JS 2C 4C 6H 7D JC AC QD TD 3H 4H QC 8H JD 4C KD KS 5C KC 7S 6D 2D 3H 2S QD 5S 7H AS TH 6S AS 6D 8D 2C 8S TD 8H QD JC AH 9C 9H 2D TD QH 2H 5C TC 3D 8H KC 8S 3D KH 2S TS TC 6S 4D JH 9H 9D QS AC KC 6H 5D 4D 8D AH 9S 5C QS 4H 7C 7D 2H 8S AD JS 3D AC 9S AS 2C 2D 2H 3H JC KH 7H QH KH JD TC KS 5S 8H 4C 8D 2H 7H 3S 2S 5H QS 3C AS 9H KD AD 3D JD 6H 5S 9C 6D AC 9S 3S 3D 5D 9C 2D AC 4S 2S AD 6C 6S QC 4C 2D 3H 6S KC QH QD 2H JH QC 3C 8S 4D 9S 2H 5C 8H QS QD 6D KD 6S 7H 3S KH 2H 5C JC 6C 3S 9S TC 6S 8H 2D AD 7S 8S TS 3C 6H 9C 3H 5C JC 8H QH TD QD 3C JS QD 5D TD 2C KH 9H TH AS 9S TC JD 3D 5C 5H AD QH 9H KC TC 7H 4H 8H 3H TD 6S AC 7C 2S QS 9D 5D 3C JC KS 4D 6C JH 2S 9S 6S 3C 7H TS 4C KD 6D 3D 9C 2D 9H AH AC 7H 2S JH 3S 7C QC QD 9H 3C 2H AC AS 8S KD 8C KH 2D 7S TD TH 6D JD 8D 4D 2H 5S 8S QH KD JD QS JH 4D KC 5H 3S 3C KH QC 6D 8H 3S AH 7D TD 2D 5S 9H QH 4S 6S 6C 6D TS TH 7S 6C 4C 6D QS JS 9C TS 3H 8D 8S JS 5C 7S AS 2C AH 2H AD 5S TC KD 6C 9C 9D TS 2S JC 4H 2C QD QS 9H TC 3H KC KS 4H 3C AD TH KH 9C 2H KD 9D TC 7S KC JH 2D 7C 3S KC AS 8C 5D 9C 9S QH 3H 2D 8C TD 4C 2H QC 5D TC 2C 7D KS 4D 6C QH TD KH 5D 7C AD 8D 2S 9S 8S 4C 8C 3D 6H QD 7C 7H 6C 8S QH 5H TS 5C 3C 4S 2S 2H 8S 6S 2H JC 3S 3H 9D 8C 2S 7H QC 2C 8H 9C AC JD 4C 4H 6S 3S 3H 3S 7D 4C 9S 5H 8H JC 3D TC QH 2S 2D 9S KD QD 9H AD 6D 9C 8D 2D KS 9S JC 4C JD KC 4S TH KH TS 6D 4D 5C KD 5H AS 9H AD QD JS 7C 6D 5D 5C TH 5H QH QS 9D QH KH 5H JH 4C 4D TC TH 6C KH AS TS 9D KD 9C 7S 4D 8H 5S KH AS 2S 7D 9D 4C TS TH AH 7C KS 4D AC 8S 9S 8D TH QH 9D 5C 5D 5C 8C QS TC 4C 3D 3S 2C 8D 9D KS 2D 3C KC 4S 8C KH 6C JC 8H AH 6H 7D 7S QD 3C 4C 6C KC 3H 2C QH 8H AS 7D 4C 8C 4H KC QD 5S 4H 2C TD AH JH QH 4C 8S 3H QS 5S JS 8H 2S 9H 9C 3S 2C 6H TS 7S JC QD AC TD KC 5S 3H QH AS QS 7D JC KC 2C 4C 5C 5S QH 3D AS JS 4H 8D 7H JC 2S 9C 5D 4D 2S 4S 9D 9C 2D QS 8H 7H 6D 7H 3H JS TS AC 2D JH 7C 8S JH 5H KC 3C TC 5S 9H 4C 8H 9D 8S KC 5H 9H AD KS 9D KH 8D AH JC 2H 9H KS 6S 3H QC 5H AH 9C 5C KH 5S AD 6C JC 9H QC 9C TD 5S 5D JC QH 2D KS 8H QS 2H TS JH 5H 5S AH 7H 3C 8S AS TD KH 6H 3D JD 2C 4C KC 7S AH 6C JH 4C KS 9D AD 7S KC 7D 8H 3S 9C 7H 5C 5H 3C 8H QC 3D KH 6D JC 2D 4H 5D 7D QC AD AH 9H QH 8H KD 8C JS 9D 3S 3C 2H 5D 6D 2S 8S 6S TS 3C 6H 8D 5S 3H TD 6C KS 3D JH 9C 7C 9S QS 5S 4H 6H 7S 6S TH 4S KC KD 3S JC JH KS 7C 3C 2S 6D QH 2C 7S 5H 8H AH KC 8D QD 6D KH 5C 7H 9D 3D 9C 6H 2D 8S JS 9S 2S 6D KC 7C TC KD 9C JH 7H KC 8S 2S 7S 3D 6H 4H 9H 2D 4C 8H 7H 5S 8S 2H 8D AD 7C 3C 7S 5S 4D 9H 3D JC KH 5D AS 7D 6D 9C JC 4C QH QS KH KD JD 7D 3D QS QC 8S 6D JS QD 6S 8C 5S QH TH 9H AS AC 2C JD QC KS QH 7S 3C 4C 5C KC 5D AH 6C 4H 9D AH 2C 3H KD 3D TS 5C TD 8S QS AS JS 3H KD AC 4H KS 7D 5D TS 9H 4H 4C 9C 2H 8C QC 2C 7D 9H 4D KS 4C QH AD KD JS QD AD AH KH 9D JS 9H JC KD JD 8S 3C 4S TS 7S 4D 5C 2S 6H 7C JS 7S 5C KD 6D QH 8S TD 2H 6S QH 6C TC 6H TD 4C 9D 2H QC 8H 3D TS 4D 2H 6H 6S 2C 7H 8S 6C 9H 9D JD JH 3S AH 2C 6S 3H 8S 2C QS 8C 5S 3H 2S 7D 3C AD 4S 5C QC QH AS TS 4S 6S 4C 5H JS JH 5C TD 4C 6H JS KD KH QS 4H TC KH JC 4D 9H 9D 8D KC 3C 8H 2H TC 8S AD 9S 4H TS 7H 2C 5C 4H 2S 6C 5S KS AH 9C 7C 8H KD TS QH TD QS 3C JH AH 2C 8D 7D 5D KC 3H 5S AC 4S 7H QS 4C 2H 3D 7D QC KH JH 6D 6C TD TH KD 5S 8D TH 6C 9D 7D KH 8C 9S 6D JD QS 7S QC 2S QH JC 4S KS 8D 7S 5S 9S JD KD 9C JC AD 2D 7C 4S 5H AH JH 9C 5D TD 7C 2D 6S KC 6C 7H 6S 9C QD 5S 4H KS TD 6S 8D KS 2D TH TD 9H JD TS 3S KH JS 4H 5D 9D TC TD QC JD TS QS QD AC AD 4C 6S 2D AS 3H KC 4C 7C 3C TD QS 9C KC AS 8D AD KC 7H QC 6D 8H 6S 5S AH 7S 8C 3S AD 9H JC 6D JD AS KH 6S JH AD 3D TS KS 7H JH 2D JS QD AC 9C JD 7C 6D TC 6H 6C JC 3D 3S QC KC 3S JC KD 2C 8D AH QS TS AS KD 3D JD 8H 7C 8C 5C QD 6C
8C TS KC 9H 4S 7D 2S 5D 3S AC 5C AD 5D AC 9C 7C 5H 8D TD KS 3H 7H 6S KC JS QH TD JC 2D 8S TH 8H 5C QS TC 9H 4D JC KS JS 7C 5H KC QH JD AS KH 4C AD 4S 5H KS 9C 7D 9H 8D 3S 5D 5C AH 6H 4H 5C 3H 2H 3S QH 5S 6S AS TD 8C 4H 7C TC KC 4C 3H 7S KS 7C 9C 6D KD 3H 4C QS QC AC KH JC 6S 5H 2H 2D KD 9D 7C AS JS AD QH TH 9D 8H TS 6D 3S AS AC 2H 4S 5C 5S TC KC JD 6C TS 3C QD AS 6H JS 2C 3D 9H KC 4H 8S KD 8S 9S 7C 2S 3S 6D 6S 4H KC 3C 8C 2D 7D 4D 9S 4S QH 4H JD 8C KC 7S TC 2D TS 8H QD AC 5C 3D KH QD 6C 6S AD AS 8H 2H QS 6S 8D 4C 8S 6C QH TC 6D 7D 9D 2S 8D 8C 4C TS 9S 9D 9C AC 3D 3C QS 2S 4H JH 3D 2D TD 8S 9H 5H QS 8S 6D 3C 8C JD AS 7H 7D 6H TD 9D AS JH 6C QC 9S KD JC AH 8S QS 4D TH AC TS 3C 3D 5C 5S 4D JS 3D 8H 6C TS 3S AD 8C 6D 7C 5D 5H 3S 5C JC 2H 5S 3D 5H 6H 2S KS 3D 5D JD 7H JS 8H KH 4H AS JS QS QC TC 6D 7C KS 3D QS TS 2H JS 4D AS 9S JC KD QD 5H 4D 5D KH 7H 3D JS KD 4H 2C 9H 6H 5C 9D 6C JC 2D TH 9S 7D 6D AS QD JH 4D JS 7C QS 5C 3H KH QD AD 8C 8H 3S TH 9D 5S AH 9S 4D 9D 8S 4H JS 3C TC 8D 2C KS 5H QD 3S TS 9H AH AD 8S 5C 7H 5D KD 9H 4D 3D 2D KS AD KS KC 9S 6D 2C QH 9D 9H TS TC 9C 6H 5D QH 4D AD 6D QC JS KH 9S 3H 9D JD 5C 4D 9H AS TC QH 2C 6D JC 9C 3C AD 9S KH 9D 7D KC 9C 7C JC JS KD 3H AS 3C 7D QD KH QS 2C 3S 8S 8H 9H 9C JC QH 8D 3C KC 4C 4H 6D AD 9H 9D 3S KS QS 7H KH 7D 5H 5D JD AD 2H 2C 6H TH TC 7D 8D 4H 8C AS 4S 2H AC QC 3S 6D TH 4D 4C KH 4D TC KS AS 7C 3C 6D 2D 9H 6C 8C TD 5D QS 2C 7H 4C 9C 3H 9H 5H JH TS 7S TD 6H AD QD 8H 8S 5S AD 9C 8C 7C 8D 5H 9D 8S 2S 4H KH KS 9S 2S KC 5S AD 4S 7D QS 9C QD 6H JS 5D AC 8D 2S AS KH AC JC 3S 9D 9S 3C 9C 5S JS AD 3C 3D KS 3S 5C 9C 8C TS 4S JH 8D 5D 6H KD QS QD 3D 6C KC 8S JD 6C 3S 8C TC QC 3C QH JS KC JC 8H 2S 9H 9C JH 8S 8C 9S 8S 2H QH 4D QC 9D KC AS TH 3C 8S 6H TH 7C 2H 6S 3C 3H AS 7S QH 5S JS 4H 5H TS 8H AH AC JC 9D 8H 2S 4S TC JC 3C 7H 3H 5C 3D AD 3C 3S 4C QC AS 5D TH 8C 6S 9D 4C JS KH AH TS JD 8H AD 4C 6S 9D 7S AC 4D 3D 3S TC JD AD 7H 6H 4H JH KC TD TS 7D 6S 8H JH TC 3S 8D 8C 9S 2C 5C 4D 2C 9D KC QH TH QS JC 9C 4H TS QS 3C QD 8H KH 4H 8D TD 8S AC 7C 3C TH 5S 8H 8C 9C JD TC KD QC TC JD TS 8C 3H 6H KD 7C TD JH QS KS 9C 6D 6S AS 9H KH 6H 2H 4D AH 2D JH 6H TD 5D 4H JD KD 8C 9S JH QD JS 2C QS 5C 7C 4S TC 7H 8D 2S 6H 7S 9C 7C KC 8C 5D 7H 4S TD QC 8S JS 4H KS AD 8S JH 6D TD KD 7C 6C 2D 7D JC 6H 6S JS 4H QH 9H AH 4C 3C 6H 5H AS 7C 7S 3D KH KC 5D 5C JC 3D TD AS 4D 6D 6S QH JD KS 8C 7S 8S QH 2S JD 5C 7H AH QD 8S 3C 6H 6C 2C 8D TD 7D 4C 4D 5D QH KH 7C 2S 7H JS 6D QC QD AD 6C 6S 7D TH 6H 2H 8H KH 4H KS JS KD 5D 2D KH 7D 9C 8C 3D 9C 6D QD 3C KS 3S 7S AH JD 2D AH QH AS JC 8S 8H 4C KC TH 7D JC 5H TD 7C 5D KD 4C AD 8H JS KC 2H AC AH 7D JH KH 5D 7S 6D 9S 5S 9C 6H 8S TD JD 9H 6C AC 7D 8S 6D TS KD 7H AC 5S 7C 5D AH QC JC 4C TC 8C 2H TS 2C 7D KD KC 6S 3D 7D 2S 8S 3H 5S 5C 8S 5D 8H 4C 6H KC 3H 7C 5S KD JH 8C 3D 3C 6C KC TD 7H 7C 4C JC KC 6H TS QS TD KS 8H 8C 9S 6C 5S 9C QH 7D AH KS KC 9S 2C 4D 4S 8H TD 9C 3S 7D 9D AS TH 6S 7D 3C 6H 5D KD 2C 5C 9D 9C 2H KC 3D AD 3H QD QS 8D JC 4S 8C 3H 9C 7C AD 5D JC 9D JS AS 5D 9H 5C 7H 6S 6C QC JC QD 9S JC QS JH 2C 6S 9C QC 3D 4S TC 4H 5S 8D 3D 4D 2S KC 2H JS 2C TD 3S TH KD 4D 7H JH JS KS AC 7S 8C 9S 2D 8S 7D 5C AD 9D AS 8C 7H 2S 6C TH 3H 4C 3S 8H AC KD 5H JC 8H JD 2D 4H TD JH 5C 3D AS QH KS 7H JD 8S 5S 6D 5H 9S 6S TC QS JC 5C 5D 9C TH 8C 5H 3S JH 9H 2S 2C 6S 7S AS KS 8C QD JC QS TC QC 4H AC KH 6C TC 5H 7D JH 4H 2H 8D JC KS 4D 5S 9C KH KD 9H 5C TS 3D 7D 2D 5H AS TC 4D 8C 2C TS 9D 3H 8D 6H 8D 2D 9H JD 6C 4S 5H 5S 6D AD 9C JC 7D 6H 9S 6D JS 9H 3C AD JH TC QS 4C 5D 9S 7C 9C AH KD 6H 2H TH 8S QD KS 9D 9H AS 4H 8H 8D 5H 6C AH 5S AS AD 8S QS 5D 4S 2H TD KS 5H AC 3H JC 9C 7D QD KD AC 6D 5H QH 6H 5S KC AH QH 2H 7D QS 3H KS 7S JD 6C 8S 3H 6D KS QD 5D 5C 8H TC 9H 4D 4S 6S 9D KH QC 4H 6C JD TD 2D QH 4S 6H JH KD 3C QD 8C 4S 6H 7C QD 9D AS AH 6S AD 3C 2C KC TH 6H 8D AH 5C 6D 8S 5D TD TS 7C AD JC QD 9H 3C KC 7H 5D 4D 5S 8H 4H 7D 3H JD KD 2D JH TD 6H QS 4S KD 5C 8S 7D 8H AC 3D AS 8C TD 7H KH 5D 6C JD 9D KS 7C 6D QH TC JD KD AS KC JH 8S 5S 7S 7D AS 2D 3D AD 2H 2H 5D AS 3C QD KC 6H 9H 9S 2C 9D 5D TH 4C JH 3H 8D TC 8H 9H 6H KD 2C TD 2H 6C 9D 2D JS 8C KD 7S 3C 7C AS QH TS AD 8C 2S QS 8H 6C JS 4C 9S QC AD TD TS 2H 7C TS TC 8C 3C 9H 2D 6D JC TC 2H 8D JH KS 6D 3H TD TH 8H 9D TD 9H QC 5D 6C 8H 8C KC TS 2H 8C 3D AH 4D TH TC 7D 8H KC TS 5C 2D 8C 6S KH AH 5H 6H KC 5S 5D AH TC 4C JD 8D 6H 8C 6C KC QD 3D 8H 2D JC 9H 4H AD 2S TD 6S 7D JS KD 4H QS 2S 3S 8C 4C 9H JH TS 3S 4H QC 5S 9S 9C 2C KD 9H JS 9S 3H JC TS 5D AC AS 2H 5D AD 5H JC 7S TD JS 4C 2D 4S 8H 3D 7D 2C AD KD 9C TS 7H QD JH 5H JS AC 3D TH 4C 8H 6D KH KC QD 5C AD 7C 2D 4H AC 3D 9D TC 8S QD 2C JC 4H JD AH 6C TD 5S TC 8S AH 2C 5D AS AC TH 7S 3D AS 6C 4C 7H 7D 4H AH 5C 2H KS 6H 7S 4H 5H 3D 3C 7H 3C 9S AC 7S QH 2H 3D 6S 3S 3H 2D 3H AS 2C 6H TC JS 6S 9C 6C QH KD QD 6D AC 6H KH 2C TS 8C 8H 7D 3S 9H 5D 3H 4S QC 9S 5H 2D 9D 7H 6H 3C 8S 5H 4D 3S 4S KD 9S 4S TC 7S QC 3S 8S 2H 7H TC 3D 8C 3H 6C 2H 6H KS KD 4D KC 3D 9S 3H JS 4S 8H 2D 6C 8S 6H QS 6C TC QD 9H 7D 7C 5H 4D TD 9D 8D 6S 6C TC 5D TS JS 8H 4H KC JD 9H TC 2C 6S 5H 8H AS JS 9C 5C 6S 9D JD 8H KC 4C 6D 4D 8D 8S 6C 7C 6H 7H 8H 5C KC TC 3D JC 6D KS 9S 6H 7S 9C 2C 6C 3S KD 5H TS 7D 9H 9S 6H KH 3D QD 4C 6H TS AC 3S 5C 2H KD 4C AS JS 9S 7C TS 7H 9H JC KS 4H 8C JD 3H 6H AD 9S 4S 5S KS 4C 2C 7D 3D AS 9C 2S QS KC 6C 8S 5H 3D 2S AC 9D 6S 3S 4D TD QD TH 7S TS 3D AC 7H 6C 5D QC TC QD AD 9C QS 5C 8D KD 3D 3C 9D 8H AS 3S 7C 8S JD 2D 8D KC 4C TH AC QH JS 8D 7D 7S 9C KH 9D 8D 4C JH 2C 2S QD KD TS 4H 4D 6D 5D 2D JH 3S 8S 3H TC KH AD 4D 2C QS 8C KD JH JD AH 5C 5C 6C 5H 2H JH 4H KS 7C TC 3H 3C 4C QC 5D JH 9C QD KH 8D TC 3H 9C JS 7H QH AS 7C 9H 5H JC 2D 5S QD 4S 3C KC 6S 6C 5C 4C 5D KH 2D TS 8S 9C AS 9S 7C 4C 7C AH 8C 8D 5S KD QH QS JH 2C 8C 9D AH 2H AC QC 5S 8H 7H 2C QD 9H 5S QS QC 9C 5H JC TH 4H 6C 6S 3H 5H 3S 6H KS 8D AC 7S AC QH 7H 8C 4S KC 6C 3D 3S TC 9D 3D JS TH AC 5H 3H 8S 3S TC QD KH JS KS 9S QC 8D AH 3C AC 5H 6C KH 3S 9S JH 2D QD AS 8C 6C 4D 7S 7H 5S JC 6S 9H 4H JH AH 5S 6H 9S AD 3S TH 2H 9D 8C 4C 8D 9H 7C QC AD 4S 9C KC 5S 9D 6H 4D TC 4C JH 2S 5D 3S AS 2H 6C 7C KH 5C AD QS TH JD 8S 3S 4S 7S AH AS KC JS 2S AD TH JS KC 2S 7D 8C 5C 9C TS 5H 9D 7S 9S 4D TD JH JS KH 6H 5D 2C JD JS JC TH 2D 3D QD 8C AC 5H 7S KH 5S 9D 5D TD 4S 6H 3C 2D 4S 5D AC 8D 4D 7C AD AS AH 9C 6S TH TS KS 2C QC AH AS 3C 4S 2H 8C 3S JC 5C 7C 3H 3C KH JH 7S 3H JC 5S 6H 4C 2S 4D KC 7H 4D 7C 4H 9S 8S 6S AD TC 6C JC KH QS 3S TC 4C 8H 8S AC 3C TS QD QS TH 3C TS 7H 7D AH TD JC TD JD QC 4D 9S 7S TS AD 7D AC AH 7H 4S 6D 7C 2H 9D KS JC TD 7C AH JD 4H 6D QS TS 2H 2C 5C TC KC 8C 9S 4C JS 3C JC 6S AH AS 7D QC 3D 5S JC JD 9D TD KH TH 3C 2S 6H AH AC 5H 5C 7S 8H QC 2D AC QD 2S 3S JD QS 6S 8H KC 4H 3C 9D JS 6H 3S 8S AS 8C 7H KC 7D JD 2H JC QH 5S 3H QS 9H TD 3S 8H 7S AC 5C 6C AH 7C 8D 9H AH JD TD QS 7D 3S 9C 8S AH QH 3C JD KC 4S 5S 5D TD KS 9H 7H 6S JH TH 4C 7C AD 5C 2D 7C KD 5S TC 9D 6S 6C 5D 2S TH KC 9H 8D 5H 7H 4H QC 3D 7C AS 6S 8S QC TD 4S 5C TH QS QD 2S 8S 5H TH QC 9H 6S KC 7D 7C 5C 7H KD AH 4D KH 5C 4S 2D KC QH 6S 2C TD JC AS 4D 6C 8C 4H 5S JC TC JD 5S 6S 8D AS 9D AD 3S 6D 6H 5D 5S TC 3D 7D QS 9D QD 4S 6C 8S 3S 7S AD KS 2D 7D 7C KC QH JC AC QD 5D 8D QS 7H 7D JS AH 8S 5H 3D TD 3H 4S 6C JH 4S QS 7D AS 9H JS KS 6D TC 5C 2D 5C 6H TC 4D QH 3D 9H 8S 6C 6D 7H TC TH 5S JD 5C 9C KS KD 8D TD QH 6S 4S 6C 8S KC 5C TC 5S 3D KS AC 4S 7D QD 4C TH 2S TS 8H 9S 6S 7S QH 3C AH 7H 8C 4C 8C TS JS QC 3D 7D 5D 7S JH 8S 7S 9D QC AC 7C 6D 2H JH KC JS KD 3C 6S 4S 7C AH QC KS 5H KS 6S 4H JD QS TC 8H KC 6H AS KH 7C TC 6S TD JC 5C 7D AH 3S 3H 4C 4H TC TH 6S 7H 6D 9C QH 7D 5H 4S 8C JS 4D 3D 8S QH KC 3H 6S AD 7H 3S QC 8S 4S 7S JS 3S JD KH TH 6H QS 9C 6C 2D QD 4S QH 4D 5H KC 7D 6D 8D TH 5S TD AD 6S 7H KD KH 9H 5S KC JC 3H QC AS TS 4S QD KS 9C 7S KC TS 6S QC 6C TH TC 9D 5C 5D KD JS 3S 4H KD 4C QD 6D 9S JC 9D 8S JS 6D 4H JH 6H 6S 6C KS KH AC 7D 5D TC 9S KH 6S QD 6H AS AS 7H 6D QH 8D TH 2S KH 5C 5H 4C 7C 3D QC TC 4S KH 8C 2D JS 6H 5D 7S 5H 9C 9H JH 8S TH 7H AS JS 2S QD KH 8H 4S AC 8D 8S 3H 4C TD KD 8C JC 5C QS 2D JD TS 7D 5D 6C 2C QS 2H 3C AH KS 4S 7C 9C 7D JH 6C 5C 8H 9D QD 2S TD 7S 6D 9C 9S QS KH QH 5C JC 6S 9C QH JH 8D 7S JS KH 2H 8D 5H TH KC 4D 4S 3S 6S 3D QS 2D JD 4C TD 7C 6D TH 7S JC AH QS 7S 4C TH 9D TS AD 4D 3H 6H 2D 3H 7D JD 3D AS 2S 9C QC 8S 4H 9H 9C 2C 7S JH KD 5C 5D 6H TC 9H 8H JC 3C 9S 8D KS AD KC TS 5H JD QS QH QC 8D 5D KH AH 5D AS 8S 6S 4C AH QC QD TH 7H 3H 4H 7D 6S 4S 9H AS 8H JS 9D JD 8C 2C 9D 7D 5H 5S 9S JC KD KD 9C 4S QD AH 7C AD 9D AC TD 6S 4H 4S 9C 8D KS TC 9D JH 7C 5S JC 5H 4S QH AC 2C JS 2S 9S 8C 5H AS QD AD 5C 7D 8S QC TD JC 4C 8D 5C KH QS 4D 6H 2H 2C TH 4S 2D KC 3H QD AC 7H AD 9D KH QD AS 8H TH KC 8D 7S QH 8C JC 6C 7D 8C KH AD QS 2H 6S 2D JC KH 2D 7D JS QC 5H 4C 5D AD TS 3S AD 4S TD 2D TH 6S 9H JH 9H 2D QS 2C 4S 3D KH AS AC 9D KH 6S 8H 4S KD 7D 9D TS QD QC JH 5H AH KS AS AD JC QC 5S KH 5D 7D 6D KS KD 3D 7C 4D JD 3S AC JS 8D 5H 9C 3H 4H 4D TS 2C 6H KS KH 9D 7C 2S 6S 8S 2H 3D 6H AC JS 7S 3S TD 8H 3H 4H TH 9H TC QC KC 5C KS 6H 4H AC 8S TC 7D QH 4S JC TS 6D 6C AC KH QH 7D 7C JH QS QD TH 3H 5D KS 3D 5S 8D JS 4C 2C KS 7H 9C 4H 5H 8S 4H TD 2C 3S QD QC 3H KC QC JS KD 9C AD 5S 9D 7D 7H TS 8C JC KH 7C 7S 6C TS 2C QD TH 5S 9D TH 3C 7S QH 8S 9C 2H 5H 5D 9H 6H 2S JS KH 3H 7C 2H 5S JD 5D 5S 2C TC 2S 6S 6C 3C 8S 4D KH 8H 4H 2D KS 3H 5C 2S 9H 3S 2D TD 7H 8S 6H JD KC 9C 8D 6S QD JH 7C 9H 5H 8S 8H TH TD QS 7S TD 7D TS JC KD 7C 3C 2C 3C JD 8S 4H 2D 2S TD AS 4D AC AH KS 6C 4C 4S 7D 8C 9H 6H AS 5S 3C 9S 2C QS KD 4D 4S AC 5D 2D TS 2C JS KH QH 5D 8C AS KC KD 3H 6C TH 8S 7S KH 6H 9S AC 6H 7S 6C QS AH 2S 2H 4H 5D 5H 5H JC QD 2C 2S JD AS QC 6S 7D 6C TC AS KD 8H 9D 2C 7D JH 9S 2H 4C 6C AH 8S TD 3H TH 7C TS KD 4S TS 6C QH 8D 9D 9C AH 7D 6D JS 5C QD QC 9C 5D 8C 2H KD 3C QH JH AD 6S AH KC 8S 6D 6H 3D 7C 4C 7S 5S 3S 6S 5H JC 3C QH 7C 5H 3C 3S 8C TS 4C KD 9C QD 3S 7S 5H 7H QH JC 7C 8C KD 3C KD KH 2S 4C TS AC 6S 2C 7C 2C KH 3C 4C 6H 4D 5H 5S 7S QD 4D 7C 8S QD TS 9D KS 6H KD 3C QS 4D TS 7S 4C 3H QD 8D 9S TC TS QH AC 6S 3C 9H 9D QS 8S 6H 3S 7S 5D 4S JS 2D 6C QH 6S TH 4C 4H AS JS 5D 3D TS 9C AC 8S 6S 9C 7C 3S 5C QS AD AS 6H 3C 9S 8C 7H 3H 6S 7C AS 9H JD KH 3D 3H 7S 4D 6C 7C AC 2H 9C TH 4H 5S 3H AC TC TH 9C 9H 9S 8D 8D 9H 5H 4D 6C 2H QD 6S 5D 3S 4C 5C JD QS 4D 3H TH AC QH 8C QC 5S 3C 7H AD 4C KS 4H JD 6D QS AH 3H KS 9H 2S JS JH 5H 2H 2H 5S TH 6S TS 3S KS 3C 5H JS 2D 9S 7H 3D KC JH 6D 7D JS TD AC JS 8H 2C 8C JH JC 2D TH 7S 5D 9S 8H 2H 3D TC AH JC KD 9C 9D QD JC 2H 6D KH TS 9S QH TH 2C 8D 4S JD 5H 3H TH TC 9C KC AS 3D 9H 7D 4D TH KH 2H 7S 3H 4H 7S KS 2S JS TS 8S 2H QD 8D 5S 6H JH KS 8H 2S QC AC 6S 3S JC AS AD QS 8H 6C KH 4C 4D QD 2S 3D TS TD 9S KS 6S QS 5C 8D 3C 6D 4S QC KC JH QD TH KH AD 9H AH 4D KS 2S 8D JH JC 7C QS 2D 6C TH 3C 8H QD QH 2S 3S KS 6H 5D 9S 4C TS TD JS QD 9D JD 5H 8H KH 8S KS 7C TD AD 4S KD 2C 7C JC 5S AS 6C 7D 8S 5H 9C 6S QD 9S TS KH QS 5S QH 3C KC 7D 3H 3C KD 5C AS JH 7H 6H JD 9D 5C 9H KC 8H KS 4S AD 4D 2S 3S JD QD 8D 2S 7C 5S 6S 5H TS 6D 9S KC TD 3S 6H QD JD 5C 8D 5H 9D TS KD 8D 6H TD QC 4C 7D 6D 4S JD 9D AH 9S AS TD 9H QD 2D 5S 2H 9C 6H 9S TD QC 7D TC 3S 2H KS TS 2C 9C 8S JS 9D 7D 3C KC 6D 5D 6C 6H 8S AS 7S QS JH 9S 2H 8D 4C 8H 9H AD TH KH QC AS 2S JS 5C 6H KD 3H 7H 2C QD 8H 2S 8D 3S 6D AH 2C TC 5C JD JS TS 8S 3H 5D TD KC JC 6H 6S QS TC 3H 5D AH JC 7C 7D 4H 7C 5D 8H 9C 2H 9H JH KH 5S 2C 9C 7H 6S TH 3S QC QD 4C AC JD 2H 5D 9S 7D KC 3S QS 2D AS KH 2S 4S 2H 7D 5C TD TH QH 9S 4D 6D 3S TS 6H 4H KS 9D 8H 5S 2D 9H KS 4H 3S 5C 5D KH 6H 6S JS KC AS 8C 4C JC KH QC TH QD AH 6S KH 9S 2C 5H TC 3C 7H JC 4D JD 4S 6S 5S 8D 7H 7S 4D 4C 2H 7H 9H 5D KH 9C 7C TS TC 7S 5H 4C 8D QC TS 4S 9H 3D AD JS 7C 8C QS 5C 5D 3H JS AH KC 4S 9D TS JD 8S QS TH JH KH 2D QD JS JD QC 5D 6S 9H 3S 2C 8H 9S TS 2S 4C AD 7H JC 5C 2D 6D 4H 3D 7S JS 2C 4H 8C AD QD 9C 3S TD JD TS 4C 6H 9H 7D QD 6D 3C AS AS 7C 4C 6S 5D 5S 5C JS QC 4S KD 6S 9S 7C 3C 5S 7D JH QD JS 4S 7S JH 2C 8S 5D 7H 3D QH AD TD 6H 2H 8D 4H 2D 7C AD KH 5D TS 3S 5H 2C QD AH 2S 5C KH TD KC 4D 8C 5D AS 6C 2H 2S 9H 7C KD JS QC TS QS KH JH 2C 5D AD 3S 5H KC 6C 9H 3H 2H AD 7D 7S 7S JS JH KD 8S 7D 2S 9H 7C 2H 9H 2D 8D QC 6S AD AS 8H 5H 6C 2S 7H 6C 6D 7D 8C 5D 9D JC 3C 7C 9C 7H JD 2H KD 3S KH AD 4S QH AS 9H 4D JD KS KD TS KH 5H 4C 8H 5S 3S 3D 7D TD AD 7S KC JS 8S 5S JC 8H TH 9C 4D 5D KC 7C 5S 9C QD 2C QH JS 5H 8D KH TD 2S KS 3D AD KC 7S TC 3C 5D 4C 2S AD QS 6C 9S QD TH QH 5C 8C AD QS 2D 2S KC JD KS 6C JC 8D 4D JS 2H 5D QD 7S 7D QH TS 6S 7H 3S 8C 8S 9D QS 8H 6C 9S 4S TC 2S 5C QD 4D QS 6D TH 6S 3S 5C 9D 6H 8D 4C 7D TC 7C TD AH 6S AS 7H 5S KD 3H 5H AC 4C 8D 8S AH KS QS 2C AD 6H 7D 5D 6H 9H 9S 2H QS 8S 9C 5D 2D KD TS QC 5S JH 7D 7S TH 9S 9H AC 7H 3H 6S KC 4D 6D 5C 4S QD TS TD 2S 7C QD 3H JH 9D 4H 7S 7H KS 3D 4H 5H TC 2S AS 2D 6D 7D 8H 3C 7H TD 3H AD KC TH 9C KH TC 4C 2C 9S 9D 9C 5C 2H JD 3C 3H AC TS 5D AD 8D 6H QC 6S 8C 2S TS 3S JD 7H 8S QH 4C 5S 8D AC 4S 6C 3C KH 3D 7C 2D 8S 2H 4H 6C 8S TH 2H 4S 8H 9S 3H 7S 7C 4C 9C 2C 5C AS 5D KD 4D QH 9H 4H TS AS 7D 8D 5D 9S 8C 2H QC KD AC AD 2H 7S AS 3S 2D 9S 2H QC 8H TC 6D QD QS 5D KH 3C TH JD QS 4C 2S 5S AD 7H 3S AS 7H JS 3D 6C 3S 6D AS 9S AC QS 9C TS AS 8C TC 8S 6H 9D 8D 6C 4D JD 9C KC 7C 6D KS 3S 8C AS 3H 6S TC 8D TS 3S KC 9S 7C AS 8C QC 4H 4S 8S 6C 3S TC AH AC 4D 7D 5C AS 2H 6S TS QC AD TC QD QC 8S 4S TH 3D AH TS JH 4H 5C 2D 9S 2C 3H 3C 9D QD QH 7D KC 9H 6C KD 7S 3C 4D AS TC 2D 3D JS 4D 9D KS 7D TH QC 3H 3C 8D 5S 2H 9D 3H 8C 4C 4H 3C TH JC TH 4S 6S JD 2D 4D 6C 3D 4C TS 3S 2D 4H AC 2C 6S 2H JH 6H TD 8S AD TC AH AC JH 9S 6S 7S 6C KC 4S JD 8D 9H 5S 7H QH AH KD 8D TS JH 5C 5H 3H AD AS JS 2D 4H 3D 6C 8C 7S AD 5D 5C 8S TD 5D 7S 9C 4S 5H 6C 8C 4C 8S JS QH 9C AS 5C QS JC 3D QC 7C JC 9C KH JH QS QC 2C TS 3D AD 5D JH AC 5C 9S TS 4C JD 8C KS KC AS 2D KH 9H 2C 5S 4D 3D 6H TH AH 2D 8S JC 3D 8C QH 7S 3S 8H QD 4H JC AS KH KS 3C 9S 6D 9S QH 7D 9C 4S AC 7H KH 4D KD AH AD TH 6D 9C 9S KD KS QH 4H QD 6H 9C 7C QS 6D 6S 9D 5S JH AH 8D 5H QD 2H JC KS 4H KH 5S 5C 2S JS 8D 9C 8C 3D AS KC AH JD 9S 2H QS 8H 5S 8C TH 5C 4C QC QS 8C 2S 2C 3S 9C 4C KS KH 2D 5D 8S AH AD TD 2C JS KS 8C TC 5S 5H 8H QC 9H 6H JD 4H 9S 3C JH 4H 9H AH 4S 2H 4C 8D AC 8S TH 4D 7D 6D QD QS 7S TC 7C KH 6D 2D JD 5H JS QD JH 4H 4S 9C 7S JH 4S 3S TS QC 8C TC 4H QH 9D 4D JH QS 3S 2C 7C 6C 2D 4H 9S JD 5C 5H AH 9D TS 2D 4C KS JH TS 5D 2D AH JS 7H AS 8D JS AH 8C AD KS 5S 8H 2C 6C TH 2H 5D AD AC KS 3D 8H TS 6H QC 6D 4H TS 9C 5H JS JH 6S JD 4C JH QH 4H 2C 6D 3C 5D 4C QS KC 6H 4H 6C 7H 6S 2S 8S KH QC 8C 3H 3D 5D KS 4H TD AD 3S 4D TS 5S 7C 8S 7D 2C KS 7S 6C 8C JS 5D 2H 3S 7C 5C QD 5H 6D 9C 9H JS 2S KD 9S 8D TD TS AC 8C 9D 5H QD 2S AC 8C 9H KS 7C 4S 3C KH AS 3H 8S 9C JS QS 4S AD 4D AS 2S TD AD 4D 9H JC 4C 5H QS 5D 7C 4H TC 2D 6C JS 4S KC 3S 4C 2C 5D AC 9H 3D JD 8S QS QH 2C 8S 6H 3C QH 6D TC KD AC AH QC 6C 3S QS 4S AC 8D 5C AD KH 5S 4C AC KH AS QC 2C 5C 8D 9C 8H JD 3C KH 8D 5C 9C QD QH 9D 7H TS 2C 8C 4S TD JC 9C 5H QH JS 4S 2C 7C TH 6C AS KS 7S JD JH 7C 9H 7H TC 5H 3D 6D 5D 4D 2C QD JH 2H 9D 5S 3D TD AD KS JD QH 3S 4D TH 7D 6S QS KS 4H TC KS 5S 8D 8H AD 2S 2D 4C JH 5S JH TC 3S 2D QS 9D 4C KD 9S AC KH 3H AS 9D KC 9H QD 6C 6S 9H 7S 3D 5C 7D KC TD 8H 4H 6S 3C 7H 8H TC QD 4D 7S 6S QH 6C 6D AD 4C QD 6C 5D 7D 9D KS TS JH 2H JD 9S 7S TS KH 8D 5D 8H 2D 9S 4C 7D 9D 5H QD 6D AC 6S 7S 6D JC QD JH 4C 6S QS 2H 7D 8C TD JH KD 2H 5C QS 2C JS 7S TC 5H 4H JH QD 3S 5S 5D 8S KH KS KH 7C 2C 5D JH 6S 9C 6D JC 5H AH JD 9C JS KC 2H 6H 4D 5S AS 3C TH QC 6H 9C 8S 8C TD 7C KC 2C QD 9C KH 4D 7S 3C TS 9H 9C QC 2S TS 8C TD 9S QD 3S 3C 4D 9D TH JH AH 6S 2S JD QH JS QD 9H 6C KD 7D 7H 5D 6S 8H AH 8H 3C 4S 2H 5H QS QH 7S 4H AC QS 3C 7S 9S 4H 3S AH KS 9D 7C AD 5S 6S 2H 2D 5H TC 4S 3C 8C QH TS 6S 4D JS KS JH AS 8S 6D 2C 8S 2S TD 5H AS TC TS 6C KC KC TS 8H 2H 3H 7C 4C 5S TH TD KD AD KH 7H 7S 5D 5H 5S 2D 9C AD 9S 3D 7S 8C QC 7C 9C KD KS 3C QC 9S 8C 4D 5C AS QD 6C 2C 2H KC 8S JD 7S AC 8D 5C 2S 4D 9D QH 3D 2S TC 3S KS 3C 9H TD KD 6S AC 2C 7H 5H 3S 6C 6H 8C QH TC 8S 6S KH TH 4H 5D TS 4D 8C JS 4H 6H 2C 2H 7D AC QD 3D QS KC 6S 2D 5S 4H TD 3H JH 4C 7S 5H 7H 8H KH 6H QS TH KD 7D 5H AD KD 7C KH 5S TD 6D 3C 6C 8C 9C 5H JD 7C KC KH 7H 2H 3S 7S 4H AD 4D 8S QS TH 3D 7H 5S 8D TC KS KD 9S 6D AD JD 5C 2S 7H 8H 6C QD 2H 6H 9D TC 9S 7C 8D 6D 4C 7C 6C 3C TH KH JS JH 5S 3S 8S JS 9H AS AD 8H 7S KD JH 7C 2C KC 5H AS AD 9C 9S JS AD AC 2C 6S QD 7C 3H TH KS KD 9D JD 4H 8H 4C KH 7S TS 8C KC 3S 5S 2H 7S 6H 7D KS 5C 6D AD 5S 8C 9H QS 7H 7S 2H 6C 7D TD QS 5S TD AC 9D KC 3D TC 2D 4D TD 2H 7D JD QD 4C 7H 5D KC 3D 4C 3H 8S KD QH 5S QC 9H TC 5H 9C QD TH 5H TS 5C 9H AH QH 2C 4D 6S 3C AC 6C 3D 2C 2H TD TH AC 9C 5D QC 4D AD 8D 6D 8C KC AD 3C 4H AC 8D 8H 7S 9S TD JC 4H 9H QH JS 2D TH TD TC KD KS 5S 6S 9S 8D TH AS KH 5H 5C 8S JD 2S 9S 6S 5S 8S 5D 7S 7H 9D 5D 8C 4C 9D AD TS 2C 7D KD TC 8S QS 4D KC 5C 8D 4S KH JD KD AS 5C AD QH 7D 2H 9S 7H 7C TC 2S 8S JD KH 7S 6C 6D AD 5D QC 9H 6H 3S 8C 8H AH TC 4H JS TD 2C TS 4D 7H 2D QC 9C 5D TH 7C 6C 8H QC 5D TS JH 5C 5H 9H 4S 2D QC 7H AS JS 8S 2H 4C 4H 8D JS 6S AC KD 3D 3C 4S 7H TH KC QH KH 6S QS 5S 4H 3C QD 3S 3H 7H AS KH 8C 4H 9C 5S 3D 6S TS 9C 7C 3H 5S QD 2C 3D AD AC 5H JH TD 2D 4C TS 3H KH AD 3S 7S AS 4C 5H 4D 6S KD JC 3C 6H 2D 3H 6S 8C 2D TH 4S AH QH AD 5H 7C 2S 9H 7H KC 5C 6D 5S 3H JC 3C TC 9C 4H QD TD JH 6D 9H 5S 7C 6S 5C 5D 6C 4S 7H 9H 6H AH AD 2H 7D KC 2C 4C 2S 9S 7H 3S TH 4C 8S 6S 3S AD KS AS JH TD 5C TD 4S 4D AD 6S 5D TC 9C 7D 8H 3S 4D 4S 5S 6H 5C AC 3H 3D 9H 3C AC 4S QS 8S 9D QH 5H 4D JC 6C 5H TS AC 9C JD 8C 7C QD 8S 8H 9C JD 2D QC QH 6H 3C 8D KS JS 2H 6H 5H QH QS 3H 7C 6D TC 3H 4S 7H QC 2H 3S 8C JS KH AH 8H 5S 4C 9H JD 3H 7S JC AC 3C 2D 4C 5S 6C 4S QS 3S JD 3D 5H 2D TC AH KS 6D 7H AD 8C 6H 6C 7S 3C JD 7C 8H KS KH AH 6D AH 7D 3H 8H 8S 7H QS 5H 9D 2D JD AC 4H 7S 8S 9S KS AS 9D QH 7S 2C 8S 5S JH QS JC AH KD 4C AH 2S 9H 4H 8D TS TD 6H QH JD 4H JC 3H QS 6D 7S 9C 8S 9D 8D 5H TD 4S 9S 4C 8C 8D 7H 3H 3D QS KH 3S 2C 2S 3C 7S TD 4S QD 7C TD 4D 5S KH AC AS 7H 4C 6C 2S 5H 6D JD 9H QS 8S 2C 2H TD 2S TS 6H 9H 7S 4H JC 4C 5D 5S 2C 5H 7D 4H 3S QH JC JS 6D 8H 4C QH 7C QD 3S AD TH 8S 5S TS 9H TC 2S TD JC 7D 3S 3D TH QH 7D 4C 8S 5C JH 8H 6S 3S KC 3H JC 3H KH TC QH TH 6H 2C AC 5H QS 2H 9D 2C AS 6S 6C 2S 8C 8S 9H 7D QC TH 4H KD QS AC 7S 3C 4D JH 6S 5S 8H KS 9S QC 3S AS JD 2D 6S 7S TC 9H KC 3H 7D KD 2H KH 7C 4D 4S 3H JS QD 7D KC 4C JC AS 9D 3C JS 6C 8H QD 4D AH JS 3S 6C 4C 3D JH 6D 9C 9H 9H 2D 8C 7H 5S KS 6H 9C 2S TC 6C 8C AD 7H 6H 3D KH AS 5D TH KS 8C 3S TS 8S 4D 5S 9S 6C 4H 9H 4S 4H 5C 7D KC 2D 2H 9D JH 5C JS TC 9D 9H 5H 7S KH JC 6S 7C 9H 8H 4D JC KH JD 2H TD TC 8H 6C 2H 2C KH 6H 9D QS QH 5H AC 7D 2S 3D QD JC 2D 8D JD JH 2H JC 2D 7H 2C 3C 8D KD TD 4H 3S 4H 6D 8D TS 3H TD 3D 6H TH JH JC 3S AC QH 9H 7H 8S QC 2C 7H TD QS 4S 8S 9C 2S 5D 4D 2H 3D TS 3H 2S QC 8H 6H KC JC KS 5D JD 7D TC 8C 6C 9S 3D 8D AC 8H 6H JH 6C 5D 8D 8S 4H AD 2C 9D 4H 2D 2C 3S TS AS TC 3C 5D 4D TH 5H KS QS 6C 4S 2H 3D AD 5C KC 6H 2C 5S 3C 4D 2D 9H 9S JD 4C 3H TH QH 9H 5S AH 8S AC 7D 9S 6S 2H TD 9C 4H 8H QS 4C 3C 6H 5D 4H 8C 9C KC 6S QD QS 3S 9H KD TC 2D JS 8C 6S 4H 4S 2S 4C 8S QS 6H KH 3H TH 8C 5D 2C KH 5S 3S 7S 7H 6C 9D QD 8D 8H KS AC 2D KH TS 6C JS KC 7H 9C KS 5C TD QC AH 6C 5H 9S 7C 5D 4D 3H 4H 6S 7C 7S AH QD TD 2H 7D QC 6S TC TS AH 7S 9D 3H TH 5H QD 9S KS 7S 7C 6H 8C TD TH 2D 4D QC 5C 7D JD AH 9C 4H 4H 3H AH 8D 6H QC QH 9H 2H 2C 2D AD 4C TS 6H 7S TH 4H QS TD 3C KD 2H 3H QS JD TC QC 5D 8H KS JC QD TH 9S KD 8D 8C 2D 9C 3C QD KD 6D 4D 8D AH AD QC 8S 8H 3S 9D 2S 3H KS 6H 4C 7C KC TH 9S 5C 3D 7D 6H AC 7S 4D 2C 5C 3D JD 4D 2D 6D 5H 9H 4C KH AS 7H TD 6C 2H 3D QD KS 4C 4S JC 3C AC 7C JD JS 8H 9S QC 5D JD 6S 5S 2H AS 8C 7D 5H JH 3D 8D TC 5S 9S 8S 3H JC 5H 7S AS 5C TD 3D 7D 4H 8D 7H 4D 5D JS QS 9C KS TD 2S 8S 5C 2H 4H AS TH 7S 4H 7D 3H JD KD 5D 2S KC JD 7H 4S 8H 4C JS 6H QH 5S 4H 2C QS 8C 5S 3H QC 2S 6C QD AD 8C 3D JD TC 4H 2H AD 5S AC 2S 5D 2C JS 2D AD 9D 3D 4C 4S JH 8D 5H 5D 6H 7S 4D KS 9D TD JD 3D 6D 9C 2S AS 7D 5S 5C 8H JD 7C 8S 3S 6S 5H JD TC AD 7H 7S 2S 9D TS 4D AC 8D 6C QD JD 3H 9S KH 2C 3C AC 3D 5H 6H 8D 5D KS 3D 2D 6S AS 4C 2S 7C 7H KH AC 2H 3S JC 5C QH 4D 2D 5H 7S TS AS JD 8C 6H JC 8S 5S 2C 5D 7S QH 7H 6C QC 8H 2D 7C JD 2S 2C QD 2S 2H JC 9C 5D 2D JD JH 7C 5C 9C 8S 7D 6D 8D 6C 9S JH 2C AD 6S 5H 3S KS 7S 9D KH 4C 7H 6C 2C 5C TH 9D 8D 3S QC AH 5S KC 6H TC 5H 8S TH 6D 3C AH 9C KD 4H AD TD 9S 4S 7D 6H 5D 7H 5C 5H 6D AS 4C KD KH 4H 9D 3C 2S 5C 6C JD QS 2H 9D 7D 3H AC 2S 6S 7S JS QD 5C QS 6H AD 5H TH QC 7H TC 3S 7C 6D KC 3D 4H 3D QC 9S 8H 2C 3S JC KS 5C 4S 6S 2C 6H 8S 3S 3D 9H 3H JS 4S 8C 4D 2D 8H 9H 7D 9D AH TS 9S 2C 9H 4C 8D AS 7D 3D 6D 5S 6S 4C 7H 8C 3H 5H JC AH 9D 9C 2S 7C 5S JD 8C 3S 3D 4D 7D 6S 3C KC 4S 5D 7D 3D JD 7H 3H 4H 9C 9H 4H 4D TH 6D QD 8S 9S 7S 2H AC 8S 4S AD 8C 2C AH 7D TC TS 9H 3C AD KS TC 3D 8C 8H JD QC 8D 2C 3C 7D 7C JD 9H 9C 6C AH 6S JS JH 5D AS QC 2C JD TD 9H KD 2H 5D 2D 3S 7D TC AH TS TD 8H AS 5D AH QC AC 6S TC 5H KS 4S 7H 4D 8D 9C TC 2H 6H 3H 3H KD 4S QD QH 3D 8H 8C TD 7S 8S JD TC AH JS QS 2D KH KS 4D 3C AD JC KD JS KH 4S TH 9H 2C QC 5S JS 9S KS AS 7C QD 2S JD KC 5S QS 3S 2D AC 5D 9H 8H KS 6H 9C TC AD 2C 6D 5S JD 6C 7C QS KH TD QD 2C 3H 8S 2S QC AH 9D 9H JH TC QH 3C 2S JS 5C 7H 6C 3S 3D 2S 4S QD 2D TH 5D 2C 2D 6H 6D 2S JC QH AS 7H 4H KH 5H 6S KS AD TC TS 7C AC 4S 4H AD 3C 4H QS 8C 9D KS 2H 2D 4D 4S 9D 6C 6D 9C AC 8D 3H 7H KD JC AH 6C TS JD 6D AD 3S 5D QD JC JH JD 3S 7S 8S JS QC 3H 4S JD TH 5C 2C AD JS 7H 9S 2H 7S 8D 3S JH 4D QC AS JD 2C KC 6H 2C AC 5H KD 5S 7H QD JH AH 2D JC QH 8D 8S TC 5H 5C AH 8C 6C 3H JS 8S QD JH 3C 4H 6D 5C 3S 6D 4S 4C AH 5H 5S 3H JD 7C 8D 8H AH 2H 3H JS 3C 7D QC 4H KD 6S 2H KD 5H 8H 2D 3C 8S 7S QD 2S 7S KC QC AH TC QS 6D 4C 8D 5S 9H 2C 3S QD 7S 6C 2H 7C 9D 3C 6C 5C 5S JD JC KS 3S 5D TS 7C KS 6S 5S 2S 2D TC 2H 5H QS AS 7H 6S TS 5H 9S 9D 3C KD 2H 4S JS QS 3S 4H 7C 2S AC 6S 9D 8C JH 2H 5H 7C 5D QH QS KH QC 3S TD 3H 7C KC 8D 5H 8S KH 8C 4H KH JD TS 3C 7H AS QC JS 5S AH 9D 2C 8D 4D 2D 6H 6C KC 6S 2S 6H 9D 3S 7H 4D KH 8H KD 3D 9C TC AC JH KH 4D JD 5H TD 3S 7S 4H 9D AS 4C 7D QS 9S 2S KH 3S 8D 8S KS 8C JC 5C KH 2H 5D 8S QH 2C 4D KC JS QC 9D AC 6H 8S 8C 7C JS JD 6S 4C 9C AC 4S QH 5D 2C 7D JC 8S 2D JS JH 4C JS 4C 7S TS JH KC KH 5H QD 4S QD 8C 8D 2D 6S TD 9D AC QH 5S QH QC JS 3D 3C 5C 4H KH 8S 7H 7C 2C 5S JC 8S 3H QC 5D 2H KC 5S 8D KD 6H 4H QD QH 6D AH 3D 7S KS 6C 2S 4D AC QS 5H TS JD 7C 2D TC 5D QS AC JS QC 6C KC 2C KS 4D 3H TS 8S AD 4H 7S 9S QD 9H QH 5H 4H 4D KH 3S JC AD 4D AC KC 8D 6D 4C 2D KH 2C JD 2C 9H 2D AH 3H 6D 9C 7D TC KS 8C 3H KD 7C 5C 2S 4S 5H AS AH TH JD 4H KD 3H TC 5C 3S AC KH 6D 7H AH 7S QC 6H 2D TD JD AS JH 5D 7H TC 9S 7D JC AS 5S KH 2H 8C AD TH 6H QD KD 9H 6S 6C QH KC 9D 4D 3S JS JH 4H 2C 9H TC 7H KH 4H JC 7D 9S 3H QS 7S AD 7D JH 6C 7H 4H 3S 3H 4D QH JD 2H 5C AS 6C QC 4D 3C TC JH AC JD 3H 6H 4C JC AD 7D 7H 9H 4H TC TS 2C 8C 6S KS 2H JD 9S 4C 3H QS QC 9S 9H 6D KC 9D 9C 5C AD 8C 2C QH TH QD JC 8D 8H QC 2C 2S QD 9C 4D 3S 8D JH QS 9D 3S 2C 7S 7C JC TD 3C TC 9H 3C TS 8H 5C 4C 2C 6S 8D 7C 4H KS 7H 2H TC 4H 2C 3S AS AH QS 8C 2D 2H 2C 4S 4C 6S 7D 5S 3S TH QC 5D TD 3C QS KD KC KS AS 4D AH KD 9H KS 5C 4C 6H JC 7S KC 4H 5C QS TC 2H JC 9S AH QH 4S 9H 3H 5H 3C QD 2H QC JH 8H 5D AS 7H 2C 3D JH 6H 4C 6S 7D 9C JD 9H AH JS 8S QH 3H KS 8H 3S AC QC TS 4D AD 3D AH 8S 9H 7H 3H QS 9C 9S 5H JH JS AH AC 8D 3C JD 2H AC 9C 7H 5S 4D 8H 7C JH 9H 6C JS 9S 7H 8C 9D 4H 2D AS 9S 6H 4D JS JH 9H AD QD 6H 7S JH KH AH 7H TD 5S 6S 2C 8H JH 6S 5H 5S 9D TC 4C QC 9S 7D 2C KD 3H 5H AS QD 7H JS 4D TS QH 6C 8H TH 5H 3C 3H 9C 9D AD KH JS 5D 3H AS AC 9S 5C KC 2C KH 8C JC QS 6D AH 2D KC TC 9D 3H 2S 7C 4D 6D KH KS 8D 7D 9H 2S TC JH AC QC 3H 5S 3S 8H 3S AS KD 8H 4C 3H 7C JH QH TS 7S 6D 7H 9D JH 4C 3D 3S 6C AS 4S 2H 2C 4C 8S 5H KC 8C QC QD 3H 3S 6C QS QC 2D 6S 5D 2C 9D 2H 8D JH 2S 3H 2D 6C 5C 7S AD 9H JS 5D QH 8S TS 2H 7S 6S AD 6D QC 9S 7H 5H 5C 7D KC JD 4H QC 5S 9H 9C 4D 6S KS 2S 4C 7C 9H 7C 4H 8D 3S 6H 5C 8H JS 7S 2D 6H JS TD 4H 4D JC TH 5H KC AC 7C 8D TH 3H 9S 2D 4C KC 4D KD QS 9C 7S 3D KS AD TS 4C 4H QH 9C 8H 2S 7D KS 7H 5D KD 4C 9C 2S 2H JC 6S 6C TC QC JH 5C 7S AC 8H KC 8S 6H QS JC 3D 6S JS 2D JH 8C 4S 6H 8H 6D 5D AD 6H 7D 2S 4H 9H 7C AS AC 8H 5S 3C JS 4S 6D 5H 2S QH 6S 9C 2C 3D 5S 6S 9S 4C QS 8D QD 8S TC 9C 3D AH 9H 5S 2C 7D AD JC 3S 7H TC AS 3C 6S 6D 7S KH KC 9H 3S TC 8H 6S 5H JH 8C 7D AC 2S QD 9D 9C 3S JC 8C KS 8H 5D 4D JS AH JD 6D 9D 8C 9H 9S 8H 3H 2D 6S 4C 4D 8S AD 4S TC AH 9H TS AC QC TH KC 6D 4H 7S 8C 2H 3C QD JS 9D 5S JC AH 2H TS 9H 3H 4D QH 5D 9C 5H 7D 4S JC 3S 8S TH 3H 7C 2H JD JS TS AC 8D 9C 2H TD KC JD 2S 8C 5S AD 2C 3D KD 7C 5H 4D QH QD TC 6H 7D 7H 2C KC 5S KD 6H AH QC 7S QH 6H 5C AC 5H 2C 9C 2D 7C TD 2S 4D 9D AH 3D 7C JD 4H 8C 4C KS TH 3C JS QH 8H 4C AS 3D QS QC 4D 7S 5H JH 6D 7D 6H JS KH 3C QD 8S 7D 2H 2C 7C JC 2S 5H 8C QH 8S 9D TC 2H AD 7C 8D QD 6S 3S 7C AD 9H 2H 9S JD TS 4C 2D 3S AS 4H QC 2C 8H 8S 7S TD TC JH TH TD 3S 4D 4H 5S 5D QS 2C 8C QD QH TC 6D 4S 9S 9D 4H QC 8C JS 9D 6H JD 3H AD 6S TD QC KC 8S 3D 7C TD 7D 8D 9H 4S 3S 6C 4S 3D 9D KD TC KC KS AC 5S 7C 6S QH 3D JS KD 6H 6D 2D 8C JD 2S 5S 4H 8S AC 2D 6S TS 5C 5H 8C 5S 3C 4S 3D 7C 8D AS 3H AS TS 7C 3H AD 7D JC QS 6C 6H 3S 9S 4C AC QH 5H 5D 9H TS 4H 6C 5C 7H 7S TD AD JD 5S 2H 2S 7D 6C KC 3S JD 8D 8S TS QS KH 8S QS 8D 6C TH AC AH 2C 8H 9S 7H TD KH QH 8S 3D 4D AH JD AS TS 3D 2H JC 2S JH KH 6C QC JS KC TH 2D 6H 7S 2S TC 8C 9D QS 3C 9D 6S KH 8H 6D 5D TH 2C 2H 6H TC 7D AD 4D 8S TS 9H TD 7S JS 6D JD JC 2H AC 6C 3D KH 8D KH JD 9S 5D 4H 4C 3H 7S QS 5C 4H JD 5D 3S 3C 4D KH QH QS 7S JD TS 8S QD AH 4C 6H 3S 5S 2C QS 3D JD AS 8D TH 7C 6S QC KS 7S 2H 8C QC 7H AC 6D 2D TH KH 5S 6C 7H KH 7D AH 8C 5C 7S 3D 3C KD AD 7D 6C 4D KS 2D 8C 4S 7C 8D 5S 2D 2S AH AD 2C 9D TD 3C AD 4S KS JH 7C 5C 8C 9C TH AS TD 4D 7C JD 8C QH 3C 5H 9S 3H 9C 8S 9S 6S QD KS AH 5H JH QC 9C 5S 4H 2H TD 7D AS 8C 9D 8C 2C 9D KD TC 7S 3D KH QC 3C 4D AS 4C QS 5S 9D 6S JD QH KS 6D AH 6C 4C 5H TS 9H 7D 3D 5S QS JD 7C 8D 9C AC 3S 6S 6C KH 8H JH 5D 9S 6D AS 6S 3S QC 7H QD AD 5C JH 2H AH 4H AS KC 2C JH 9C 2C 6H 2D JS 5D 9H KC 6D 7D 9D KD TH 3H AS 6S QC 6H AD JD 4H 7D KC 3H JS 3C TH 3D QS 4C 3H 8C QD 5H 6H AS 8H AD JD TH 8S KD 5D QC 7D JS 5S 5H TS 7D KC 9D QS 3H 3C 6D TS 7S AH 7C 4H 7H AH QC AC 4D 5D 6D TH 3C 4H 2S KD 8H 5H JH TC 6C JD 4S 8C 3D 4H JS TD 7S JH QS KD 7C QC KD 4D 7H 6S AD TD TC KH 5H 9H KC 3H 4D 3D AD 6S QD 6H TH 7C 6H TS QH 5S 2C KC TD 6S 7C 4D 5S JD JH 7D AC KD KH 4H 7D 6C 8D 8H 5C JH 8S QD TH JD 8D 7D 6C 7C 9D KD AS 5C QH JH 9S 2C 8C 3C 4C KS JH 2D 8D 4H 7S 6C JH KH 8H 3H 9D 2D AH 6D 4D TC 9C 8D 7H TD KS TH KD 3C JD 9H 8D QD AS KD 9D 2C 2S 9C 8D 3H 5C 7H KS 5H QH 2D 8C 9H 2D TH 6D QD 6C KC 3H 3S AD 4C 4H 3H JS 9D 3C TC 5H QH QC JC 3D 5C 6H 3S 3C JC 5S 7S 2S QH AC 5C 8C 4D 5D 4H 2S QD 3C 3H 2C TD AH 9C KD JS 6S QD 4C QC QS 8C 3S 4H TC JS 3H 7C JC AD 5H 4D 9C KS JC TD 9S TS 8S 9H QD TS 7D AS AC 2C TD 6H 8H AH 6S AD 8C 4S 9H 8D 9D KH 8S 3C QS 4D 2D 7S KH JS JC AD 4C 3C QS 9S 7H KC TD TH 5H JS AC JH 6D AC 2S QS 7C AS KS 6S KH 5S 6D 8H KH 3C QS 2H 5C 9C 9D 6C JS 2C 4C 6H 7D JC AC QD TD 3H 4H QC 8H JD 4C KD KS 5C KC 7S 6D 2D 3H 2S QD 5S 7H AS TH 6S AS 6D 8D 2C 8S TD 8H QD JC AH 9C 9H 2D TD QH 2H 5C TC 3D 8H KC 8S 3D KH 2S TS TC 6S 4D JH 9H 9D QS AC KC 6H 5D 4D 8D AH 9S 5C QS 4H 7C 7D 2H 8S AD JS 3D AC 9S AS 2C 2D 2H 3H JC KH 7H QH KH JD TC KS 5S 8H 4C 8D 2H 7H 3S 2S 5H QS 3C AS 9H KD AD 3D JD 6H 5S 9C 6D AC 9S 3S 3D 5D 9C 2D AC 4S 2S AD 6C 6S QC 4C 2D 3H 6S KC QH QD 2H JH QC 3C 8S 4D 9S 2H 5C 8H QS QD 6D KD 6S 7H 3S KH 2H 5C JC 6C 3S 9S TC 6S 8H 2D AD 7S 8S TS 3C 6H 9C 3H 5C JC 8H QH TD QD 3C JS QD 5D TD 2C KH 9H TH AS 9S TC JD 3D 5C 5H AD QH 9H KC TC 7H 4H 8H 3H TD 6S AC 7C 2S QS 9D 5D 3C JC KS 4D 6C JH 2S 9S 6S 3C 7H TS 4C KD 6D 3D 9C 2D 9H AH AC 7H 2S JH 3S 7C QC QD 9H 3C 2H AC AS 8S KD 8C KH 2D 7S TD TH 6D JD 8D 4D 2H 5S 8S QH KD JD QS JH 4D KC 5H 3S 3C KH QC 6D 8H 3S AH 7D TD 2D 5S 9H QH 4S 6S 6C 6D TS TH 7S 6C 4C 6D QS JS 9C TS 3H 8D 8S JS 5C 7S AS 2C AH 2H AD 5S TC KD 6C 9C 9D TS 2S JC 4H 2C QD QS 9H TC 3H KC KS 4H 3C AD TH KH 9C 2H KD 9D TC 7S KC JH 2D 7C 3S KC AS 8C 5D 9C 9S QH 3H 2D 8C TD 4C 2H QC 5D TC 2C 7D KS 4D 6C QH TD KH 5D 7C AD 8D 2S 9S 8S 4C 8C 3D 6H QD 7C 7H 6C 8S QH 5H TS 5C 3C 4S 2S 2H 8S 6S 2H JC 3S 3H 9D 8C 2S 7H QC 2C 8H 9C AC JD 4C 4H 6S 3S 3H 3S 7D 4C 9S 5H 8H JC 3D TC QH 2S 2D 9S KD QD 9H AD 6D 9C 8D 2D KS 9S JC 4C JD KC 4S TH KH TS 6D 4D 5C KD 5H AS 9H AD QD JS 7C 6D 5D 5C TH 5H QH QS 9D QH KH 5H JH 4C 4D TC TH 6C KH AS TS 9D KD 9C 7S 4D 8H 5S KH AS 2S 7D 9D 4C TS TH AH 7C KS 4D AC 8S 9S 8D TH QH 9D 5C 5D 5C 8C QS TC 4C 3D 3S 2C 8D 9D KS 2D 3C KC 4S 8C KH 6C JC 8H AH 6H 7D 7S QD 3C 4C 6C KC 3H 2C QH 8H AS 7D 4C 8C 4H KC QD 5S 4H 2C TD AH JH QH 4C 8S 3H QS 5S JS 8H 2S 9H 9C 3S 2C 6H TS 7S JC QD AC TD KC 5S 3H QH AS QS 7D JC KC 2C 4C 5C 5S QH 3D AS JS 4H 8D 7H JC 2S 9C 5D 4D 2S 4S 9D 9C 2D QS 8H 7H 6D 7H 3H JS TS AC 2D JH 7C 8S JH 5H KC 3C TC 5S 9H 4C 8H 9D 8S KC 5H 9H AD KS 9D KH 8D AH JC 2H 9H KS 6S 3H QC 5H AH 9C 5C KH 5S AD 6C JC 9H QC 9C TD 5S 5D JC QH 2D KS 8H QS 2H TS JH 5H 5S AH 7H 3C 8S AS TD KH 6H 3D JD 2C 4C KC 7S AH 6C JH 4C KS 9D AD 7S KC 7D 8H 3S 9C 7H 5C 5H 3C 8H QC 3D KH 6D JC 2D 4H 5D 7D QC AD AH 9H QH 8H KD 8C JS 9D 3S 3C 2H 5D 6D 2S 8S 6S TS 3C 6H 8D 5S 3H TD 6C KS 3D JH 9C 7C 9S QS 5S 4H 6H 7S 6S TH 4S KC KD 3S JC JH KS 7C 3C 2S 6D QH 2C 7S 5H 8H AH KC 8D QD 6D KH 5C 7H 9D 3D 9C 6H 2D 8S JS 9S 2S 6D KC 7C TC KD 9C JH 7H KC 8S 2S 7S 3D 6H 4H 9H 2D 4C 8H 7H 5S 8S 2H 8D AD 7C 3C 7S 5S 4D 9H 3D JC KH 5D AS 7D 6D 9C JC 4C QH QS KH KD JD 7D 3D QS QC 8S 6D JS QD 6S 8C 5S QH TH 9H AS AC 2C JD QC KS QH 7S 3C 4C 5C KC 5D AH 6C 4H 9D AH 2C 3H KD 3D TS 5C TD 8S QS AS JS 3H KD AC 4H KS 7D 5D TS 9H 4H 4C 9C 2H 8C QC 2C 7D 9H 4D KS 4C QH AD KD JS QD AD AH KH 9D JS 9H JC KD JD 8S 3C 4S TS 7S 4D 5C 2S 6H 7C JS 7S 5C KD 6D QH 8S TD 2H 6S QH 6C TC 6H TD 4C 9D 2H QC 8H 3D TS 4D 2H 6H 6S 2C 7H 8S 6C 9H 9D JD JH 3S AH 2C 6S 3H 8S 2C QS 8C 5S 3H 2S 7D 3C AD 4S 5C QC QH AS TS 4S 6S 4C 5H JS JH 5C TD 4C 6H JS KD KH QS 4H TC KH JC 4D 9H 9D 8D KC 3C 8H 2H TC 8S AD 9S 4H TS 7H 2C 5C 4H 2S 6C 5S KS AH 9C 7C 8H KD TS QH TD QS 3C JH AH 2C 8D 7D 5D KC 3H 5S AC 4S 7H QS 4C 2H 3D 7D QC KH JH 6D 6C TD TH KD 5S 8D TH 6C 9D 7D KH 8C 9S 6D JD QS 7S QC 2S QH JC 4S KS 8D 7S 5S 9S JD KD 9C JC AD 2D 7C 4S 5H AH JH 9C 5D TD 7C 2D 6S KC 6C 7H 6S 9C QD 5S 4H KS TD 6S 8D KS 2D TH TD 9H JD TS 3S KH JS 4H 5D 9D TC TD QC JD TS QS QD AC AD 4C 6S 2D AS 3H KC 4C 7C 3C TD QS 9C KC AS 8D AD KC 7H QC 6D 8H 6S 5S AH 7S 8C 3S AD 9H JC 6D JD AS KH 6S JH AD 3D TS KS 7H JH 2D JS QD AC 9C JD 7C 6D TC 6H 6C JC 3D 3S QC KC 3S JC KD 2C 8D AH QS TS AS KD 3D JD 8H 7C 8C 5C QD 6C
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ import math from decimal import Decimal, getcontext def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 >>> solution(3.4) 2 >>> 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.") getcontext().prec = 100 phi = (Decimal(5) ** Decimal(0.5) + 1) / Decimal(2) index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 2 num = Decimal(round(phi ** Decimal(index + 1))) / (phi + 2) total = num // 2 return int(total) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ import math from decimal import Decimal, getcontext def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 >>> solution(3.4) 2 >>> 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.") getcontext().prec = 100 phi = (Decimal(5) ** Decimal(0.5) + 1) / Decimal(2) index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 2 num = Decimal(round(phi ** Decimal(index + 1))) / (phi + 2) total = num // 2 return int(total) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Primality Testing with the Rabin-Miller Algorithm import random def rabin_miller(num: int) -> bool: s = num - 1 t = 0 while s % 2 == 0: s = s // 2 t += 1 for _ in range(5): a = random.randrange(2, num - 1) v = pow(a, s, num) if v != 1: i = 0 while v != (num - 1): if i == t - 1: return False else: i = i + 1 v = (v**2) % num return True def is_prime_low_num(num: int) -> bool: if num < 2: return False low_primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(num) def generate_large_prime(keysize: int = 1024) -> int: while True: num = random.randrange(2 ** (keysize - 1), 2 ** (keysize)) if is_prime_low_num(num): return num if __name__ == "__main__": num = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
# Primality Testing with the Rabin-Miller Algorithm import random def rabin_miller(num: int) -> bool: s = num - 1 t = 0 while s % 2 == 0: s = s // 2 t += 1 for _ in range(5): a = random.randrange(2, num - 1) v = pow(a, s, num) if v != 1: i = 0 while v != (num - 1): if i == t - 1: return False else: i = i + 1 v = (v**2) % num return True def is_prime_low_num(num: int) -> bool: if num < 2: return False low_primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(num) def generate_large_prime(keysize: int = 1024) -> int: while True: num = random.randrange(2 ** (keysize - 1), 2 ** (keysize)) if is_prime_low_num(num): return num if __name__ == "__main__": num = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Gamma function is a very useful tool in math and physics. It helps calculating complex integral in a convenient way. for more info: https://en.wikipedia.org/wiki/Gamma_function Python's Standard Library math.gamma() function overflows around gamma(171.624). """ from math import pi, sqrt def gamma(num: float) -> float: """ Calculates the value of Gamma function of num where num is either an integer (1, 2, 3..) or a half-integer (0.5, 1.5, 2.5 ...). Implemented using recursion Examples: >>> from math import isclose, gamma as math_gamma >>> gamma(0.5) 1.7724538509055159 >>> gamma(2) 1.0 >>> gamma(3.5) 3.3233509704478426 >>> gamma(171.5) 9.483367566824795e+307 >>> all(isclose(gamma(num), math_gamma(num)) for num in (0.5, 2, 3.5, 171.5)) True >>> gamma(0) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(-1.1) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(-4) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(172) Traceback (most recent call last): ... OverflowError: math range error >>> gamma(1.1) Traceback (most recent call last): ... NotImplementedError: num must be an integer or a half-integer """ if num <= 0: raise ValueError("math domain error") if num > 171.5: raise OverflowError("math range error") elif num - int(num) not in (0, 0.5): raise NotImplementedError("num must be an integer or a half-integer") elif num == 0.5: return sqrt(pi) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1) def test_gamma() -> None: """ >>> test_gamma() """ assert gamma(0.5) == sqrt(pi) assert gamma(1) == 1.0 assert gamma(2) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() num = 1.0 while num: num = float(input("Gamma of: ")) print(f"gamma({num}) = {gamma(num)}") print("\nEnter 0 to exit...")
""" Gamma function is a very useful tool in math and physics. It helps calculating complex integral in a convenient way. for more info: https://en.wikipedia.org/wiki/Gamma_function Python's Standard Library math.gamma() function overflows around gamma(171.624). """ from math import pi, sqrt def gamma(num: float) -> float: """ Calculates the value of Gamma function of num where num is either an integer (1, 2, 3..) or a half-integer (0.5, 1.5, 2.5 ...). Implemented using recursion Examples: >>> from math import isclose, gamma as math_gamma >>> gamma(0.5) 1.7724538509055159 >>> gamma(2) 1.0 >>> gamma(3.5) 3.3233509704478426 >>> gamma(171.5) 9.483367566824795e+307 >>> all(isclose(gamma(num), math_gamma(num)) for num in (0.5, 2, 3.5, 171.5)) True >>> gamma(0) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(-1.1) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(-4) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(172) Traceback (most recent call last): ... OverflowError: math range error >>> gamma(1.1) Traceback (most recent call last): ... NotImplementedError: num must be an integer or a half-integer """ if num <= 0: raise ValueError("math domain error") if num > 171.5: raise OverflowError("math range error") elif num - int(num) not in (0, 0.5): raise NotImplementedError("num must be an integer or a half-integer") elif num == 0.5: return sqrt(pi) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1) def test_gamma() -> None: """ >>> test_gamma() """ assert gamma(0.5) == sqrt(pi) assert gamma(1) == 1.0 assert gamma(2) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() num = 1.0 while num: num = float(input("Gamma of: ")) print(f"gamma({num}) = {gamma(num)}") print("\nEnter 0 to exit...")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. A straightforward pythonic solution using list comprehension. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ return sum(i for i in range(n) if i % 3 == 0 or i % 5 == 0) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. A straightforward pythonic solution using list comprehension. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ return sum(i for i in range(n) if i % 3 == 0 or i % 5 == 0) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
519432,525806 632382,518061 78864,613712 466580,530130 780495,510032 525895,525320 15991,714883 960290,502358 760018,511029 166800,575487 210884,564478 555151,523163 681146,515199 563395,522587 738250,512126 923525,503780 595148,520429 177108,572629 750923,511482 440902,532446 881418,505504 422489,534197 979858,501616 685893,514935 747477,511661 167214,575367 234140,559696 940238,503122 728969,512609 232083,560102 900971,504694 688801,514772 189664,569402 891022,505104 445689,531996 119570,591871 821453,508118 371084,539600 911745,504251 623655,518600 144361,582486 352442,541775 420726,534367 295298,549387 6530,787777 468397,529976 672336,515696 431861,533289 84228,610150 805376,508857 444409,532117 33833,663511 381850,538396 402931,536157 92901,604930 304825,548004 731917,512452 753734,511344 51894,637373 151578,580103 295075,549421 303590,548183 333594,544123 683952,515042 60090,628880 951420,502692 28335,674991 714940,513349 343858,542826 549279,523586 804571,508887 260653,554881 291399,549966 402342,536213 408889,535550 40328,652524 375856,539061 768907,510590 165993,575715 976327,501755 898500,504795 360404,540830 478714,529095 694144,514472 488726,528258 841380,507226 328012,544839 22389,690868 604053,519852 329514,544641 772965,510390 492798,527927 30125,670983 895603,504906 450785,531539 840237,507276 380711,538522 63577,625673 76801,615157 502694,527123 597706,520257 310484,547206 944468,502959 121283,591152 451131,531507 566499,522367 425373,533918 40240,652665 39130,654392 714926,513355 469219,529903 806929,508783 287970,550487 92189,605332 103841,599094 671839,515725 452048,531421 987837,501323 935192,503321 88585,607450 613883,519216 144551,582413 647359,517155 213902,563816 184120,570789 258126,555322 502546,527130 407655,535678 401528,536306 477490,529193 841085,507237 732831,512408 833000,507595 904694,504542 581435,521348 455545,531110 873558,505829 94916,603796 720176,513068 545034,523891 246348,557409 556452,523079 832015,507634 173663,573564 502634,527125 250732,556611 569786,522139 216919,563178 521815,525623 92304,605270 164446,576167 753413,511364 11410,740712 448845,531712 925072,503725 564888,522477 7062,780812 641155,517535 738878,512100 636204,517828 372540,539436 443162,532237 571192,522042 655350,516680 299741,548735 581914,521307 965471,502156 513441,526277 808682,508700 237589,559034 543300,524025 804712,508889 247511,557192 543486,524008 504383,526992 326529,545039 792493,509458 86033,609017 126554,589005 579379,521481 948026,502823 404777,535969 265767,554022 266876,553840 46631,643714 492397,527958 856106,506581 795757,509305 748946,511584 294694,549480 409781,535463 775887,510253 543747,523991 210592,564536 517119,525990 520253,525751 247926,557124 592141,520626 346580,542492 544969,523902 506501,526817 244520,557738 144745,582349 69274,620858 292620,549784 926027,503687 736320,512225 515528,526113 407549,535688 848089,506927 24141,685711 9224,757964 980684,501586 175259,573121 489160,528216 878970,505604 969546,502002 525207,525365 690461,514675 156510,578551 659778,516426 468739,529945 765252,510770 76703,615230 165151,575959 29779,671736 928865,503569 577538,521605 927555,503618 185377,570477 974756,501809 800130,509093 217016,563153 365709,540216 774508,510320 588716,520851 631673,518104 954076,502590 777828,510161 990659,501222 597799,520254 786905,509727 512547,526348 756449,511212 869787,505988 653747,516779 84623,609900 839698,507295 30159,670909 797275,509234 678136,515373 897144,504851 989554,501263 413292,535106 55297,633667 788650,509637 486748,528417 150724,580377 56434,632490 77207,614869 588631,520859 611619,519367 100006,601055 528924,525093 190225,569257 851155,506789 682593,515114 613043,519275 514673,526183 877634,505655 878905,505602 1926,914951 613245,519259 152481,579816 841774,507203 71060,619442 865335,506175 90244,606469 302156,548388 399059,536557 478465,529113 558601,522925 69132,620966 267663,553700 988276,501310 378354,538787 529909,525014 161733,576968 758541,511109 823425,508024 149821,580667 269258,553438 481152,528891 120871,591322 972322,501901 981350,501567 676129,515483 950860,502717 119000,592114 392252,537272 191618,568919 946699,502874 289555,550247 799322,509139 703886,513942 194812,568143 261823,554685 203052,566221 217330,563093 734748,512313 391759,537328 807052,508777 564467,522510 59186,629748 113447,594545 518063,525916 905944,504492 613922,519213 439093,532607 445946,531981 230530,560399 297887,549007 459029,530797 403692,536075 855118,506616 963127,502245 841711,507208 407411,535699 924729,503735 914823,504132 333725,544101 176345,572832 912507,504225 411273,535308 259774,555036 632853,518038 119723,591801 163902,576321 22691,689944 402427,536212 175769,572988 837260,507402 603432,519893 313679,546767 538165,524394 549026,523608 61083,627945 898345,504798 992556,501153 369999,539727 32847,665404 891292,505088 152715,579732 824104,507997 234057,559711 730507,512532 960529,502340 388395,537687 958170,502437 57105,631806 186025,570311 993043,501133 576770,521664 215319,563513 927342,503628 521353,525666 39563,653705 752516,511408 110755,595770 309749,547305 374379,539224 919184,503952 990652,501226 647780,517135 187177,570017 168938,574877 649558,517023 278126,552016 162039,576868 658512,516499 498115,527486 896583,504868 561170,522740 747772,511647 775093,510294 652081,516882 724905,512824 499707,527365 47388,642755 646668,517204 571700,522007 180430,571747 710015,513617 435522,532941 98137,602041 759176,511070 486124,528467 526942,525236 878921,505604 408313,535602 926980,503640 882353,505459 566887,522345 3326,853312 911981,504248 416309,534800 392991,537199 622829,518651 148647,581055 496483,527624 666314,516044 48562,641293 672618,515684 443676,532187 274065,552661 265386,554079 347668,542358 31816,667448 181575,571446 961289,502320 365689,540214 987950,501317 932299,503440 27388,677243 746701,511701 492258,527969 147823,581323 57918,630985 838849,507333 678038,515375 27852,676130 850241,506828 818403,508253 131717,587014 850216,506834 904848,504529 189758,569380 392845,537217 470876,529761 925353,503711 285431,550877 454098,531234 823910,508003 318493,546112 766067,510730 261277,554775 421530,534289 694130,514478 120439,591498 213308,563949 854063,506662 365255,540263 165437,575872 662240,516281 289970,550181 847977,506933 546083,523816 413252,535113 975829,501767 361540,540701 235522,559435 224643,561577 736350,512229 328303,544808 35022,661330 307838,547578 474366,529458 873755,505819 73978,617220 827387,507845 670830,515791 326511,545034 309909,547285 400970,536363 884827,505352 718307,513175 28462,674699 599384,520150 253565,556111 284009,551093 343403,542876 446557,531921 992372,501160 961601,502308 696629,514342 919537,503945 894709,504944 892201,505051 358160,541097 448503,531745 832156,507636 920045,503924 926137,503675 416754,534757 254422,555966 92498,605151 826833,507873 660716,516371 689335,514746 160045,577467 814642,508425 969939,501993 242856,558047 76302,615517 472083,529653 587101,520964 99066,601543 498005,527503 709800,513624 708000,513716 20171,698134 285020,550936 266564,553891 981563,501557 846502,506991 334,1190800 209268,564829 9844,752610 996519,501007 410059,535426 432931,533188 848012,506929 966803,502110 983434,501486 160700,577267 504374,526989 832061,507640 392825,537214 443842,532165 440352,532492 745125,511776 13718,726392 661753,516312 70500,619875 436952,532814 424724,533973 21954,692224 262490,554567 716622,513264 907584,504425 60086,628882 837123,507412 971345,501940 947162,502855 139920,584021 68330,621624 666452,516038 731446,512481 953350,502619 183157,571042 845400,507045 651548,516910 20399,697344 861779,506331 629771,518229 801706,509026 189207,569512 737501,512168 719272,513115 479285,529045 136046,585401 896746,504860 891735,505067 684771,514999 865309,506184 379066,538702 503117,527090 621780,518717 209518,564775 677135,515423 987500,501340 197049,567613 329315,544673 236756,559196 357092,541226 520440,525733 213471,563911 956852,502490 702223,514032 404943,535955 178880,572152 689477,514734 691351,514630 866669,506128 370561,539656 739805,512051 71060,619441 624861,518534 261660,554714 366137,540160 166054,575698 601878,519990 153445,579501 279899,551729 379166,538691 423209,534125 675310,515526 145641,582050 691353,514627 917468,504026 284778,550976 81040,612235 161699,576978 616394,519057 767490,510661 156896,578431 427408,533714 254849,555884 737217,512182 897133,504851 203815,566051 270822,553189 135854,585475 778805,510111 784373,509847 305426,547921 733418,512375 732087,512448 540668,524215 702898,513996 628057,518328 640280,517587 422405,534204 10604,746569 746038,511733 839808,507293 457417,530938 479030,529064 341758,543090 620223,518824 251661,556451 561790,522696 497733,527521 724201,512863 489217,528217 415623,534867 624610,518548 847541,506953 432295,533249 400391,536421 961158,502319 139173,584284 421225,534315 579083,521501 74274,617000 701142,514087 374465,539219 217814,562985 358972,540995 88629,607424 288597,550389 285819,550812 538400,524385 809930,508645 738326,512126 955461,502535 163829,576343 826475,507891 376488,538987 102234,599905 114650,594002 52815,636341 434037,533082 804744,508880 98385,601905 856620,506559 220057,562517 844734,507078 150677,580387 558697,522917 621751,518719 207067,565321 135297,585677 932968,503404 604456,519822 579728,521462 244138,557813 706487,513800 711627,513523 853833,506674 497220,527562 59428,629511 564845,522486 623621,518603 242689,558077 125091,589591 363819,540432 686453,514901 656813,516594 489901,528155 386380,537905 542819,524052 243987,557841 693412,514514 488484,528271 896331,504881 336730,543721 728298,512647 604215,519840 153729,579413 595687,520398 540360,524240 245779,557511 924873,503730 509628,526577 528523,525122 3509,847707 522756,525555 895447,504922 44840,646067 45860,644715 463487,530404 398164,536654 894483,504959 619415,518874 966306,502129 990922,501212 835756,507474 548881,523618 453578,531282 474993,529410 80085,612879 737091,512193 50789,638638 979768,501620 792018,509483 665001,516122 86552,608694 462772,530469 589233,520821 891694,505072 592605,520594 209645,564741 42531,649269 554376,523226 803814,508929 334157,544042 175836,572970 868379,506051 658166,516520 278203,551995 966198,502126 627162,518387 296774,549165 311803,547027 843797,507118 702304,514032 563875,522553 33103,664910 191932,568841 543514,524006 506835,526794 868368,506052 847025,506971 678623,515342 876139,505726 571997,521984 598632,520198 213590,563892 625404,518497 726508,512738 689426,514738 332495,544264 411366,535302 242546,558110 315209,546555 797544,509219 93889,604371 858879,506454 124906,589666 449072,531693 235960,559345 642403,517454 720567,513047 705534,513858 603692,519870 488137,528302 157370,578285 63515,625730 666326,516041 619226,518883 443613,532186 597717,520257 96225,603069 86940,608450 40725,651929 460976,530625 268875,553508 270671,553214 363254,540500 384248,538137 762889,510892 377941,538833 278878,551890 176615,572755 860008,506412 944392,502967 608395,519571 225283,561450 45095,645728 333798,544090 625733,518476 995584,501037 506135,526853 238050,558952 557943,522972 530978,524938 634244,517949 177168,572616 85200,609541 953043,502630 523661,525484 999295,500902 840803,507246 961490,502312 471747,529685 380705,538523 911180,504275 334149,544046 478992,529065 325789,545133 335884,543826 426976,533760 749007,511582 667067,516000 607586,519623 674054,515599 188534,569675 565185,522464 172090,573988 87592,608052 907432,504424 8912,760841 928318,503590 757917,511138 718693,513153 315141,546566 728326,512645 353492,541647 638429,517695 628892,518280 877286,505672 620895,518778 385878,537959 423311,534113 633501,517997 884833,505360 883402,505416 999665,500894 708395,513697 548142,523667 756491,511205 987352,501340 766520,510705 591775,520647 833758,507563 843890,507108 925551,503698 74816,616598 646942,517187 354923,541481 256291,555638 634470,517942 930904,503494 134221,586071 282663,551304 986070,501394 123636,590176 123678,590164 481717,528841 423076,534137 866246,506145 93313,604697 783632,509880 317066,546304 502977,527103 141272,583545 71708,618938 617748,518975 581190,521362 193824,568382 682368,515131 352956,541712 351375,541905 505362,526909 905165,504518 128645,588188 267143,553787 158409,577965 482776,528754 628896,518282 485233,528547 563606,522574 111001,595655 115920,593445 365510,540237 959724,502374 938763,503184 930044,503520 970959,501956 913658,504176 68117,621790 989729,501253 567697,522288 820427,508163 54236,634794 291557,549938 124961,589646 403177,536130 405421,535899 410233,535417 815111,508403 213176,563974 83099,610879 998588,500934 513640,526263 129817,587733 1820,921851 287584,550539 299160,548820 860621,506386 529258,525059 586297,521017 953406,502616 441234,532410 986217,501386 781938,509957 461247,530595 735424,512277 146623,581722 839838,507288 510667,526494 935085,503327 737523,512167 303455,548204 992779,501145 60240,628739 939095,503174 794368,509370 501825,527189 459028,530798 884641,505363 512287,526364 835165,507499 307723,547590 160587,577304 735043,512300 493289,527887 110717,595785 306480,547772 318593,546089 179810,571911 200531,566799 314999,546580 197020,567622 301465,548487 237808,559000 131944,586923 882527,505449 468117,530003 711319,513541 156240,578628 965452,502162 992756,501148 437959,532715 739938,512046 614249,519196 391496,537356 62746,626418 688215,514806 75501,616091 883573,505412 558824,522910 759371,511061 173913,573489 891351,505089 727464,512693 164833,576051 812317,508529 540320,524243 698061,514257 69149,620952 471673,529694 159092,577753 428134,533653 89997,606608 711061,513557 779403,510081 203327,566155 798176,509187 667688,515963 636120,517833 137410,584913 217615,563034 556887,523038 667229,515991 672276,515708 325361,545187 172115,573985 13846,725685
519432,525806 632382,518061 78864,613712 466580,530130 780495,510032 525895,525320 15991,714883 960290,502358 760018,511029 166800,575487 210884,564478 555151,523163 681146,515199 563395,522587 738250,512126 923525,503780 595148,520429 177108,572629 750923,511482 440902,532446 881418,505504 422489,534197 979858,501616 685893,514935 747477,511661 167214,575367 234140,559696 940238,503122 728969,512609 232083,560102 900971,504694 688801,514772 189664,569402 891022,505104 445689,531996 119570,591871 821453,508118 371084,539600 911745,504251 623655,518600 144361,582486 352442,541775 420726,534367 295298,549387 6530,787777 468397,529976 672336,515696 431861,533289 84228,610150 805376,508857 444409,532117 33833,663511 381850,538396 402931,536157 92901,604930 304825,548004 731917,512452 753734,511344 51894,637373 151578,580103 295075,549421 303590,548183 333594,544123 683952,515042 60090,628880 951420,502692 28335,674991 714940,513349 343858,542826 549279,523586 804571,508887 260653,554881 291399,549966 402342,536213 408889,535550 40328,652524 375856,539061 768907,510590 165993,575715 976327,501755 898500,504795 360404,540830 478714,529095 694144,514472 488726,528258 841380,507226 328012,544839 22389,690868 604053,519852 329514,544641 772965,510390 492798,527927 30125,670983 895603,504906 450785,531539 840237,507276 380711,538522 63577,625673 76801,615157 502694,527123 597706,520257 310484,547206 944468,502959 121283,591152 451131,531507 566499,522367 425373,533918 40240,652665 39130,654392 714926,513355 469219,529903 806929,508783 287970,550487 92189,605332 103841,599094 671839,515725 452048,531421 987837,501323 935192,503321 88585,607450 613883,519216 144551,582413 647359,517155 213902,563816 184120,570789 258126,555322 502546,527130 407655,535678 401528,536306 477490,529193 841085,507237 732831,512408 833000,507595 904694,504542 581435,521348 455545,531110 873558,505829 94916,603796 720176,513068 545034,523891 246348,557409 556452,523079 832015,507634 173663,573564 502634,527125 250732,556611 569786,522139 216919,563178 521815,525623 92304,605270 164446,576167 753413,511364 11410,740712 448845,531712 925072,503725 564888,522477 7062,780812 641155,517535 738878,512100 636204,517828 372540,539436 443162,532237 571192,522042 655350,516680 299741,548735 581914,521307 965471,502156 513441,526277 808682,508700 237589,559034 543300,524025 804712,508889 247511,557192 543486,524008 504383,526992 326529,545039 792493,509458 86033,609017 126554,589005 579379,521481 948026,502823 404777,535969 265767,554022 266876,553840 46631,643714 492397,527958 856106,506581 795757,509305 748946,511584 294694,549480 409781,535463 775887,510253 543747,523991 210592,564536 517119,525990 520253,525751 247926,557124 592141,520626 346580,542492 544969,523902 506501,526817 244520,557738 144745,582349 69274,620858 292620,549784 926027,503687 736320,512225 515528,526113 407549,535688 848089,506927 24141,685711 9224,757964 980684,501586 175259,573121 489160,528216 878970,505604 969546,502002 525207,525365 690461,514675 156510,578551 659778,516426 468739,529945 765252,510770 76703,615230 165151,575959 29779,671736 928865,503569 577538,521605 927555,503618 185377,570477 974756,501809 800130,509093 217016,563153 365709,540216 774508,510320 588716,520851 631673,518104 954076,502590 777828,510161 990659,501222 597799,520254 786905,509727 512547,526348 756449,511212 869787,505988 653747,516779 84623,609900 839698,507295 30159,670909 797275,509234 678136,515373 897144,504851 989554,501263 413292,535106 55297,633667 788650,509637 486748,528417 150724,580377 56434,632490 77207,614869 588631,520859 611619,519367 100006,601055 528924,525093 190225,569257 851155,506789 682593,515114 613043,519275 514673,526183 877634,505655 878905,505602 1926,914951 613245,519259 152481,579816 841774,507203 71060,619442 865335,506175 90244,606469 302156,548388 399059,536557 478465,529113 558601,522925 69132,620966 267663,553700 988276,501310 378354,538787 529909,525014 161733,576968 758541,511109 823425,508024 149821,580667 269258,553438 481152,528891 120871,591322 972322,501901 981350,501567 676129,515483 950860,502717 119000,592114 392252,537272 191618,568919 946699,502874 289555,550247 799322,509139 703886,513942 194812,568143 261823,554685 203052,566221 217330,563093 734748,512313 391759,537328 807052,508777 564467,522510 59186,629748 113447,594545 518063,525916 905944,504492 613922,519213 439093,532607 445946,531981 230530,560399 297887,549007 459029,530797 403692,536075 855118,506616 963127,502245 841711,507208 407411,535699 924729,503735 914823,504132 333725,544101 176345,572832 912507,504225 411273,535308 259774,555036 632853,518038 119723,591801 163902,576321 22691,689944 402427,536212 175769,572988 837260,507402 603432,519893 313679,546767 538165,524394 549026,523608 61083,627945 898345,504798 992556,501153 369999,539727 32847,665404 891292,505088 152715,579732 824104,507997 234057,559711 730507,512532 960529,502340 388395,537687 958170,502437 57105,631806 186025,570311 993043,501133 576770,521664 215319,563513 927342,503628 521353,525666 39563,653705 752516,511408 110755,595770 309749,547305 374379,539224 919184,503952 990652,501226 647780,517135 187177,570017 168938,574877 649558,517023 278126,552016 162039,576868 658512,516499 498115,527486 896583,504868 561170,522740 747772,511647 775093,510294 652081,516882 724905,512824 499707,527365 47388,642755 646668,517204 571700,522007 180430,571747 710015,513617 435522,532941 98137,602041 759176,511070 486124,528467 526942,525236 878921,505604 408313,535602 926980,503640 882353,505459 566887,522345 3326,853312 911981,504248 416309,534800 392991,537199 622829,518651 148647,581055 496483,527624 666314,516044 48562,641293 672618,515684 443676,532187 274065,552661 265386,554079 347668,542358 31816,667448 181575,571446 961289,502320 365689,540214 987950,501317 932299,503440 27388,677243 746701,511701 492258,527969 147823,581323 57918,630985 838849,507333 678038,515375 27852,676130 850241,506828 818403,508253 131717,587014 850216,506834 904848,504529 189758,569380 392845,537217 470876,529761 925353,503711 285431,550877 454098,531234 823910,508003 318493,546112 766067,510730 261277,554775 421530,534289 694130,514478 120439,591498 213308,563949 854063,506662 365255,540263 165437,575872 662240,516281 289970,550181 847977,506933 546083,523816 413252,535113 975829,501767 361540,540701 235522,559435 224643,561577 736350,512229 328303,544808 35022,661330 307838,547578 474366,529458 873755,505819 73978,617220 827387,507845 670830,515791 326511,545034 309909,547285 400970,536363 884827,505352 718307,513175 28462,674699 599384,520150 253565,556111 284009,551093 343403,542876 446557,531921 992372,501160 961601,502308 696629,514342 919537,503945 894709,504944 892201,505051 358160,541097 448503,531745 832156,507636 920045,503924 926137,503675 416754,534757 254422,555966 92498,605151 826833,507873 660716,516371 689335,514746 160045,577467 814642,508425 969939,501993 242856,558047 76302,615517 472083,529653 587101,520964 99066,601543 498005,527503 709800,513624 708000,513716 20171,698134 285020,550936 266564,553891 981563,501557 846502,506991 334,1190800 209268,564829 9844,752610 996519,501007 410059,535426 432931,533188 848012,506929 966803,502110 983434,501486 160700,577267 504374,526989 832061,507640 392825,537214 443842,532165 440352,532492 745125,511776 13718,726392 661753,516312 70500,619875 436952,532814 424724,533973 21954,692224 262490,554567 716622,513264 907584,504425 60086,628882 837123,507412 971345,501940 947162,502855 139920,584021 68330,621624 666452,516038 731446,512481 953350,502619 183157,571042 845400,507045 651548,516910 20399,697344 861779,506331 629771,518229 801706,509026 189207,569512 737501,512168 719272,513115 479285,529045 136046,585401 896746,504860 891735,505067 684771,514999 865309,506184 379066,538702 503117,527090 621780,518717 209518,564775 677135,515423 987500,501340 197049,567613 329315,544673 236756,559196 357092,541226 520440,525733 213471,563911 956852,502490 702223,514032 404943,535955 178880,572152 689477,514734 691351,514630 866669,506128 370561,539656 739805,512051 71060,619441 624861,518534 261660,554714 366137,540160 166054,575698 601878,519990 153445,579501 279899,551729 379166,538691 423209,534125 675310,515526 145641,582050 691353,514627 917468,504026 284778,550976 81040,612235 161699,576978 616394,519057 767490,510661 156896,578431 427408,533714 254849,555884 737217,512182 897133,504851 203815,566051 270822,553189 135854,585475 778805,510111 784373,509847 305426,547921 733418,512375 732087,512448 540668,524215 702898,513996 628057,518328 640280,517587 422405,534204 10604,746569 746038,511733 839808,507293 457417,530938 479030,529064 341758,543090 620223,518824 251661,556451 561790,522696 497733,527521 724201,512863 489217,528217 415623,534867 624610,518548 847541,506953 432295,533249 400391,536421 961158,502319 139173,584284 421225,534315 579083,521501 74274,617000 701142,514087 374465,539219 217814,562985 358972,540995 88629,607424 288597,550389 285819,550812 538400,524385 809930,508645 738326,512126 955461,502535 163829,576343 826475,507891 376488,538987 102234,599905 114650,594002 52815,636341 434037,533082 804744,508880 98385,601905 856620,506559 220057,562517 844734,507078 150677,580387 558697,522917 621751,518719 207067,565321 135297,585677 932968,503404 604456,519822 579728,521462 244138,557813 706487,513800 711627,513523 853833,506674 497220,527562 59428,629511 564845,522486 623621,518603 242689,558077 125091,589591 363819,540432 686453,514901 656813,516594 489901,528155 386380,537905 542819,524052 243987,557841 693412,514514 488484,528271 896331,504881 336730,543721 728298,512647 604215,519840 153729,579413 595687,520398 540360,524240 245779,557511 924873,503730 509628,526577 528523,525122 3509,847707 522756,525555 895447,504922 44840,646067 45860,644715 463487,530404 398164,536654 894483,504959 619415,518874 966306,502129 990922,501212 835756,507474 548881,523618 453578,531282 474993,529410 80085,612879 737091,512193 50789,638638 979768,501620 792018,509483 665001,516122 86552,608694 462772,530469 589233,520821 891694,505072 592605,520594 209645,564741 42531,649269 554376,523226 803814,508929 334157,544042 175836,572970 868379,506051 658166,516520 278203,551995 966198,502126 627162,518387 296774,549165 311803,547027 843797,507118 702304,514032 563875,522553 33103,664910 191932,568841 543514,524006 506835,526794 868368,506052 847025,506971 678623,515342 876139,505726 571997,521984 598632,520198 213590,563892 625404,518497 726508,512738 689426,514738 332495,544264 411366,535302 242546,558110 315209,546555 797544,509219 93889,604371 858879,506454 124906,589666 449072,531693 235960,559345 642403,517454 720567,513047 705534,513858 603692,519870 488137,528302 157370,578285 63515,625730 666326,516041 619226,518883 443613,532186 597717,520257 96225,603069 86940,608450 40725,651929 460976,530625 268875,553508 270671,553214 363254,540500 384248,538137 762889,510892 377941,538833 278878,551890 176615,572755 860008,506412 944392,502967 608395,519571 225283,561450 45095,645728 333798,544090 625733,518476 995584,501037 506135,526853 238050,558952 557943,522972 530978,524938 634244,517949 177168,572616 85200,609541 953043,502630 523661,525484 999295,500902 840803,507246 961490,502312 471747,529685 380705,538523 911180,504275 334149,544046 478992,529065 325789,545133 335884,543826 426976,533760 749007,511582 667067,516000 607586,519623 674054,515599 188534,569675 565185,522464 172090,573988 87592,608052 907432,504424 8912,760841 928318,503590 757917,511138 718693,513153 315141,546566 728326,512645 353492,541647 638429,517695 628892,518280 877286,505672 620895,518778 385878,537959 423311,534113 633501,517997 884833,505360 883402,505416 999665,500894 708395,513697 548142,523667 756491,511205 987352,501340 766520,510705 591775,520647 833758,507563 843890,507108 925551,503698 74816,616598 646942,517187 354923,541481 256291,555638 634470,517942 930904,503494 134221,586071 282663,551304 986070,501394 123636,590176 123678,590164 481717,528841 423076,534137 866246,506145 93313,604697 783632,509880 317066,546304 502977,527103 141272,583545 71708,618938 617748,518975 581190,521362 193824,568382 682368,515131 352956,541712 351375,541905 505362,526909 905165,504518 128645,588188 267143,553787 158409,577965 482776,528754 628896,518282 485233,528547 563606,522574 111001,595655 115920,593445 365510,540237 959724,502374 938763,503184 930044,503520 970959,501956 913658,504176 68117,621790 989729,501253 567697,522288 820427,508163 54236,634794 291557,549938 124961,589646 403177,536130 405421,535899 410233,535417 815111,508403 213176,563974 83099,610879 998588,500934 513640,526263 129817,587733 1820,921851 287584,550539 299160,548820 860621,506386 529258,525059 586297,521017 953406,502616 441234,532410 986217,501386 781938,509957 461247,530595 735424,512277 146623,581722 839838,507288 510667,526494 935085,503327 737523,512167 303455,548204 992779,501145 60240,628739 939095,503174 794368,509370 501825,527189 459028,530798 884641,505363 512287,526364 835165,507499 307723,547590 160587,577304 735043,512300 493289,527887 110717,595785 306480,547772 318593,546089 179810,571911 200531,566799 314999,546580 197020,567622 301465,548487 237808,559000 131944,586923 882527,505449 468117,530003 711319,513541 156240,578628 965452,502162 992756,501148 437959,532715 739938,512046 614249,519196 391496,537356 62746,626418 688215,514806 75501,616091 883573,505412 558824,522910 759371,511061 173913,573489 891351,505089 727464,512693 164833,576051 812317,508529 540320,524243 698061,514257 69149,620952 471673,529694 159092,577753 428134,533653 89997,606608 711061,513557 779403,510081 203327,566155 798176,509187 667688,515963 636120,517833 137410,584913 217615,563034 556887,523038 667229,515991 672276,515708 325361,545187 172115,573985 13846,725685
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore filepaths = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" upper_files = [file for file in filepaths if file != file.lower()] if upper_files: print(f"{len(upper_files)} files contain uppercase characters:") print("\n".join(upper_files) + "\n") space_files = [file for file in filepaths if " " in file] if space_files: print(f"{len(space_files)} files contain space characters:") print("\n".join(space_files) + "\n") hyphen_files = [file for file in filepaths if "-" in file] if hyphen_files: print(f"{len(hyphen_files)} files contain hyphen characters:") print("\n".join(hyphen_files) + "\n") nodir_files = [file for file in filepaths if os.sep not in file] if nodir_files: print(f"{len(nodir_files)} files are not in a directory:") print("\n".join(nodir_files) + "\n") bad_files = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
#!/usr/bin/env python3 import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore filepaths = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" upper_files = [file for file in filepaths if file != file.lower()] if upper_files: print(f"{len(upper_files)} files contain uppercase characters:") print("\n".join(upper_files) + "\n") space_files = [file for file in filepaths if " " in file] if space_files: print(f"{len(space_files)} files contain space characters:") print("\n".join(space_files) + "\n") hyphen_files = [file for file in filepaths if "-" in file] if hyphen_files: print(f"{len(hyphen_files)} files contain hyphen characters:") print("\n".join(hyphen_files) + "\n") nodir_files = [file for file in filepaths if os.sep not in file] if nodir_files: print(f"{len(nodir_files)} files are not in a directory:") print("\n".join(nodir_files) + "\n") bad_files = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from datetime import datetime import requests def download_video(url: str) -> bytes: base_url = "https://downloadgram.net/wp-json/wppress/video-downloader/video?url=" video_url = requests.get(base_url + url).json()[0]["urls"][0]["src"] return requests.get(video_url).content if __name__ == "__main__": url = input("Enter Video/IGTV url: ").strip() file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4" with open(file_name, "wb") as fp: fp.write(download_video(url)) print(f"Done. Video saved to disk as {file_name}.")
from datetime import datetime import requests def download_video(url: str) -> bytes: base_url = "https://downloadgram.net/wp-json/wppress/video-downloader/video?url=" video_url = requests.get(base_url + url).json()[0]["urls"][0]["src"] return requests.get(video_url).content if __name__ == "__main__": url = input("Enter Video/IGTV url: ").strip() file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4" with open(file_name, "wb") as fp: fp.write(download_video(url)) print(f"Done. Video saved to disk as {file_name}.")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from typing import Any class Node: def __init__(self, data: Any): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): temp = self.head while temp is not None: print(temp.data, end=" ") temp = temp.next print() # adding nodes def push(self, new_data: Any): new_node = Node(new_data) new_node.next = self.head self.head = new_node # swapping nodes def swap_nodes(self, node_data_1, node_data_2): if node_data_1 == node_data_2: return else: node_1 = self.head while node_1 is not None and node_1.data != node_data_1: node_1 = node_1.next node_2 = self.head while node_2 is not None and node_2.data != node_data_2: node_2 = node_2.next if node_1 is None or node_2 is None: return node_1.data, node_2.data = node_2.data, node_1.data if __name__ == "__main__": ll = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print("After swapping") ll.print_list()
from typing import Any class Node: def __init__(self, data: Any): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): temp = self.head while temp is not None: print(temp.data, end=" ") temp = temp.next print() # adding nodes def push(self, new_data: Any): new_node = Node(new_data) new_node.next = self.head self.head = new_node # swapping nodes def swap_nodes(self, node_data_1, node_data_2): if node_data_1 == node_data_2: return else: node_1 = self.head while node_1 is not None and node_1.data != node_data_1: node_1 = node_1.next node_2 = self.head while node_2 is not None and node_2.data != node_data_2: node_2 = node_2.next if node_1 is None or node_2 is None: return node_1.data, node_2.data = node_2.data, node_1.data if __name__ == "__main__": ll = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print("After swapping") ll.print_list()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def get_set_bits_count(number: int) -> int: """ Count the number of set bits in a 32 bit integer >>> get_set_bits_count(25) 3 >>> get_set_bits_count(37) 3 >>> get_set_bits_count(21) 3 >>> get_set_bits_count(58) 4 >>> get_set_bits_count(0) 0 >>> get_set_bits_count(256) 1 >>> get_set_bits_count(-1) Traceback (most recent call last): ... ValueError: the value of input must be positive """ if number < 0: raise ValueError("the value of input must be positive") result = 0 while number: if number % 2 == 1: result += 1 number = number >> 1 return result if __name__ == "__main__": import doctest doctest.testmod()
def get_set_bits_count(number: int) -> int: """ Count the number of set bits in a 32 bit integer >>> get_set_bits_count(25) 3 >>> get_set_bits_count(37) 3 >>> get_set_bits_count(21) 3 >>> get_set_bits_count(58) 4 >>> get_set_bits_count(0) 0 >>> get_set_bits_count(256) 1 >>> get_set_bits_count(-1) Traceback (most recent call last): ... ValueError: the value of input must be positive """ if number < 0: raise ValueError("the value of input must be positive") result = 0 while number: if number % 2 == 1: result += 1 number = number >> 1 return result if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import re def dna(dna: str) -> str: """ https://en.wikipedia.org/wiki/DNA Returns the second side of a DNA strand >>> dna("GCTA") 'CGAT' >>> dna("ATGC") 'TACG' >>> dna("CTGA") 'GACT' >>> dna("GFGG") 'Invalid Strand' """ r = len(re.findall("[ATCG]", dna)) != len(dna) val = dna.translate(dna.maketrans("ATCG", "TAGC")) return "Invalid Strand" if r else val if __name__ == "__main__": __import__("doctest").testmod()
import re def dna(dna: str) -> str: """ https://en.wikipedia.org/wiki/DNA Returns the second side of a DNA strand >>> dna("GCTA") 'CGAT' >>> dna("ATGC") 'TACG' >>> dna("CTGA") 'GACT' >>> dna("GFGG") 'Invalid Strand' """ r = len(re.findall("[ATCG]", dna)) != len(dna) val = dna.translate(dna.maketrans("ATCG", "TAGC")) return "Invalid Strand" if r else val if __name__ == "__main__": __import__("doctest").testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Cocktail_shaker_sort """ def cocktail_shaker_sort(unsorted: list) -> list: """ Pure implementation of the cocktail shaker sort algorithm in Python. >>> cocktail_shaker_sort([4, 5, 2, 1, 2]) [1, 2, 2, 4, 5] >>> cocktail_shaker_sort([-4, 5, 0, 1, 2, 11]) [-4, 0, 1, 2, 5, 11] >>> cocktail_shaker_sort([0.1, -2.4, 4.4, 2.2]) [-2.4, 0.1, 2.2, 4.4] >>> cocktail_shaker_sort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> cocktail_shaker_sort([-4, -5, -24, -7, -11]) [-24, -11, -7, -5, -4] """ for i in range(len(unsorted) - 1, 0, -1): swapped = False for j in range(i, 0, -1): if unsorted[j] < unsorted[j - 1]: unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j] swapped = True for j in range(i): if unsorted[j] > unsorted[j + 1]: unsorted[j], unsorted[j + 1] = unsorted[j + 1], unsorted[j] swapped = True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{cocktail_shaker_sort(unsorted) = }")
""" https://en.wikipedia.org/wiki/Cocktail_shaker_sort """ def cocktail_shaker_sort(unsorted: list) -> list: """ Pure implementation of the cocktail shaker sort algorithm in Python. >>> cocktail_shaker_sort([4, 5, 2, 1, 2]) [1, 2, 2, 4, 5] >>> cocktail_shaker_sort([-4, 5, 0, 1, 2, 11]) [-4, 0, 1, 2, 5, 11] >>> cocktail_shaker_sort([0.1, -2.4, 4.4, 2.2]) [-2.4, 0.1, 2.2, 4.4] >>> cocktail_shaker_sort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> cocktail_shaker_sort([-4, -5, -24, -7, -11]) [-24, -11, -7, -5, -4] """ for i in range(len(unsorted) - 1, 0, -1): swapped = False for j in range(i, 0, -1): if unsorted[j] < unsorted[j - 1]: unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j] swapped = True for j in range(i): if unsorted[j] > unsorted[j + 1]: unsorted[j], unsorted[j + 1] = unsorted[j + 1], unsorted[j] swapped = True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{cocktail_shaker_sort(unsorted) = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_xor(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary xor operation on the integers provided. >>> binary_xor(25, 32) '0b111001' >>> binary_xor(37, 50) '0b010111' >>> binary_xor(21, 30) '0b01011' >>> binary_xor(58, 73) '0b1110011' >>> binary_xor(0, 255) '0b11111111' >>> binary_xor(256, 256) '0b000000000' >>> binary_xor(0, -1) Traceback (most recent call last): ... ValueError: the value of both inputs must be positive >>> binary_xor(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_xor("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] # remove the leading "0b" max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int(char_a != char_b)) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_xor(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary xor operation on the integers provided. >>> binary_xor(25, 32) '0b111001' >>> binary_xor(37, 50) '0b010111' >>> binary_xor(21, 30) '0b01011' >>> binary_xor(58, 73) '0b1110011' >>> binary_xor(0, 255) '0b11111111' >>> binary_xor(256, 256) '0b000000000' >>> binary_xor(0, -1) Traceback (most recent call last): ... ValueError: the value of both inputs must be positive >>> binary_xor(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_xor("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] # remove the leading "0b" max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int(char_a != char_b)) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
### Interest * Compound Interest: "Compound interest is calculated by multiplying the initial principal amount by one plus the annual interest rate raised to the number of compound periods minus one." [Compound Interest](https://www.investopedia.com/) * Simple Interest: "Simple interest paid or received over a certain period is a fixed percentage of the principal amount that was borrowed or lent. " [Simple Interest](https://www.investopedia.com/)
### Interest * Compound Interest: "Compound interest is calculated by multiplying the initial principal amount by one plus the annual interest rate raised to the number of compound periods minus one." [Compound Interest](https://www.investopedia.com/) * Simple Interest: "Simple interest paid or received over a certain period is a fixed percentage of the principal amount that was borrowed or lent. " [Simple Interest](https://www.investopedia.com/)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from timeit import timeit def sum_of_digits(n: int) -> int: """ Find the sum of digits of a number. >>> sum_of_digits(12345) 15 >>> sum_of_digits(123) 6 >>> sum_of_digits(-123) 6 >>> sum_of_digits(0) 0 """ n = -n if n < 0 else n res = 0 while n > 0: res += n % 10 n = n // 10 return res def sum_of_digits_recursion(n: int) -> int: """ Find the sum of digits of a number using recursion >>> sum_of_digits_recursion(12345) 15 >>> sum_of_digits_recursion(123) 6 >>> sum_of_digits_recursion(-123) 6 >>> sum_of_digits_recursion(0) 0 """ n = -n if n < 0 else n return n if n < 10 else n % 10 + sum_of_digits(n // 10) def sum_of_digits_compact(n: int) -> int: """ Find the sum of digits of a number >>> sum_of_digits_compact(12345) 15 >>> sum_of_digits_compact(123) 6 >>> sum_of_digits_compact(-123) 6 >>> sum_of_digits_compact(0) 0 """ return sum(int(c) for c in str(abs(n))) def benchmark() -> None: """ Benchmark code for comparing 3 functions, with 3 different length int values. """ print("\nFor small_num = ", small_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(small_num), "\ttime =", timeit("z.sum_of_digits(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(small_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(small_num), "\ttime =", timeit("z.sum_of_digits_compact(z.small_num)", setup="import __main__ as z"), "seconds", ) print("\nFor medium_num = ", medium_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(medium_num), "\ttime =", timeit("z.sum_of_digits(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(medium_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(medium_num), "\ttime =", timeit("z.sum_of_digits_compact(z.medium_num)", setup="import __main__ as z"), "seconds", ) print("\nFor large_num = ", large_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(large_num), "\ttime =", timeit("z.sum_of_digits(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(large_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(large_num), "\ttime =", timeit("z.sum_of_digits_compact(z.large_num)", setup="import __main__ as z"), "seconds", ) if __name__ == "__main__": small_num = 262144 medium_num = 1125899906842624 large_num = 1267650600228229401496703205376 benchmark() import doctest doctest.testmod()
from timeit import timeit def sum_of_digits(n: int) -> int: """ Find the sum of digits of a number. >>> sum_of_digits(12345) 15 >>> sum_of_digits(123) 6 >>> sum_of_digits(-123) 6 >>> sum_of_digits(0) 0 """ n = -n if n < 0 else n res = 0 while n > 0: res += n % 10 n = n // 10 return res def sum_of_digits_recursion(n: int) -> int: """ Find the sum of digits of a number using recursion >>> sum_of_digits_recursion(12345) 15 >>> sum_of_digits_recursion(123) 6 >>> sum_of_digits_recursion(-123) 6 >>> sum_of_digits_recursion(0) 0 """ n = -n if n < 0 else n return n if n < 10 else n % 10 + sum_of_digits(n // 10) def sum_of_digits_compact(n: int) -> int: """ Find the sum of digits of a number >>> sum_of_digits_compact(12345) 15 >>> sum_of_digits_compact(123) 6 >>> sum_of_digits_compact(-123) 6 >>> sum_of_digits_compact(0) 0 """ return sum(int(c) for c in str(abs(n))) def benchmark() -> None: """ Benchmark code for comparing 3 functions, with 3 different length int values. """ print("\nFor small_num = ", small_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(small_num), "\ttime =", timeit("z.sum_of_digits(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(small_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(small_num), "\ttime =", timeit("z.sum_of_digits_compact(z.small_num)", setup="import __main__ as z"), "seconds", ) print("\nFor medium_num = ", medium_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(medium_num), "\ttime =", timeit("z.sum_of_digits(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(medium_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(medium_num), "\ttime =", timeit("z.sum_of_digits_compact(z.medium_num)", setup="import __main__ as z"), "seconds", ) print("\nFor large_num = ", large_num, ":") print( "> sum_of_digits()", "\t\tans =", sum_of_digits(large_num), "\ttime =", timeit("z.sum_of_digits(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_recursion()", "\tans =", sum_of_digits_recursion(large_num), "\ttime =", timeit("z.sum_of_digits_recursion(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> sum_of_digits_compact()", "\tans =", sum_of_digits_compact(large_num), "\ttime =", timeit("z.sum_of_digits_compact(z.large_num)", setup="import __main__ as z"), "seconds", ) if __name__ == "__main__": small_num = 262144 medium_num = 1125899906842624 large_num = 1267650600228229401496703205376 benchmark() import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def merge(left_half: list, right_half: list) -> list: """Helper function for mergesort. >>> left_half = [-2] >>> right_half = [-1] >>> merge(left_half, right_half) [-2, -1] >>> left_half = [1,2,3] >>> right_half = [4,5,6] >>> merge(left_half, right_half) [1, 2, 3, 4, 5, 6] >>> left_half = [-2] >>> right_half = [-1] >>> merge(left_half, right_half) [-2, -1] >>> left_half = [12, 15] >>> right_half = [13, 14] >>> merge(left_half, right_half) [12, 13, 14, 15] >>> left_half = [] >>> right_half = [] >>> merge(left_half, right_half) [] """ sorted_array = [None] * (len(right_half) + len(left_half)) pointer1 = 0 # pointer to current index for left Half pointer2 = 0 # pointer to current index for the right Half index = 0 # pointer to current index for the sorted array Half while pointer1 < len(left_half) and pointer2 < len(right_half): if left_half[pointer1] < right_half[pointer2]: sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 else: sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 while pointer1 < len(left_half): sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 while pointer2 < len(right_half): sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 return sorted_array def merge_sort(array: list) -> list: """Returns a list of sorted array elements using merge sort. >>> from random import shuffle >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200] >>> shuffle(array) >>> merge_sort(array) [-200, -10, -2, 3, 11, 99, 100, 100000] >>> shuffle(array) >>> merge_sort(array) [-200, -10, -2, 3, 11, 99, 100, 100000] >>> array = [-200] >>> merge_sort(array) [-200] >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200] >>> shuffle(array) >>> sorted(array) == merge_sort(array) True >>> array = [-2] >>> merge_sort(array) [-2] >>> array = [] >>> merge_sort(array) [] >>> array = [10000000, 1, -1111111111, 101111111112, 9000002] >>> sorted(array) == merge_sort(array) True """ if len(array) <= 1: return array # the actual formula to calculate the middle element = left + (right - left) // 2 # this avoids integer overflow in case of large N middle = 0 + (len(array) - 0) // 2 # Split the array into halves till the array length becomes equal to One # merge the arrays of single length returned by mergeSort function and # pass them into the merge arrays function which merges the array left_half = array[:middle] right_half = array[middle:] return merge(merge_sort(left_half), merge_sort(right_half)) if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations def merge(left_half: list, right_half: list) -> list: """Helper function for mergesort. >>> left_half = [-2] >>> right_half = [-1] >>> merge(left_half, right_half) [-2, -1] >>> left_half = [1,2,3] >>> right_half = [4,5,6] >>> merge(left_half, right_half) [1, 2, 3, 4, 5, 6] >>> left_half = [-2] >>> right_half = [-1] >>> merge(left_half, right_half) [-2, -1] >>> left_half = [12, 15] >>> right_half = [13, 14] >>> merge(left_half, right_half) [12, 13, 14, 15] >>> left_half = [] >>> right_half = [] >>> merge(left_half, right_half) [] """ sorted_array = [None] * (len(right_half) + len(left_half)) pointer1 = 0 # pointer to current index for left Half pointer2 = 0 # pointer to current index for the right Half index = 0 # pointer to current index for the sorted array Half while pointer1 < len(left_half) and pointer2 < len(right_half): if left_half[pointer1] < right_half[pointer2]: sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 else: sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 while pointer1 < len(left_half): sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 while pointer2 < len(right_half): sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 return sorted_array def merge_sort(array: list) -> list: """Returns a list of sorted array elements using merge sort. >>> from random import shuffle >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200] >>> shuffle(array) >>> merge_sort(array) [-200, -10, -2, 3, 11, 99, 100, 100000] >>> shuffle(array) >>> merge_sort(array) [-200, -10, -2, 3, 11, 99, 100, 100000] >>> array = [-200] >>> merge_sort(array) [-200] >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200] >>> shuffle(array) >>> sorted(array) == merge_sort(array) True >>> array = [-2] >>> merge_sort(array) [-2] >>> array = [] >>> merge_sort(array) [] >>> array = [10000000, 1, -1111111111, 101111111112, 9000002] >>> sorted(array) == merge_sort(array) True """ if len(array) <= 1: return array # the actual formula to calculate the middle element = left + (right - left) // 2 # this avoids integer overflow in case of large N middle = 0 + (len(array) - 0) // 2 # Split the array into halves till the array length becomes equal to One # merge the arrays of single length returned by mergeSort function and # pass them into the merge arrays function which merges the array left_half = array[:middle] right_half = array[middle:] return merge(merge_sort(left_half), merge_sort(right_half)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Welcome to Quantum Algorithms Started at https://github.com/TheAlgorithms/Python/issues/1831 * D-Wave: https://www.dwavesys.com and https://github.com/dwavesystems * Google: https://research.google/teams/applied-science/quantum * IBM: https://qiskit.org and https://github.com/Qiskit * Rigetti: https://rigetti.com and https://github.com/rigetti * Zapata: https://www.zapatacomputing.com and https://github.com/zapatacomputing ## IBM Qiskit - Start using by installing `pip install qiskit`, refer the [docs](https://qiskit.org/documentation/install.html) for more info. - Tutorials & References - https://github.com/Qiskit/qiskit-tutorials - https://quantum-computing.ibm.com/docs/iql/first-circuit - https://medium.com/qiskit/how-to-program-a-quantum-computer-982a9329ed02 ## Google Cirq - Start using by installing `python -m pip install cirq`, refer the [docs](https://quantumai.google/cirq/start/install) for more info. - Tutorials & references - https://github.com/quantumlib/cirq - https://quantumai.google/cirq/experiments - https://tanishabassan.medium.com/quantum-programming-with-google-cirq-3209805279bc
# Welcome to Quantum Algorithms Started at https://github.com/TheAlgorithms/Python/issues/1831 * D-Wave: https://www.dwavesys.com and https://github.com/dwavesystems * Google: https://research.google/teams/applied-science/quantum * IBM: https://qiskit.org and https://github.com/Qiskit * Rigetti: https://rigetti.com and https://github.com/rigetti * Zapata: https://www.zapatacomputing.com and https://github.com/zapatacomputing ## IBM Qiskit - Start using by installing `pip install qiskit`, refer the [docs](https://qiskit.org/documentation/install.html) for more info. - Tutorials & References - https://github.com/Qiskit/qiskit-tutorials - https://quantum-computing.ibm.com/docs/iql/first-circuit - https://medium.com/qiskit/how-to-program-a-quantum-computer-982a9329ed02 ## Google Cirq - Start using by installing `python -m pip install cirq`, refer the [docs](https://quantumai.google/cirq/start/install) for more info. - Tutorials & references - https://github.com/quantumlib/cirq - https://quantumai.google/cirq/experiments - https://tanishabassan.medium.com/quantum-programming-with-google-cirq-3209805279bc
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" PyTest's for Digital Image Processing """ import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uint8 from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny as canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs img = imread(r"digital_image_processing/image_data/lena_small.jpg") gray = cvtColor(img, COLOR_BGR2GRAY) # Test: convert_to_negative() def test_convert_to_negative(): negative_img = cn.convert_to_negative(img) # assert negative_img array for at least one True assert negative_img.any() # Test: change_contrast() def test_change_contrast(): with Image.open("digital_image_processing/image_data/lena_small.jpg") as img: # Work around assertion for response assert str(cc.change_contrast(img, 110)).startswith( "<PIL.Image.Image image mode=RGB size=100x100 at" ) # canny.gen_gaussian_kernel() def test_gen_gaussian_kernel(): resp = canny.gen_gaussian_kernel(9, sigma=1.4) # Assert ambiguous array assert resp.all() # canny.py def test_canny(): canny_img = imread("digital_image_processing/image_data/lena_small.jpg", 0) # assert ambiguous array for all == True assert canny_img.all() canny_array = canny.canny(canny_img) # assert canny array for at least one True assert canny_array.any() # filters/gaussian_filter.py def test_gen_gaussian_kernel_filter(): assert gg.gaussian_filter(gray, 5, sigma=0.9).all() def test_convolve_filter(): # laplace diagonals laplace = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]]) res = conv.img_convolve(gray, laplace).astype(uint8) assert res.any() def test_median_filter(): assert med.median_filter(gray, 3).any() def test_sobel_filter(): grad, theta = sob.sobel_filter(gray) assert grad.any() and theta.any() def test_sepia(): sepia = sp.make_sepia(img, 20) assert sepia.all() def test_burkes(file_path: str = "digital_image_processing/image_data/lena_small.jpg"): burkes = bs.Burkes(imread(file_path, 1), 120) burkes.process() assert burkes.output_img.any() def test_nearest_neighbour( file_path: str = "digital_image_processing/image_data/lena_small.jpg", ): nn = rs.NearestNeighbour(imread(file_path, 1), 400, 200) nn.process() assert nn.output.any() def test_local_binary_pattern(): file_path: str = "digital_image_processing/image_data/lena.jpg" # Reading the image and converting it to grayscale. image = imread(file_path, 0) # Test for get_neighbors_pixel function() return not None x_coordinate = 0 y_coordinate = 0 center = image[x_coordinate][y_coordinate] neighbors_pixels = lbp.get_neighbors_pixel( image, x_coordinate, y_coordinate, center ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image lbp_image = np.zeros((image.shape[0], image.shape[1])) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0, image.shape[0]): for j in range(0, image.shape[1]): lbp_image[i][j] = lbp.local_binary_value(image, i, j) assert lbp_image.any()
""" PyTest's for Digital Image Processing """ import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uint8 from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny as canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs img = imread(r"digital_image_processing/image_data/lena_small.jpg") gray = cvtColor(img, COLOR_BGR2GRAY) # Test: convert_to_negative() def test_convert_to_negative(): negative_img = cn.convert_to_negative(img) # assert negative_img array for at least one True assert negative_img.any() # Test: change_contrast() def test_change_contrast(): with Image.open("digital_image_processing/image_data/lena_small.jpg") as img: # Work around assertion for response assert str(cc.change_contrast(img, 110)).startswith( "<PIL.Image.Image image mode=RGB size=100x100 at" ) # canny.gen_gaussian_kernel() def test_gen_gaussian_kernel(): resp = canny.gen_gaussian_kernel(9, sigma=1.4) # Assert ambiguous array assert resp.all() # canny.py def test_canny(): canny_img = imread("digital_image_processing/image_data/lena_small.jpg", 0) # assert ambiguous array for all == True assert canny_img.all() canny_array = canny.canny(canny_img) # assert canny array for at least one True assert canny_array.any() # filters/gaussian_filter.py def test_gen_gaussian_kernel_filter(): assert gg.gaussian_filter(gray, 5, sigma=0.9).all() def test_convolve_filter(): # laplace diagonals laplace = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]]) res = conv.img_convolve(gray, laplace).astype(uint8) assert res.any() def test_median_filter(): assert med.median_filter(gray, 3).any() def test_sobel_filter(): grad, theta = sob.sobel_filter(gray) assert grad.any() and theta.any() def test_sepia(): sepia = sp.make_sepia(img, 20) assert sepia.all() def test_burkes(file_path: str = "digital_image_processing/image_data/lena_small.jpg"): burkes = bs.Burkes(imread(file_path, 1), 120) burkes.process() assert burkes.output_img.any() def test_nearest_neighbour( file_path: str = "digital_image_processing/image_data/lena_small.jpg", ): nn = rs.NearestNeighbour(imread(file_path, 1), 400, 200) nn.process() assert nn.output.any() def test_local_binary_pattern(): file_path: str = "digital_image_processing/image_data/lena.jpg" # Reading the image and converting it to grayscale. image = imread(file_path, 0) # Test for get_neighbors_pixel function() return not None x_coordinate = 0 y_coordinate = 0 center = image[x_coordinate][y_coordinate] neighbors_pixels = lbp.get_neighbors_pixel( image, x_coordinate, y_coordinate, center ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image lbp_image = np.zeros((image.shape[0], image.shape[1])) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0, image.shape[0]): for j in range(0, image.shape[1]): lbp_image[i][j] = lbp.local_binary_value(image, i, j) assert lbp_image.any()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Author: 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): # print("Numpy version: " + np.__version__) 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): # noqa: E741,E743 """ 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): # print("Numpy version: " + np.__version__) 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): # noqa: E741,E743 """ 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
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Shellsort#Pseudocode """ def shell_sort(collection): """Pure implementation of shell sort algorithm in Python :param collection: Some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending >>> shell_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> shell_sort([]) [] >>> shell_sort([-2, -5, -45]) [-45, -5, -2] """ # Marcin Ciura's gap sequence gaps = [701, 301, 132, 57, 23, 10, 4, 1] for gap in gaps: for i in range(gap, len(collection)): insert_value = collection[i] j = i while j >= gap and collection[j - gap] > insert_value: collection[j] = collection[j - gap] j -= gap if j != i: collection[j] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(shell_sort(unsorted))
""" https://en.wikipedia.org/wiki/Shellsort#Pseudocode """ def shell_sort(collection): """Pure implementation of shell sort algorithm in Python :param collection: Some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending >>> shell_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> shell_sort([]) [] >>> shell_sort([-2, -5, -45]) [-45, -5, -2] """ # Marcin Ciura's gap sequence gaps = [701, 301, 132, 57, 23, 10, 4, 1] for gap in gaps: for i in range(gap, len(collection)): insert_value = collection[i] j = i while j >= gap and collection[j - gap] > insert_value: collection[j] = collection[j - gap] j -= gap if j != i: collection[j] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(shell_sort(unsorted))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations import random import string class ShuffledShiftCipher: """ This algorithm uses the Caesar Cipher algorithm but removes the option to use brute force to decrypt the message. The passcode is a random password from the selection buffer of 1. uppercase letters of the English alphabet 2. lowercase letters of the English alphabet 3. digits from 0 to 9 Using unique characters from the passcode, the normal list of characters, that can be allowed in the plaintext, is pivoted and shuffled. Refer to docstring of __make_key_list() to learn more about the shuffling. Then, using the passcode, a number is calculated which is used to encrypt the plaintext message with the normal shift cipher method, only in this case, the reference, to look back at while decrypting, is shuffled. Each cipher object can possess an optional argument as passcode, without which a new passcode is generated for that object automatically. cip1 = ShuffledShiftCipher('d4usr9TWxw9wMD') cip2 = ShuffledShiftCipher() """ def __init__(self, passcode: str | None = None) -> None: """ Initializes a cipher object with a passcode as it's entity Note: No new passcode is generated if user provides a passcode while creating the object """ self.__passcode = passcode or self.__passcode_creator() self.__key_list = self.__make_key_list() self.__shift_key = self.__make_shift_key() def __str__(self) -> str: """ :return: passcode of the cipher object """ return "Passcode is: " + "".join(self.__passcode) def __neg_pos(self, iterlist: list[int]) -> list[int]: """ Mutates the list by changing the sign of each alternate element :param iterlist: takes a list iterable :return: the mutated list """ for i in range(1, len(iterlist), 2): iterlist[i] *= -1 return iterlist def __passcode_creator(self) -> list[str]: """ Creates a random password from the selection buffer of 1. uppercase letters of the English alphabet 2. lowercase letters of the English alphabet 3. digits from 0 to 9 :rtype: list :return: a password of a random length between 10 to 20 """ choices = string.ascii_letters + string.digits password = [random.choice(choices) for _ in range(random.randint(10, 20))] return password def __make_key_list(self) -> list[str]: """ Shuffles the ordered character choices by pivoting at breakpoints Breakpoints are the set of characters in the passcode eg: if, ABCDEFGHIJKLMNOPQRSTUVWXYZ are the possible characters and CAMERA is the passcode then, breakpoints = [A,C,E,M,R] # sorted set of characters from passcode shuffled parts: [A,CB,ED,MLKJIHGF,RQPON,ZYXWVUTS] shuffled __key_list : ACBEDMLKJIHGFRQPONZYXWVUTS Shuffling only 26 letters of the english alphabet can generate 26! combinations for the shuffled list. In the program we consider, a set of 97 characters (including letters, digits, punctuation and whitespaces), thereby creating a possibility of 97! combinations (which is a 152 digit number in itself), thus diminishing the possibility of a brute force approach. Moreover, shift keys even introduce a multiple of 26 for a brute force approach for each of the already 97! combinations. """ # key_list_options contain nearly all printable except few elements from # string.whitespace key_list_options = ( string.ascii_letters + string.digits + string.punctuation + " \t\n" ) keys_l = [] # creates points known as breakpoints to break the key_list_options at those # points and pivot each substring breakpoints = sorted(set(self.__passcode)) temp_list: list[str] = [] # algorithm for creating a new shuffled list, keys_l, out of key_list_options for i in key_list_options: temp_list.extend(i) # checking breakpoints at which to pivot temporary sublist and add it into # keys_l if i in breakpoints or i == key_list_options[-1]: keys_l.extend(temp_list[::-1]) temp_list.clear() # returning a shuffled keys_l to prevent brute force guessing of shift key return keys_l def __make_shift_key(self) -> int: """ sum() of the mutated list of ascii values of all characters where the mutated list is the one returned by __neg_pos() """ num = sum(self.__neg_pos([ord(x) for x in self.__passcode])) return num if num > 0 else len(self.__passcode) def decrypt(self, encoded_message: str) -> str: """ Performs shifting of the encoded_message w.r.t. the shuffled __key_list to create the decoded_message >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44') >>> ssc.decrypt("d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#") 'Hello, this is a modified Caesar cipher' """ decoded_message = "" # decoding shift like Caesar cipher algorithm implementing negative shift or # reverse shift or left shift for i in encoded_message: position = self.__key_list.index(i) decoded_message += self.__key_list[ (position - self.__shift_key) % -len(self.__key_list) ] return decoded_message def encrypt(self, plaintext: str) -> str: """ Performs shifting of the plaintext w.r.t. the shuffled __key_list to create the encoded_message >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44') >>> ssc.encrypt('Hello, this is a modified Caesar cipher') "d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#" """ encoded_message = "" # encoding shift like Caesar cipher algorithm implementing positive shift or # forward shift or right shift for i in plaintext: position = self.__key_list.index(i) encoded_message += self.__key_list[ (position + self.__shift_key) % len(self.__key_list) ] return encoded_message def test_end_to_end(msg: str = "Hello, this is a modified Caesar cipher") -> str: """ >>> test_end_to_end() 'Hello, this is a modified Caesar cipher' """ cip1 = ShuffledShiftCipher() return cip1.decrypt(cip1.encrypt(msg)) if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations import random import string class ShuffledShiftCipher: """ This algorithm uses the Caesar Cipher algorithm but removes the option to use brute force to decrypt the message. The passcode is a random password from the selection buffer of 1. uppercase letters of the English alphabet 2. lowercase letters of the English alphabet 3. digits from 0 to 9 Using unique characters from the passcode, the normal list of characters, that can be allowed in the plaintext, is pivoted and shuffled. Refer to docstring of __make_key_list() to learn more about the shuffling. Then, using the passcode, a number is calculated which is used to encrypt the plaintext message with the normal shift cipher method, only in this case, the reference, to look back at while decrypting, is shuffled. Each cipher object can possess an optional argument as passcode, without which a new passcode is generated for that object automatically. cip1 = ShuffledShiftCipher('d4usr9TWxw9wMD') cip2 = ShuffledShiftCipher() """ def __init__(self, passcode: str | None = None) -> None: """ Initializes a cipher object with a passcode as it's entity Note: No new passcode is generated if user provides a passcode while creating the object """ self.__passcode = passcode or self.__passcode_creator() self.__key_list = self.__make_key_list() self.__shift_key = self.__make_shift_key() def __str__(self) -> str: """ :return: passcode of the cipher object """ return "Passcode is: " + "".join(self.__passcode) def __neg_pos(self, iterlist: list[int]) -> list[int]: """ Mutates the list by changing the sign of each alternate element :param iterlist: takes a list iterable :return: the mutated list """ for i in range(1, len(iterlist), 2): iterlist[i] *= -1 return iterlist def __passcode_creator(self) -> list[str]: """ Creates a random password from the selection buffer of 1. uppercase letters of the English alphabet 2. lowercase letters of the English alphabet 3. digits from 0 to 9 :rtype: list :return: a password of a random length between 10 to 20 """ choices = string.ascii_letters + string.digits password = [random.choice(choices) for _ in range(random.randint(10, 20))] return password def __make_key_list(self) -> list[str]: """ Shuffles the ordered character choices by pivoting at breakpoints Breakpoints are the set of characters in the passcode eg: if, ABCDEFGHIJKLMNOPQRSTUVWXYZ are the possible characters and CAMERA is the passcode then, breakpoints = [A,C,E,M,R] # sorted set of characters from passcode shuffled parts: [A,CB,ED,MLKJIHGF,RQPON,ZYXWVUTS] shuffled __key_list : ACBEDMLKJIHGFRQPONZYXWVUTS Shuffling only 26 letters of the english alphabet can generate 26! combinations for the shuffled list. In the program we consider, a set of 97 characters (including letters, digits, punctuation and whitespaces), thereby creating a possibility of 97! combinations (which is a 152 digit number in itself), thus diminishing the possibility of a brute force approach. Moreover, shift keys even introduce a multiple of 26 for a brute force approach for each of the already 97! combinations. """ # key_list_options contain nearly all printable except few elements from # string.whitespace key_list_options = ( string.ascii_letters + string.digits + string.punctuation + " \t\n" ) keys_l = [] # creates points known as breakpoints to break the key_list_options at those # points and pivot each substring breakpoints = sorted(set(self.__passcode)) temp_list: list[str] = [] # algorithm for creating a new shuffled list, keys_l, out of key_list_options for i in key_list_options: temp_list.extend(i) # checking breakpoints at which to pivot temporary sublist and add it into # keys_l if i in breakpoints or i == key_list_options[-1]: keys_l.extend(temp_list[::-1]) temp_list.clear() # returning a shuffled keys_l to prevent brute force guessing of shift key return keys_l def __make_shift_key(self) -> int: """ sum() of the mutated list of ascii values of all characters where the mutated list is the one returned by __neg_pos() """ num = sum(self.__neg_pos([ord(x) for x in self.__passcode])) return num if num > 0 else len(self.__passcode) def decrypt(self, encoded_message: str) -> str: """ Performs shifting of the encoded_message w.r.t. the shuffled __key_list to create the decoded_message >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44') >>> ssc.decrypt("d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#") 'Hello, this is a modified Caesar cipher' """ decoded_message = "" # decoding shift like Caesar cipher algorithm implementing negative shift or # reverse shift or left shift for i in encoded_message: position = self.__key_list.index(i) decoded_message += self.__key_list[ (position - self.__shift_key) % -len(self.__key_list) ] return decoded_message def encrypt(self, plaintext: str) -> str: """ Performs shifting of the plaintext w.r.t. the shuffled __key_list to create the encoded_message >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44') >>> ssc.encrypt('Hello, this is a modified Caesar cipher') "d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#" """ encoded_message = "" # encoding shift like Caesar cipher algorithm implementing positive shift or # forward shift or right shift for i in plaintext: position = self.__key_list.index(i) encoded_message += self.__key_list[ (position + self.__shift_key) % len(self.__key_list) ] return encoded_message def test_end_to_end(msg: str = "Hello, this is a modified Caesar cipher") -> str: """ >>> test_end_to_end() 'Hello, this is a modified Caesar cipher' """ cip1 = ShuffledShiftCipher() return cip1.decrypt(cip1.encrypt(msg)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 6: https://projecteuler.net/problem=6 Sum square difference The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ def solution(n: int = 100) -> int: """ Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ sum_cubes = (n * (n + 1) // 2) ** 2 sum_squares = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 6: https://projecteuler.net/problem=6 Sum square difference The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ def solution(n: int = 100) -> int: """ Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ sum_cubes = (n * (n + 1) // 2) ** 2 sum_squares = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from json import loads from pathlib import Path import numpy as np from yulewalker import yulewalk from audio_filters.butterworth_filter import make_highpass from audio_filters.iir_filter import IIRFilter data = loads((Path(__file__).resolve().parent / "loudness_curve.json").read_text()) class EqualLoudnessFilter: r""" An equal-loudness filter which compensates for the human ear's non-linear response to sound. This filter corrects this by cascading a yulewalk filter and a butterworth filter. Designed for use with samplerate of 44.1kHz and above. If you're using a lower samplerate, use with caution. Code based on matlab implementation at https://bit.ly/3eqh2HU (url shortened for flake8) Target curve: https://i.imgur.com/3g2VfaM.png Yulewalk response: https://i.imgur.com/J9LnJ4C.png Butterworth and overall response: https://i.imgur.com/3g2VfaM.png Images and original matlab implementation by David Robinson, 2001 """ def __init__(self, samplerate: int = 44100) -> None: self.yulewalk_filter = IIRFilter(10) self.butterworth_filter = make_highpass(150, samplerate) # pad the data to nyquist curve_freqs = np.array(data["frequencies"] + [max(20000.0, samplerate / 2)]) curve_gains = np.array(data["gains"] + [140]) # Convert to angular frequency freqs_normalized = curve_freqs / samplerate * 2 # Invert the curve and normalize to 0dB gains_normalized = np.power(10, (np.min(curve_gains) - curve_gains) / 20) # Scipy's `yulewalk` function is a stub, so we're using the # `yulewalker` library instead. # This function computes the coefficients using a least-squares # fit to the specified curve. ya, yb = yulewalk(10, freqs_normalized, gains_normalized) self.yulewalk_filter.set_coefficients(ya, yb) def process(self, sample: float) -> float: """ Process a single sample through both filters >>> filt = EqualLoudnessFilter() >>> filt.process(0.0) 0.0 """ tmp = self.yulewalk_filter.process(sample) return self.butterworth_filter.process(tmp)
from json import loads from pathlib import Path import numpy as np from yulewalker import yulewalk from audio_filters.butterworth_filter import make_highpass from audio_filters.iir_filter import IIRFilter data = loads((Path(__file__).resolve().parent / "loudness_curve.json").read_text()) class EqualLoudnessFilter: r""" An equal-loudness filter which compensates for the human ear's non-linear response to sound. This filter corrects this by cascading a yulewalk filter and a butterworth filter. Designed for use with samplerate of 44.1kHz and above. If you're using a lower samplerate, use with caution. Code based on matlab implementation at https://bit.ly/3eqh2HU (url shortened for flake8) Target curve: https://i.imgur.com/3g2VfaM.png Yulewalk response: https://i.imgur.com/J9LnJ4C.png Butterworth and overall response: https://i.imgur.com/3g2VfaM.png Images and original matlab implementation by David Robinson, 2001 """ def __init__(self, samplerate: int = 44100) -> None: self.yulewalk_filter = IIRFilter(10) self.butterworth_filter = make_highpass(150, samplerate) # pad the data to nyquist curve_freqs = np.array(data["frequencies"] + [max(20000.0, samplerate / 2)]) curve_gains = np.array(data["gains"] + [140]) # Convert to angular frequency freqs_normalized = curve_freqs / samplerate * 2 # Invert the curve and normalize to 0dB gains_normalized = np.power(10, (np.min(curve_gains) - curve_gains) / 20) # Scipy's `yulewalk` function is a stub, so we're using the # `yulewalker` library instead. # This function computes the coefficients using a least-squares # fit to the specified curve. ya, yb = yulewalk(10, freqs_normalized, gains_normalized) self.yulewalk_filter.set_coefficients(ya, yb) def process(self, sample: float) -> float: """ Process a single sample through both filters >>> filt = EqualLoudnessFilter() >>> filt.process(0.0) 0.0 """ tmp = self.yulewalk_filter.process(sample) return self.butterworth_filter.process(tmp)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a pure Python implementation of the merge sort algorithm For doctests run following command: python -m doctest -v merge_sort.py or python3 -m doctest -v merge_sort.py For manual testing run: python merge_sort.py """ def merge_sort(collection: list) -> list: """Pure implementation of the merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_sort([]) [] >>> merge_sort([-2, -5, -45]) [-45, -5, -2] """ def merge(left: list, right: list) -> list: """merge left and right :param left: left collection :param right: right collection :return: merge result """ def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0) yield from left yield from right return list(_merge()) if len(collection) <= 1: return collection mid = len(collection) // 2 return merge(merge_sort(collection[:mid]), merge_sort(collection[mid:])) if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
""" This is a pure Python implementation of the merge sort algorithm For doctests run following command: python -m doctest -v merge_sort.py or python3 -m doctest -v merge_sort.py For manual testing run: python merge_sort.py """ def merge_sort(collection: list) -> list: """Pure implementation of the merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_sort([]) [] >>> merge_sort([-2, -5, -45]) [-45, -5, -2] """ def merge(left: list, right: list) -> list: """merge left and right :param left: left collection :param right: right collection :return: merge result """ def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0) yield from left yield from right return list(_merge()) if len(collection) <= 1: return collection mid = len(collection) // 2 return merge(merge_sort(collection[:mid]), merge_sort(collection[mid:])) if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A recursive implementation of the insertion sort algorithm """ from __future__ import annotations def rec_insertion_sort(collection: list, n: int): """ Given a collection of numbers and its length, sorts the collections in ascending order :param collection: A mutable collection of comparable elements :param n: The length of collections >>> col = [1, 2, 1] >>> rec_insertion_sort(col, len(col)) >>> print(col) [1, 1, 2] >>> col = [2, 1, 0, -1, -2] >>> rec_insertion_sort(col, len(col)) >>> print(col) [-2, -1, 0, 1, 2] >>> col = [1] >>> rec_insertion_sort(col, len(col)) >>> print(col) [1] """ # Checks if the entire collection has been sorted if len(collection) <= 1 or n <= 1: return insert_next(collection, n - 1) rec_insertion_sort(collection, n - 1) def insert_next(collection: list, index: int): """ Inserts the '(index-1)th' element into place >>> col = [3, 2, 4, 2] >>> insert_next(col, 1) >>> print(col) [2, 3, 4, 2] >>> col = [3, 2, 3] >>> insert_next(col, 2) >>> print(col) [3, 2, 3] >>> col = [] >>> insert_next(col, 1) >>> print(col) [] """ # Checks order between adjacent elements if index >= len(collection) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order collection[index - 1], collection[index] = ( collection[index], collection[index - 1], ) insert_next(collection, index + 1) if __name__ == "__main__": numbers = input("Enter integers separated by spaces: ") number_list: list[int] = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
""" A recursive implementation of the insertion sort algorithm """ from __future__ import annotations def rec_insertion_sort(collection: list, n: int): """ Given a collection of numbers and its length, sorts the collections in ascending order :param collection: A mutable collection of comparable elements :param n: The length of collections >>> col = [1, 2, 1] >>> rec_insertion_sort(col, len(col)) >>> print(col) [1, 1, 2] >>> col = [2, 1, 0, -1, -2] >>> rec_insertion_sort(col, len(col)) >>> print(col) [-2, -1, 0, 1, 2] >>> col = [1] >>> rec_insertion_sort(col, len(col)) >>> print(col) [1] """ # Checks if the entire collection has been sorted if len(collection) <= 1 or n <= 1: return insert_next(collection, n - 1) rec_insertion_sort(collection, n - 1) def insert_next(collection: list, index: int): """ Inserts the '(index-1)th' element into place >>> col = [3, 2, 4, 2] >>> insert_next(col, 1) >>> print(col) [2, 3, 4, 2] >>> col = [3, 2, 3] >>> insert_next(col, 2) >>> print(col) [3, 2, 3] >>> col = [] >>> insert_next(col, 1) >>> print(col) [] """ # Checks order between adjacent elements if index >= len(collection) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order collection[index - 1], collection[index] = ( collection[index], collection[index - 1], ) insert_next(collection, index + 1) if __name__ == "__main__": numbers = input("Enter integers separated by spaces: ") number_list: list[int] = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def snake_to_camel_case(input_str: str, use_pascal: bool = False) -> str: """ Transforms a snake_case given string to camelCase (or PascalCase if indicated) (defaults to not use Pascal) >>> snake_to_camel_case("some_random_string") 'someRandomString' >>> snake_to_camel_case("some_random_string", use_pascal=True) 'SomeRandomString' >>> snake_to_camel_case("some_random_string_with_numbers_123") 'someRandomStringWithNumbers123' >>> snake_to_camel_case("some_random_string_with_numbers_123", use_pascal=True) 'SomeRandomStringWithNumbers123' >>> snake_to_camel_case(123) Traceback (most recent call last): ... ValueError: Expected string as input, found <class 'int'> >>> snake_to_camel_case("some_string", use_pascal="True") Traceback (most recent call last): ... ValueError: Expected boolean as use_pascal parameter, found <class 'str'> """ if not isinstance(input_str, str): raise ValueError(f"Expected string as input, found {type(input_str)}") if not isinstance(use_pascal, bool): raise ValueError( f"Expected boolean as use_pascal parameter, found {type(use_pascal)}" ) words = input_str.split("_") start_index = 0 if use_pascal else 1 words_to_capitalize = words[start_index:] capitalized_words = [word[0].upper() + word[1:] for word in words_to_capitalize] initial_word = "" if use_pascal else words[0] return "".join([initial_word] + capitalized_words) if __name__ == "__main__": from doctest import testmod testmod()
def snake_to_camel_case(input_str: str, use_pascal: bool = False) -> str: """ Transforms a snake_case given string to camelCase (or PascalCase if indicated) (defaults to not use Pascal) >>> snake_to_camel_case("some_random_string") 'someRandomString' >>> snake_to_camel_case("some_random_string", use_pascal=True) 'SomeRandomString' >>> snake_to_camel_case("some_random_string_with_numbers_123") 'someRandomStringWithNumbers123' >>> snake_to_camel_case("some_random_string_with_numbers_123", use_pascal=True) 'SomeRandomStringWithNumbers123' >>> snake_to_camel_case(123) Traceback (most recent call last): ... ValueError: Expected string as input, found <class 'int'> >>> snake_to_camel_case("some_string", use_pascal="True") Traceback (most recent call last): ... ValueError: Expected boolean as use_pascal parameter, found <class 'str'> """ if not isinstance(input_str, str): raise ValueError(f"Expected string as input, found {type(input_str)}") if not isinstance(use_pascal, bool): raise ValueError( f"Expected boolean as use_pascal parameter, found {type(use_pascal)}" ) words = input_str.split("_") start_index = 0 if use_pascal else 1 words_to_capitalize = words[start_index:] capitalized_words = [word[0].upper() + word[1:] for word in words_to_capitalize] initial_word = "" if use_pascal else words[0] return "".join([initial_word] + capitalized_words) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 234: https://projecteuler.net/problem=234 For any integer n, consider the three functions f1,n(x,y,z) = x^(n+1) + y^(n+1) - z^(n+1) f2,n(x,y,z) = (xy + yz + zx)*(x^(n-1) + y^(n-1) - z^(n-1)) f3,n(x,y,z) = xyz*(xn-2 + yn-2 - zn-2) and their combination fn(x,y,z) = f1,n(x,y,z) + f2,n(x,y,z) - f3,n(x,y,z) We call (x,y,z) a golden triple of order k if x, y, and z are all rational numbers of the form a / b with 0 < a < b ≤ k and there is (at least) one integer n, so that fn(x,y,z) = 0. Let s(x,y,z) = x + y + z. Let t = u / v be the sum of all distinct s(x,y,z) for all golden triples (x,y,z) of order 35. All the s(x,y,z) and t must be in reduced form. Find u + v. Solution: By expanding the brackets it is easy to show that fn(x, y, z) = (x + y + z) * (x^n + y^n - z^n). Since x,y,z are positive, the requirement fn(x, y, z) = 0 is fulfilled if and only if x^n + y^n = z^n. By Fermat's Last Theorem, this means that the absolute value of n can not exceed 2, i.e. n is in {-2, -1, 0, 1, 2}. We can eliminate n = 0 since then the equation would reduce to 1 + 1 = 1, for which there are no solutions. So all we have to do is iterate through the possible numerators and denominators of x and y, calculate the corresponding z, and check if the corresponding numerator and denominator are integer and satisfy 0 < z_num < z_den <= 0. We use a set "uniquq_s" to make sure there are no duplicates, and the fractions.Fraction class to make sure we get the right numerator and denominator. Reference: https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem """ from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def is_sq(number: int) -> bool: """ Check if number is a perfect square. >>> is_sq(1) True >>> is_sq(1000001) False >>> is_sq(1000000) True """ sq: int = int(number**0.5) return number == sq * sq def add_three( x_num: int, x_den: int, y_num: int, y_den: int, z_num: int, z_den: int ) -> tuple[int, int]: """ Given the numerators and denominators of three fractions, return the numerator and denominator of their sum in lowest form. >>> add_three(1, 3, 1, 3, 1, 3) (1, 1) >>> add_three(2, 5, 4, 11, 12, 3) (262, 55) """ top: int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den bottom: int = x_den * y_den * z_den hcf: int = gcd(top, bottom) top //= hcf bottom //= hcf return top, bottom def solution(order: int = 35) -> int: """ Find the sum of the numerator and denominator of the sum of all s(x,y,z) for golden triples (x,y,z) of the given order. >>> solution(5) 296 >>> solution(10) 12519 >>> solution(20) 19408891927 """ unique_s: set = set() hcf: int total: Fraction = Fraction(0) fraction_sum: tuple[int, int] for x_num in range(1, order + 1): for x_den in range(x_num + 1, order + 1): for y_num in range(1, order + 1): for y_den in range(y_num + 1, order + 1): # n=1 z_num = x_num * y_den + x_den * y_num z_den = x_den * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) z_den = x_den * x_den * y_den * y_den if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=-1 z_num = x_num * y_num z_den = x_den * y_num + x_num * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = x_num * x_num * y_num * y_num z_den = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) for num, den in unique_s: total += Fraction(num, den) return total.denominator + total.numerator if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 234: https://projecteuler.net/problem=234 For any integer n, consider the three functions f1,n(x,y,z) = x^(n+1) + y^(n+1) - z^(n+1) f2,n(x,y,z) = (xy + yz + zx)*(x^(n-1) + y^(n-1) - z^(n-1)) f3,n(x,y,z) = xyz*(xn-2 + yn-2 - zn-2) and their combination fn(x,y,z) = f1,n(x,y,z) + f2,n(x,y,z) - f3,n(x,y,z) We call (x,y,z) a golden triple of order k if x, y, and z are all rational numbers of the form a / b with 0 < a < b ≤ k and there is (at least) one integer n, so that fn(x,y,z) = 0. Let s(x,y,z) = x + y + z. Let t = u / v be the sum of all distinct s(x,y,z) for all golden triples (x,y,z) of order 35. All the s(x,y,z) and t must be in reduced form. Find u + v. Solution: By expanding the brackets it is easy to show that fn(x, y, z) = (x + y + z) * (x^n + y^n - z^n). Since x,y,z are positive, the requirement fn(x, y, z) = 0 is fulfilled if and only if x^n + y^n = z^n. By Fermat's Last Theorem, this means that the absolute value of n can not exceed 2, i.e. n is in {-2, -1, 0, 1, 2}. We can eliminate n = 0 since then the equation would reduce to 1 + 1 = 1, for which there are no solutions. So all we have to do is iterate through the possible numerators and denominators of x and y, calculate the corresponding z, and check if the corresponding numerator and denominator are integer and satisfy 0 < z_num < z_den <= 0. We use a set "uniquq_s" to make sure there are no duplicates, and the fractions.Fraction class to make sure we get the right numerator and denominator. Reference: https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem """ from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def is_sq(number: int) -> bool: """ Check if number is a perfect square. >>> is_sq(1) True >>> is_sq(1000001) False >>> is_sq(1000000) True """ sq: int = int(number**0.5) return number == sq * sq def add_three( x_num: int, x_den: int, y_num: int, y_den: int, z_num: int, z_den: int ) -> tuple[int, int]: """ Given the numerators and denominators of three fractions, return the numerator and denominator of their sum in lowest form. >>> add_three(1, 3, 1, 3, 1, 3) (1, 1) >>> add_three(2, 5, 4, 11, 12, 3) (262, 55) """ top: int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den bottom: int = x_den * y_den * z_den hcf: int = gcd(top, bottom) top //= hcf bottom //= hcf return top, bottom def solution(order: int = 35) -> int: """ Find the sum of the numerator and denominator of the sum of all s(x,y,z) for golden triples (x,y,z) of the given order. >>> solution(5) 296 >>> solution(10) 12519 >>> solution(20) 19408891927 """ unique_s: set = set() hcf: int total: Fraction = Fraction(0) fraction_sum: tuple[int, int] for x_num in range(1, order + 1): for x_den in range(x_num + 1, order + 1): for y_num in range(1, order + 1): for y_den in range(y_num + 1, order + 1): # n=1 z_num = x_num * y_den + x_den * y_num z_den = x_den * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) z_den = x_den * x_den * y_den * y_den if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=-1 z_num = x_num * y_num z_den = x_den * y_num + x_num * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = x_num * x_num * y_num * y_num z_den = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) for num, den in unique_s: total += Fraction(num, den) return total.denominator + total.numerator if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/python # Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries """ Implementing logistic regression for classification problem Helpful resources: Coursera ML course https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac """ import numpy as np from matplotlib import pyplot as plt from sklearn import datasets # get_ipython().run_line_magic('matplotlib', 'inline') # In[67]: # sigmoid function or logistic function is used as a hypothesis function in # classification problems def sigmoid_function(z): return 1 / (1 + np.exp(-z)) def cost_function(h, y): return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean() def log_likelihood(x, y, weights): scores = np.dot(x, weights) return np.sum(y * scores - np.log(1 + np.exp(scores))) # here alpha is the learning rate, X is the feature matrix,y is the target matrix def logistic_reg(alpha, x, y, max_iterations=70000): theta = np.zeros(x.shape[1]) for iterations in range(max_iterations): z = np.dot(x, theta) h = sigmoid_function(z) gradient = np.dot(x.T, h - y) / y.size theta = theta - alpha * gradient # updating the weights z = np.dot(x, theta) h = sigmoid_function(z) j = cost_function(h, y) if iterations % 100 == 0: print(f"loss: {j} \t") # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": iris = datasets.load_iris() x = iris.data[:, :2] y = (iris.target != 0) * 1 alpha = 0.1 theta = logistic_reg(alpha, x, y, max_iterations=70000) print("theta: ", theta) # printing the theta i.e our weights vector def predict_prob(x): return sigmoid_function( np.dot(x, theta) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color="b", label="0") plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color="r", label="1") (x1_min, x1_max) = (x[:, 0].min(), x[:, 0].max()) (x2_min, x2_max) = (x[:, 1].min(), x[:, 1].max()) (xx1, xx2) = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max)) grid = np.c_[xx1.ravel(), xx2.ravel()] probs = predict_prob(grid).reshape(xx1.shape) plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors="black") plt.legend() plt.show()
#!/usr/bin/python # Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries """ Implementing logistic regression for classification problem Helpful resources: Coursera ML course https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac """ import numpy as np from matplotlib import pyplot as plt from sklearn import datasets # get_ipython().run_line_magic('matplotlib', 'inline') # In[67]: # sigmoid function or logistic function is used as a hypothesis function in # classification problems def sigmoid_function(z): return 1 / (1 + np.exp(-z)) def cost_function(h, y): return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean() def log_likelihood(x, y, weights): scores = np.dot(x, weights) return np.sum(y * scores - np.log(1 + np.exp(scores))) # here alpha is the learning rate, X is the feature matrix,y is the target matrix def logistic_reg(alpha, x, y, max_iterations=70000): theta = np.zeros(x.shape[1]) for iterations in range(max_iterations): z = np.dot(x, theta) h = sigmoid_function(z) gradient = np.dot(x.T, h - y) / y.size theta = theta - alpha * gradient # updating the weights z = np.dot(x, theta) h = sigmoid_function(z) j = cost_function(h, y) if iterations % 100 == 0: print(f"loss: {j} \t") # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": iris = datasets.load_iris() x = iris.data[:, :2] y = (iris.target != 0) * 1 alpha = 0.1 theta = logistic_reg(alpha, x, y, max_iterations=70000) print("theta: ", theta) # printing the theta i.e our weights vector def predict_prob(x): return sigmoid_function( np.dot(x, theta) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color="b", label="0") plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color="r", label="1") (x1_min, x1_max) = (x[:, 0].min(), x[:, 0].max()) (x2_min, x2_max) = (x[:, 1].min(), x[:, 1].max()) (xx1, xx2) = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max)) grid = np.c_[xx1.ravel(), xx2.ravel()] probs = predict_prob(grid).reshape(xx1.shape) plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors="black") plt.legend() plt.show()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""example of simple chaos machine""" # Chaos Machine (K, t, m) K = [0.33, 0.44, 0.55, 0.44, 0.33] t = 3 m = 5 # Buffer Space (with Parameters Space) buffer_space: list[float] = [] params_space: list[float] = [] # Machine Time machine_time = 0 def push(seed): global buffer_space, params_space, machine_time, K, m, t # Choosing Dynamical Systems (All) for key, value in enumerate(buffer_space): # Evolution Parameter e = float(seed / value) # Control Theory: Orbit Change value = (buffer_space[(key + 1) % m] + e) % 1 # Control Theory: Trajectory Change r = (params_space[key] + e) % 1 + 3 # Modification (Transition Function) - Jumps buffer_space[key] = round(float(r * value * (1 - value)), 10) params_space[key] = r # Saving to Parameters Space # Logistic Map assert max(buffer_space) < 1 assert max(params_space) < 4 # Machine Time machine_time += 1 def pull(): global buffer_space, params_space, machine_time, K, m, t # PRNG (Xorshift by George Marsaglia) def xorshift(x, y): x ^= y >> 13 y ^= x << 17 x ^= y >> 5 return x # Choosing Dynamical Systems (Increment) key = machine_time % m # Evolution (Time Length) for _ in range(0, t): # Variables (Position + Parameters) r = params_space[key] value = buffer_space[key] # Modification (Transition Function) - Flow buffer_space[key] = round(float(r * value * (1 - value)), 10) params_space[key] = (machine_time * 0.01 + r * 1.01) % 1 + 3 # Choosing Chaotic Data x = int(buffer_space[(key + 2) % m] * (10**10)) y = int(buffer_space[(key - 2) % m] * (10**10)) # Machine Time machine_time += 1 return xorshift(x, y) % 0xFFFFFFFF def reset(): global buffer_space, params_space, machine_time, K, m, t buffer_space = K params_space = [0] * m machine_time = 0 if __name__ == "__main__": # Initialization reset() # Pushing Data (Input) import random message = random.sample(range(0xFFFFFFFF), 100) for chunk in message: push(chunk) # for controlling inp = "" # Pulling Data (Output) while inp in ("e", "E"): print(f"{format(pull(), '#04x')}") print(buffer_space) print(params_space) inp = input("(e)exit? ").strip()
"""example of simple chaos machine""" # Chaos Machine (K, t, m) K = [0.33, 0.44, 0.55, 0.44, 0.33] t = 3 m = 5 # Buffer Space (with Parameters Space) buffer_space: list[float] = [] params_space: list[float] = [] # Machine Time machine_time = 0 def push(seed): global buffer_space, params_space, machine_time, K, m, t # Choosing Dynamical Systems (All) for key, value in enumerate(buffer_space): # Evolution Parameter e = float(seed / value) # Control Theory: Orbit Change value = (buffer_space[(key + 1) % m] + e) % 1 # Control Theory: Trajectory Change r = (params_space[key] + e) % 1 + 3 # Modification (Transition Function) - Jumps buffer_space[key] = round(float(r * value * (1 - value)), 10) params_space[key] = r # Saving to Parameters Space # Logistic Map assert max(buffer_space) < 1 assert max(params_space) < 4 # Machine Time machine_time += 1 def pull(): global buffer_space, params_space, machine_time, K, m, t # PRNG (Xorshift by George Marsaglia) def xorshift(x, y): x ^= y >> 13 y ^= x << 17 x ^= y >> 5 return x # Choosing Dynamical Systems (Increment) key = machine_time % m # Evolution (Time Length) for _ in range(0, t): # Variables (Position + Parameters) r = params_space[key] value = buffer_space[key] # Modification (Transition Function) - Flow buffer_space[key] = round(float(r * value * (1 - value)), 10) params_space[key] = (machine_time * 0.01 + r * 1.01) % 1 + 3 # Choosing Chaotic Data x = int(buffer_space[(key + 2) % m] * (10**10)) y = int(buffer_space[(key - 2) % m] * (10**10)) # Machine Time machine_time += 1 return xorshift(x, y) % 0xFFFFFFFF def reset(): global buffer_space, params_space, machine_time, K, m, t buffer_space = K params_space = [0] * m machine_time = 0 if __name__ == "__main__": # Initialization reset() # Pushing Data (Input) import random message = random.sample(range(0xFFFFFFFF), 100) for chunk in message: push(chunk) # for controlling inp = "" # Pulling Data (Output) while inp in ("e", "E"): print(f"{format(pull(), '#04x')}") print(buffer_space) print(params_space) inp = input("(e)exit? ").strip()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import tensorflow as tf from random import shuffle from numpy import array def TFKMeansCluster(vectors, noofclusters): """ K-Means Clustering using TensorFlow. 'vectors' should be a n*k 2-D NumPy array, where n is the number of vectors of dimensionality k. 'noofclusters' should be an integer. """ noofclusters = int(noofclusters) assert noofclusters < len(vectors) # Find out the dimensionality dim = len(vectors[0]) # Will help select random centroids from among the available vectors vector_indices = list(range(len(vectors))) shuffle(vector_indices) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. graph = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION sess = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points centroids = [ tf.Variable(vectors[vector_indices[i]]) for i in range(noofclusters) ] ##These nodes will assign the centroid Variables the appropriate ##values centroid_value = tf.placeholder("float64", [dim]) cent_assigns = [] for centroid in centroids: cent_assigns.append(tf.assign(centroid, centroid_value)) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) assignments = [tf.Variable(0) for i in range(len(vectors))] ##These nodes will assign an assignment Variable the appropriate ##value assignment_value = tf.placeholder("int32") cluster_assigns = [] for assignment in assignments: cluster_assigns.append(tf.assign(assignment, assignment_value)) ##Now lets construct the node that will compute the mean # The placeholder for the input mean_input = tf.placeholder("float", [None, dim]) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors mean_op = tf.reduce_mean(mean_input, 0) ##Node for computing Euclidean distances # Placeholders for input v1 = tf.placeholder("float", [dim]) v2 = tf.placeholder("float", [dim]) euclid_dist = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(v1, v2), 2))) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input centroid_distances = tf.placeholder("float", [noofclusters]) cluster_assignment = tf.argmin(centroid_distances, 0) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. init_op = tf.initialize_all_variables() # Initialize all variables sess.run(init_op) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. noofiterations = 100 for iteration_n in range(noofiterations): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(vectors)): vect = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. distances = [ sess.run(euclid_dist, feed_dict={v1: vect, v2: sess.run(centroid)}) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input assignment = sess.run( cluster_assignment, feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n], feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(noofclusters): # Collect all the vectors assigned to this cluster assigned_vects = [ vectors[i] for i in range(len(vectors)) if sess.run(assignments[i]) == cluster_n ] # Compute new centroid location new_location = sess.run( mean_op, feed_dict={mean_input: array(assigned_vects)} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n], feed_dict={centroid_value: new_location} ) # Return centroids and assignments centroids = sess.run(centroids) assignments = sess.run(assignments) return centroids, assignments
import tensorflow as tf from random import shuffle from numpy import array def TFKMeansCluster(vectors, noofclusters): """ K-Means Clustering using TensorFlow. 'vectors' should be a n*k 2-D NumPy array, where n is the number of vectors of dimensionality k. 'noofclusters' should be an integer. """ noofclusters = int(noofclusters) assert noofclusters < len(vectors) # Find out the dimensionality dim = len(vectors[0]) # Will help select random centroids from among the available vectors vector_indices = list(range(len(vectors))) shuffle(vector_indices) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. graph = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION sess = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points centroids = [ tf.Variable(vectors[vector_indices[i]]) for i in range(noofclusters) ] ##These nodes will assign the centroid Variables the appropriate ##values centroid_value = tf.placeholder("float64", [dim]) cent_assigns = [] for centroid in centroids: cent_assigns.append(tf.assign(centroid, centroid_value)) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) assignments = [tf.Variable(0) for i in range(len(vectors))] ##These nodes will assign an assignment Variable the appropriate ##value assignment_value = tf.placeholder("int32") cluster_assigns = [] for assignment in assignments: cluster_assigns.append(tf.assign(assignment, assignment_value)) ##Now lets construct the node that will compute the mean # The placeholder for the input mean_input = tf.placeholder("float", [None, dim]) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors mean_op = tf.reduce_mean(mean_input, 0) ##Node for computing Euclidean distances # Placeholders for input v1 = tf.placeholder("float", [dim]) v2 = tf.placeholder("float", [dim]) euclid_dist = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(v1, v2), 2))) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input centroid_distances = tf.placeholder("float", [noofclusters]) cluster_assignment = tf.argmin(centroid_distances, 0) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. init_op = tf.initialize_all_variables() # Initialize all variables sess.run(init_op) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. noofiterations = 100 for iteration_n in range(noofiterations): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(vectors)): vect = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. distances = [ sess.run(euclid_dist, feed_dict={v1: vect, v2: sess.run(centroid)}) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input assignment = sess.run( cluster_assignment, feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n], feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(noofclusters): # Collect all the vectors assigned to this cluster assigned_vects = [ vectors[i] for i in range(len(vectors)) if sess.run(assignments[i]) == cluster_n ] # Compute new centroid location new_location = sess.run( mean_op, feed_dict={mean_input: array(assigned_vects)} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n], feed_dict={centroid_value: new_location} ) # Return centroids and assignments centroids = sess.run(centroids) assignments = sess.run(assignments) return centroids, assignments
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 43: https://projecteuler.net/problem=43 The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 d4d5d6=635 is divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 Find the sum of all 0 to 9 pandigital numbers with this property. """ from itertools import permutations def is_substring_divisible(num: tuple) -> bool: """ Returns True if the pandigital number passes all the divisibility tests. >>> is_substring_divisible((0, 1, 2, 4, 6, 5, 7, 3, 8, 9)) False >>> is_substring_divisible((5, 1, 2, 4, 6, 0, 7, 8, 3, 9)) False >>> is_substring_divisible((1, 4, 0, 6, 3, 5, 7, 2, 8, 9)) True """ if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False tests = [7, 11, 13, 17] for i, test in enumerate(tests): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def solution(n: int = 10) -> int: """ Returns the sum of all pandigital numbers which pass the divisibility tests. >>> solution(10) 16695334890 """ return sum( int("".join(map(str, num))) for num in permutations(range(n)) if is_substring_divisible(num) ) if __name__ == "__main__": print(f"{solution() = }")
""" Problem 43: https://projecteuler.net/problem=43 The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 d4d5d6=635 is divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 Find the sum of all 0 to 9 pandigital numbers with this property. """ from itertools import permutations def is_substring_divisible(num: tuple) -> bool: """ Returns True if the pandigital number passes all the divisibility tests. >>> is_substring_divisible((0, 1, 2, 4, 6, 5, 7, 3, 8, 9)) False >>> is_substring_divisible((5, 1, 2, 4, 6, 0, 7, 8, 3, 9)) False >>> is_substring_divisible((1, 4, 0, 6, 3, 5, 7, 2, 8, 9)) True """ if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False tests = [7, 11, 13, 17] for i, test in enumerate(tests): if (num[i + 4] * 100 + num[i + 5] * 10 + num[i + 6]) % test != 0: return False return True def solution(n: int = 10) -> int: """ Returns the sum of all pandigital numbers which pass the divisibility tests. >>> solution(10) 16695334890 """ return sum( int("".join(map(str, num))) for num in permutations(range(n)) if is_substring_divisible(num) ) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 6: https://projecteuler.net/problem=6 Sum square difference The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ import math def solution(n: int = 100) -> int: """ Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ sum_of_squares = sum(i * i for i in range(1, n + 1)) square_of_sum = int(math.pow(sum(range(1, n + 1)), 2)) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 6: https://projecteuler.net/problem=6 Sum square difference The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ import math def solution(n: int = 100) -> int: """ Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ sum_of_squares = sum(i * i for i in range(1, n + 1)) square_of_sum = int(math.pow(sum(range(1, n + 1)), 2)) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Truncatable primes Problem 37: https://projecteuler.net/problem=37 The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from __future__ import annotations import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def list_truncated_nums(n: int) -> list[int]: """ Returns a list of all left and right truncated numbers of n >>> list_truncated_nums(927628) [927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9] >>> list_truncated_nums(467) [467, 67, 46, 7, 4] >>> list_truncated_nums(58) [58, 8, 5] """ str_num = str(n) list_nums = [n] for i in range(1, len(str_num)): list_nums.append(int(str_num[i:])) list_nums.append(int(str_num[:-i])) return list_nums def validate(n: int) -> bool: """ To optimize the approach, we will rule out the numbers above 1000, whose first or last three digits are not prime >>> validate(74679) False >>> validate(235693) False >>> validate(3797) True """ if len(str(n)) > 3: if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])): return False return True def compute_truncated_primes(count: int = 11) -> list[int]: """ Returns the list of truncated primes >>> compute_truncated_primes(11) [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397] """ list_truncated_primes: list[int] = [] num = 13 while len(list_truncated_primes) != count: if validate(num): list_nums = list_truncated_nums(num) if all(is_prime(i) for i in list_nums): list_truncated_primes.append(num) num += 2 return list_truncated_primes def solution() -> int: """ Returns the sum of truncated primes """ return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
""" Truncatable primes Problem 37: https://projecteuler.net/problem=37 The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from __future__ import annotations import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def list_truncated_nums(n: int) -> list[int]: """ Returns a list of all left and right truncated numbers of n >>> list_truncated_nums(927628) [927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9] >>> list_truncated_nums(467) [467, 67, 46, 7, 4] >>> list_truncated_nums(58) [58, 8, 5] """ str_num = str(n) list_nums = [n] for i in range(1, len(str_num)): list_nums.append(int(str_num[i:])) list_nums.append(int(str_num[:-i])) return list_nums def validate(n: int) -> bool: """ To optimize the approach, we will rule out the numbers above 1000, whose first or last three digits are not prime >>> validate(74679) False >>> validate(235693) False >>> validate(3797) True """ if len(str(n)) > 3: if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])): return False return True def compute_truncated_primes(count: int = 11) -> list[int]: """ Returns the list of truncated primes >>> compute_truncated_primes(11) [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397] """ list_truncated_primes: list[int] = [] num = 13 while len(list_truncated_primes) != count: if validate(num): list_nums = list_truncated_nums(num) if all(is_prime(i) for i in list_nums): list_truncated_primes.append(num) num += 2 return list_truncated_primes def solution() -> int: """ Returns the sum of truncated primes """ return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Modular Exponential. Modular exponentiation is a type of exponentiation performed over a modulus. For more explanation, please check https://en.wikipedia.org/wiki/Modular_exponentiation """ """Calculate Modular Exponential.""" def modular_exponential(base: int, power: int, mod: int): """ >>> modular_exponential(5, 0, 10) 1 >>> modular_exponential(2, 8, 7) 4 >>> modular_exponential(3, -2, 9) -1 """ if power < 0: return -1 base %= mod result = 1 while power > 0: if power & 1: result = (result * base) % mod power = power >> 1 base = (base * base) % mod return result def main(): """Call Modular Exponential Function.""" print(modular_exponential(3, 200, 13)) if __name__ == "__main__": import doctest doctest.testmod() main()
""" Modular Exponential. Modular exponentiation is a type of exponentiation performed over a modulus. For more explanation, please check https://en.wikipedia.org/wiki/Modular_exponentiation """ """Calculate Modular Exponential.""" def modular_exponential(base: int, power: int, mod: int): """ >>> modular_exponential(5, 0, 10) 1 >>> modular_exponential(2, 8, 7) 4 >>> modular_exponential(3, -2, 9) -1 """ if power < 0: return -1 base %= mod result = 1 while power > 0: if power & 1: result = (result * base) % mod power = power >> 1 base = (base * base) % mod return result def main(): """Call Modular Exponential Function.""" print(modular_exponential(3, 200, 13)) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def find_min(nums: list[int | float]) -> int | float: """ Find Minimum Number in a List :param nums: contains elements :return: min number in list >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_min(nums) == min(nums) True True True True >>> find_min([0, 1, 2, 3, 4, 5, -3, 24, -56]) -56 >>> find_min([]) Traceback (most recent call last): ... ValueError: find_min() arg is an empty sequence """ if len(nums) == 0: raise ValueError("find_min() arg is an empty sequence") min_num = nums[0] for num in nums: if min_num > num: min_num = num return min_num if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
from __future__ import annotations def find_min(nums: list[int | float]) -> int | float: """ Find Minimum Number in a List :param nums: contains elements :return: min number in list >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_min(nums) == min(nums) True True True True >>> find_min([0, 1, 2, 3, 4, 5, -3, 24, -56]) -56 >>> find_min([]) Traceback (most recent call last): ... ValueError: find_min() arg is an empty sequence """ if len(nums) == 0: raise ValueError("find_min() arg is an empty sequence") min_num = nums[0] for num in nums: if min_num > num: min_num = num return min_num if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This script demonstrates the implementation of the Softmax function. Its a function that takes as input a vector of K real numbers, and normalizes it into a probability distribution consisting of K probabilities proportional to the exponentials of the input numbers. After softmax, the elements of the vector always sum up to 1. Script inspired from its corresponding Wikipedia article https://en.wikipedia.org/wiki/Softmax_function """ import numpy as np def softmax(vector): """ Implements the softmax function Parameters: vector (np.array,list,tuple): A numpy array of shape (1,n) consisting of real values or a similar list,tuple Returns: softmax_vec (np.array): The input numpy array after applying softmax. The softmax vector adds up to one. We need to ceil to mitigate for precision >>> np.ceil(np.sum(softmax([1,2,3,4]))) 1.0 >>> vec = np.array([5,5]) >>> softmax(vec) array([0.5, 0.5]) >>> softmax([0]) array([1.]) """ # Calculate e^x for each x in your vector where e is Euler's # number (approximately 2.718) exponent_vector = np.exp(vector) # Add up the all the exponentials sum_of_exponents = np.sum(exponent_vector) # Divide every exponent by the sum of all exponents softmax_vector = exponent_vector / sum_of_exponents return softmax_vector if __name__ == "__main__": print(softmax((0,)))
""" This script demonstrates the implementation of the Softmax function. Its a function that takes as input a vector of K real numbers, and normalizes it into a probability distribution consisting of K probabilities proportional to the exponentials of the input numbers. After softmax, the elements of the vector always sum up to 1. Script inspired from its corresponding Wikipedia article https://en.wikipedia.org/wiki/Softmax_function """ import numpy as np def softmax(vector): """ Implements the softmax function Parameters: vector (np.array,list,tuple): A numpy array of shape (1,n) consisting of real values or a similar list,tuple Returns: softmax_vec (np.array): The input numpy array after applying softmax. The softmax vector adds up to one. We need to ceil to mitigate for precision >>> np.ceil(np.sum(softmax([1,2,3,4]))) 1.0 >>> vec = np.array([5,5]) >>> softmax(vec) array([0.5, 0.5]) >>> softmax([0]) array([1.]) """ # Calculate e^x for each x in your vector where e is Euler's # number (approximately 2.718) exponent_vector = np.exp(vector) # Add up the all the exponentials sum_of_exponents = np.sum(exponent_vector) # Divide every exponent by the sum of all exponents softmax_vector = exponent_vector / sum_of_exponents return softmax_vector if __name__ == "__main__": print(softmax((0,)))
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Horizontal Projectile Motion problem in physics. This algorithm solves a specific problem in which the motion starts from the ground as can be seen below: (v = 0) ** * * * * * * * * * * GROUND GROUND For more info: https://en.wikipedia.org/wiki/Projectile_motion """ # Importing packages from math import radians as angle_to_radians from math import sin # Acceleration Constant on Earth (unit m/s^2) g = 9.80665 def check_args(init_velocity: float, angle: float) -> None: """ Check that the arguments are valid """ # Ensure valid instance if not isinstance(init_velocity, (int, float)): raise TypeError("Invalid velocity. Should be a positive number.") if not isinstance(angle, (int, float)): raise TypeError("Invalid angle. Range is 1-90 degrees.") # Ensure valid angle if angle > 90 or angle < 1: raise ValueError("Invalid angle. Range is 1-90 degrees.") # Ensure valid velocity if init_velocity < 0: raise ValueError("Invalid velocity. Should be a positive number.") def horizontal_distance(init_velocity: float, angle: float) -> float: """ Returns the horizontal distance that the object cover Formula: v_0^2 * sin(2 * alpha) --------------------- g v_0 - initial velocity alpha - angle >>> horizontal_distance(30, 45) 91.77 >>> horizontal_distance(100, 78) 414.76 >>> horizontal_distance(-1, 20) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, -20) Traceback (most recent call last): ... ValueError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(2 * angle) return round(init_velocity**2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: """ Returns the maximum height that the object reach Formula: v_0^2 * sin^2(alpha) -------------------- 2g v_0 - initial velocity alpha - angle >>> max_height(30, 45) 22.94 >>> max_height(100, 78) 487.82 >>> max_height("a", 20) Traceback (most recent call last): ... TypeError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: """ Returns total time of the motion Formula: 2 * v_0 * sin(alpha) -------------------- g v_0 - initial velocity alpha - angle >>> total_time(30, 45) 4.33 >>> total_time(100, 78) 19.95 >>> total_time(-10, 40) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> total_time(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(2 * init_velocity * sin(radians) / g, 2) def test_motion() -> None: """ >>> test_motion() """ v0, angle = 25, 20 assert horizontal_distance(v0, angle) == 40.97 assert max_height(v0, angle) == 3.73 assert total_time(v0, angle) == 1.74 if __name__ == "__main__": from doctest import testmod testmod() # Get input from user init_vel = float(input("Initial Velocity: ").strip()) # Get input from user angle = float(input("angle: ").strip()) # Print results print() print("Results: ") print(f"Horizontal Distance: {str(horizontal_distance(init_vel, angle))} [m]") print(f"Maximum Height: {str(max_height(init_vel, angle))} [m]") print(f"Total Time: {str(total_time(init_vel, angle))} [s]")
""" Horizontal Projectile Motion problem in physics. This algorithm solves a specific problem in which the motion starts from the ground as can be seen below: (v = 0) ** * * * * * * * * * * GROUND GROUND For more info: https://en.wikipedia.org/wiki/Projectile_motion """ # Importing packages from math import radians as angle_to_radians from math import sin # Acceleration Constant on Earth (unit m/s^2) g = 9.80665 def check_args(init_velocity: float, angle: float) -> None: """ Check that the arguments are valid """ # Ensure valid instance if not isinstance(init_velocity, (int, float)): raise TypeError("Invalid velocity. Should be a positive number.") if not isinstance(angle, (int, float)): raise TypeError("Invalid angle. Range is 1-90 degrees.") # Ensure valid angle if angle > 90 or angle < 1: raise ValueError("Invalid angle. Range is 1-90 degrees.") # Ensure valid velocity if init_velocity < 0: raise ValueError("Invalid velocity. Should be a positive number.") def horizontal_distance(init_velocity: float, angle: float) -> float: """ Returns the horizontal distance that the object cover Formula: v_0^2 * sin(2 * alpha) --------------------- g v_0 - initial velocity alpha - angle >>> horizontal_distance(30, 45) 91.77 >>> horizontal_distance(100, 78) 414.76 >>> horizontal_distance(-1, 20) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, -20) Traceback (most recent call last): ... ValueError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(2 * angle) return round(init_velocity**2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: """ Returns the maximum height that the object reach Formula: v_0^2 * sin^2(alpha) -------------------- 2g v_0 - initial velocity alpha - angle >>> max_height(30, 45) 22.94 >>> max_height(100, 78) 487.82 >>> max_height("a", 20) Traceback (most recent call last): ... TypeError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: """ Returns total time of the motion Formula: 2 * v_0 * sin(alpha) -------------------- g v_0 - initial velocity alpha - angle >>> total_time(30, 45) 4.33 >>> total_time(100, 78) 19.95 >>> total_time(-10, 40) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> total_time(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(2 * init_velocity * sin(radians) / g, 2) def test_motion() -> None: """ >>> test_motion() """ v0, angle = 25, 20 assert horizontal_distance(v0, angle) == 40.97 assert max_height(v0, angle) == 3.73 assert total_time(v0, angle) == 1.74 if __name__ == "__main__": from doctest import testmod testmod() # Get input from user init_vel = float(input("Initial Velocity: ").strip()) # Get input from user angle = float(input("angle: ").strip()) # Print results print() print("Results: ") print(f"Horizontal Distance: {str(horizontal_distance(init_vel, angle))} [m]") print(f"Maximum Height: {str(max_height(init_vel, angle))} [m]") print(f"Total Time: {str(total_time(init_vel, angle))} [s]")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Created on Mon Feb 26 14:29:11 2018 @author: Christian Bender @license: MIT-license This module contains some useful classes and functions for dealing with linear algebra in python. Overview: - class Vector - function zero_vector(dimension) - function unit_basis_vector(dimension, pos) - function axpy(scalar, vector1, vector2) - function random_vector(N, a, b) - class Matrix - function square_zero_matrix(N) - function random_matrix(W, H, a, b) """ from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class Vector: """ This class represents a vector of arbitrary size. You need to give the vector components. Overview of the methods: __init__(components: Collection[float] | None): init the vector __len__(): gets the size of the vector (number of components) __str__(): returns a string representation __add__(other: Vector): vector addition __sub__(other: Vector): vector subtraction __mul__(other: float): scalar multiplication __mul__(other: Vector): dot product set(components: Collection[float]): changes the vector components copy(): copies this vector and returns it component(i): gets the i-th component (0-indexed) change_component(pos: int, value: float): changes specified component euclidean_length(): returns the euclidean length of the vector angle(other: Vector, deg: bool): returns the angle between two vectors TODO: compare-operator """ def __init__(self, components: Collection[float] | None = None) -> None: """ input: components or nothing simple constructor for init the vector """ if components is None: components = [] self.__components = list(components) def __len__(self) -> int: """ returns the size of the vector """ return len(self.__components) def __str__(self) -> str: """ returns a string representation of the vector """ return "(" + ",".join(map(str, self.__components)) + ")" def __add__(self, other: Vector) -> Vector: """ input: other vector assumes: other vector has the same size returns a new vector that represents the sum. """ size = len(self) if size == len(other): result = [self.__components[i] + other.component(i) for i in range(size)] return Vector(result) else: raise Exception("must have the same size") def __sub__(self, other: Vector) -> Vector: """ input: other vector assumes: other vector has the same size returns a new vector that represents the difference. """ size = len(self) if size == len(other): result = [self.__components[i] - other.component(i) for i in range(size)] return Vector(result) else: # error case raise Exception("must have the same size") @overload def __mul__(self, other: float) -> Vector: ... @overload def __mul__(self, other: Vector) -> float: ... def __mul__(self, other: float | Vector) -> float | Vector: """ mul implements the scalar multiplication and the dot-product """ if isinstance(other, float) or isinstance(other, int): ans = [c * other for c in self.__components] return Vector(ans) elif isinstance(other, Vector) and len(self) == len(other): size = len(self) prods = [self.__components[i] * other.component(i) for i in range(size)] return sum(prods) else: # error case raise Exception("invalid operand!") def set(self, components: Collection[float]) -> None: """ input: new components changes the components of the vector. replaces the components with newer one. """ if len(components) > 0: self.__components = list(components) else: raise Exception("please give any vector") def copy(self) -> Vector: """ copies this vector and returns it. """ return Vector(self.__components) def component(self, i: int) -> float: """ input: index (0-indexed) output: the i-th component of the vector. """ if type(i) is int and -len(self.__components) <= i < len(self.__components): return self.__components[i] else: raise Exception("index out of range") def change_component(self, pos: int, value: float) -> None: """ input: an index (pos) and a value changes the specified component (pos) with the 'value' """ # precondition assert -len(self.__components) <= pos < len(self.__components) self.__components[pos] = value def euclidean_length(self) -> float: """ returns the euclidean length of the vector >>> Vector([2, 3, 4]).euclidean_length() 5.385164807134504 >>> Vector([1]).euclidean_length() 1.0 >>> Vector([0, -1, -2, -3, 4, 5, 6]).euclidean_length() 9.539392014169456 >>> Vector([]).euclidean_length() Traceback (most recent call last): ... Exception: Vector is empty """ if len(self.__components) == 0: raise Exception("Vector is empty") squares = [c**2 for c in self.__components] return math.sqrt(sum(squares)) def angle(self, other: Vector, deg: bool = False) -> float: """ find angle between two Vector (self, Vector) >>> Vector([3, 4, -1]).angle(Vector([2, -1, 1])) 1.4906464636572374 >>> Vector([3, 4, -1]).angle(Vector([2, -1, 1]), deg = True) 85.40775111366095 >>> Vector([3, 4, -1]).angle(Vector([2, -1])) Traceback (most recent call last): ... Exception: invalid operand! """ num = self * other den = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den)) else: return math.acos(num / den) def zero_vector(dimension: int) -> Vector: """ returns a zero-vector of size 'dimension' """ # precondition assert isinstance(dimension, int) return Vector([0] * dimension) def unit_basis_vector(dimension: int, pos: int) -> Vector: """ returns a unit basis vector with a One at index 'pos' (indexing at 0) """ # precondition assert isinstance(dimension, int) and (isinstance(pos, int)) ans = [0] * dimension ans[pos] = 1 return Vector(ans) def axpy(scalar: float, x: Vector, y: Vector) -> Vector: """ input: a 'scalar' and two vectors 'x' and 'y' output: a vector computes the axpy operation """ # precondition assert ( isinstance(x, Vector) and isinstance(y, Vector) and (isinstance(scalar, int) or isinstance(scalar, float)) ) return x * scalar + y def random_vector(n: int, a: int, b: int) -> Vector: """ input: size (N) of the vector. random range (a,b) output: returns a random vector of size N, with random integer components between 'a' and 'b'. """ random.seed(None) ans = [random.randint(a, b) for _ in range(n)] return Vector(ans) class Matrix: """ class: Matrix This class represents an arbitrary matrix. Overview of the methods: __init__(): __str__(): returns a string representation __add__(other: Matrix): matrix addition __sub__(other: Matrix): matrix subtraction __mul__(other: float): scalar multiplication __mul__(other: Vector): vector multiplication height() : returns height width() : returns width component(x: int, y: int): returns specified component change_component(x: int, y: int, value: float): changes specified component minor(x: int, y: int): returns minor along (x, y) cofactor(x: int, y: int): returns cofactor along (x, y) determinant() : returns determinant """ def __init__(self, matrix: list[list[float]], w: int, h: int) -> None: """ simple constructor for initializing the matrix with components. """ self.__matrix = matrix self.__width = w self.__height = h def __str__(self) -> str: """ returns a string representation of this matrix. """ ans = "" for i in range(self.__height): ans += "|" for j in range(self.__width): if j < self.__width - 1: ans += str(self.__matrix[i][j]) + "," else: ans += str(self.__matrix[i][j]) + "|\n" return ans def __add__(self, other: Matrix) -> Matrix: """ implements matrix addition. """ if self.__width == other.width() and self.__height == other.height(): matrix = [] for i in range(self.__height): row = [ self.__matrix[i][j] + other.component(i, j) for j in range(self.__width) ] matrix.append(row) return Matrix(matrix, self.__width, self.__height) else: raise Exception("matrix must have the same dimension!") def __sub__(self, other: Matrix) -> Matrix: """ implements matrix subtraction. """ if self.__width == other.width() and self.__height == other.height(): matrix = [] for i in range(self.__height): row = [ self.__matrix[i][j] - other.component(i, j) for j in range(self.__width) ] matrix.append(row) return Matrix(matrix, self.__width, self.__height) else: raise Exception("matrices must have the same dimension!") @overload def __mul__(self, other: float) -> Matrix: ... @overload def __mul__(self, other: Vector) -> Vector: ... def __mul__(self, other: float | Vector) -> Vector | Matrix: """ implements the matrix-vector multiplication. implements the matrix-scalar multiplication """ if isinstance(other, Vector): # matrix-vector if len(other) == self.__width: ans = zero_vector(self.__height) for i in range(self.__height): prods = [ self.__matrix[i][j] * other.component(j) for j in range(self.__width) ] ans.change_component(i, sum(prods)) return ans else: raise Exception( "vector must have the same size as the " "number of columns of the matrix!" ) elif isinstance(other, int) or isinstance(other, float): # matrix-scalar matrix = [ [self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height) ] return Matrix(matrix, self.__width, self.__height) def height(self) -> int: """ getter for the height """ return self.__height def width(self) -> int: """ getter for the width """ return self.__width def component(self, x: int, y: int) -> float: """ returns the specified (x,y) component """ if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception("change_component: indices out of bounds") def change_component(self, x: int, y: int, value: float) -> None: """ changes the x-y component of this matrix """ if 0 <= x < self.__height and 0 <= y < self.__width: self.__matrix[x][y] = value else: raise Exception("change_component: indices out of bounds") def minor(self, x: int, y: int) -> float: """ returns the minor along (x, y) """ if self.__height != self.__width: raise Exception("Matrix is not square") minor = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(minor)): minor[i] = minor[i][:y] + minor[i][y + 1 :] return Matrix(minor, self.__width - 1, self.__height - 1).determinant() def cofactor(self, x: int, y: int) -> float: """ returns the cofactor (signed minor) along (x, y) """ if self.__height != self.__width: raise Exception("Matrix is not square") if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(x, y) else: raise Exception("Indices out of bounds") def determinant(self) -> float: """ returns the determinant of an nxn matrix using Laplace expansion """ if self.__height != self.__width: raise Exception("Matrix is not square") if self.__height < 1: raise Exception("Matrix has no element") elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: cofactor_prods = [ self.__matrix[0][y] * self.cofactor(0, y) for y in range(self.__width) ] return sum(cofactor_prods) def square_zero_matrix(n: int) -> Matrix: """ returns a square zero-matrix of dimension NxN """ ans: list[list[float]] = [[0] * n for _ in range(n)] return Matrix(ans, n, n) def random_matrix(width: int, height: int, a: int, b: int) -> Matrix: """ returns a random matrix WxH with integer components between 'a' and 'b' """ random.seed(None) matrix: list[list[float]] = [ [random.randint(a, b) for _ in range(width)] for _ in range(height) ] return Matrix(matrix, width, height)
""" Created on Mon Feb 26 14:29:11 2018 @author: Christian Bender @license: MIT-license This module contains some useful classes and functions for dealing with linear algebra in python. Overview: - class Vector - function zero_vector(dimension) - function unit_basis_vector(dimension, pos) - function axpy(scalar, vector1, vector2) - function random_vector(N, a, b) - class Matrix - function square_zero_matrix(N) - function random_matrix(W, H, a, b) """ from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class Vector: """ This class represents a vector of arbitrary size. You need to give the vector components. Overview of the methods: __init__(components: Collection[float] | None): init the vector __len__(): gets the size of the vector (number of components) __str__(): returns a string representation __add__(other: Vector): vector addition __sub__(other: Vector): vector subtraction __mul__(other: float): scalar multiplication __mul__(other: Vector): dot product set(components: Collection[float]): changes the vector components copy(): copies this vector and returns it component(i): gets the i-th component (0-indexed) change_component(pos: int, value: float): changes specified component euclidean_length(): returns the euclidean length of the vector angle(other: Vector, deg: bool): returns the angle between two vectors TODO: compare-operator """ def __init__(self, components: Collection[float] | None = None) -> None: """ input: components or nothing simple constructor for init the vector """ if components is None: components = [] self.__components = list(components) def __len__(self) -> int: """ returns the size of the vector """ return len(self.__components) def __str__(self) -> str: """ returns a string representation of the vector """ return "(" + ",".join(map(str, self.__components)) + ")" def __add__(self, other: Vector) -> Vector: """ input: other vector assumes: other vector has the same size returns a new vector that represents the sum. """ size = len(self) if size == len(other): result = [self.__components[i] + other.component(i) for i in range(size)] return Vector(result) else: raise Exception("must have the same size") def __sub__(self, other: Vector) -> Vector: """ input: other vector assumes: other vector has the same size returns a new vector that represents the difference. """ size = len(self) if size == len(other): result = [self.__components[i] - other.component(i) for i in range(size)] return Vector(result) else: # error case raise Exception("must have the same size") @overload def __mul__(self, other: float) -> Vector: ... @overload def __mul__(self, other: Vector) -> float: ... def __mul__(self, other: float | Vector) -> float | Vector: """ mul implements the scalar multiplication and the dot-product """ if isinstance(other, float) or isinstance(other, int): ans = [c * other for c in self.__components] return Vector(ans) elif isinstance(other, Vector) and len(self) == len(other): size = len(self) prods = [self.__components[i] * other.component(i) for i in range(size)] return sum(prods) else: # error case raise Exception("invalid operand!") def set(self, components: Collection[float]) -> None: """ input: new components changes the components of the vector. replaces the components with newer one. """ if len(components) > 0: self.__components = list(components) else: raise Exception("please give any vector") def copy(self) -> Vector: """ copies this vector and returns it. """ return Vector(self.__components) def component(self, i: int) -> float: """ input: index (0-indexed) output: the i-th component of the vector. """ if type(i) is int and -len(self.__components) <= i < len(self.__components): return self.__components[i] else: raise Exception("index out of range") def change_component(self, pos: int, value: float) -> None: """ input: an index (pos) and a value changes the specified component (pos) with the 'value' """ # precondition assert -len(self.__components) <= pos < len(self.__components) self.__components[pos] = value def euclidean_length(self) -> float: """ returns the euclidean length of the vector >>> Vector([2, 3, 4]).euclidean_length() 5.385164807134504 >>> Vector([1]).euclidean_length() 1.0 >>> Vector([0, -1, -2, -3, 4, 5, 6]).euclidean_length() 9.539392014169456 >>> Vector([]).euclidean_length() Traceback (most recent call last): ... Exception: Vector is empty """ if len(self.__components) == 0: raise Exception("Vector is empty") squares = [c**2 for c in self.__components] return math.sqrt(sum(squares)) def angle(self, other: Vector, deg: bool = False) -> float: """ find angle between two Vector (self, Vector) >>> Vector([3, 4, -1]).angle(Vector([2, -1, 1])) 1.4906464636572374 >>> Vector([3, 4, -1]).angle(Vector([2, -1, 1]), deg = True) 85.40775111366095 >>> Vector([3, 4, -1]).angle(Vector([2, -1])) Traceback (most recent call last): ... Exception: invalid operand! """ num = self * other den = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den)) else: return math.acos(num / den) def zero_vector(dimension: int) -> Vector: """ returns a zero-vector of size 'dimension' """ # precondition assert isinstance(dimension, int) return Vector([0] * dimension) def unit_basis_vector(dimension: int, pos: int) -> Vector: """ returns a unit basis vector with a One at index 'pos' (indexing at 0) """ # precondition assert isinstance(dimension, int) and (isinstance(pos, int)) ans = [0] * dimension ans[pos] = 1 return Vector(ans) def axpy(scalar: float, x: Vector, y: Vector) -> Vector: """ input: a 'scalar' and two vectors 'x' and 'y' output: a vector computes the axpy operation """ # precondition assert ( isinstance(x, Vector) and isinstance(y, Vector) and (isinstance(scalar, int) or isinstance(scalar, float)) ) return x * scalar + y def random_vector(n: int, a: int, b: int) -> Vector: """ input: size (N) of the vector. random range (a,b) output: returns a random vector of size N, with random integer components between 'a' and 'b'. """ random.seed(None) ans = [random.randint(a, b) for _ in range(n)] return Vector(ans) class Matrix: """ class: Matrix This class represents an arbitrary matrix. Overview of the methods: __init__(): __str__(): returns a string representation __add__(other: Matrix): matrix addition __sub__(other: Matrix): matrix subtraction __mul__(other: float): scalar multiplication __mul__(other: Vector): vector multiplication height() : returns height width() : returns width component(x: int, y: int): returns specified component change_component(x: int, y: int, value: float): changes specified component minor(x: int, y: int): returns minor along (x, y) cofactor(x: int, y: int): returns cofactor along (x, y) determinant() : returns determinant """ def __init__(self, matrix: list[list[float]], w: int, h: int) -> None: """ simple constructor for initializing the matrix with components. """ self.__matrix = matrix self.__width = w self.__height = h def __str__(self) -> str: """ returns a string representation of this matrix. """ ans = "" for i in range(self.__height): ans += "|" for j in range(self.__width): if j < self.__width - 1: ans += str(self.__matrix[i][j]) + "," else: ans += str(self.__matrix[i][j]) + "|\n" return ans def __add__(self, other: Matrix) -> Matrix: """ implements matrix addition. """ if self.__width == other.width() and self.__height == other.height(): matrix = [] for i in range(self.__height): row = [ self.__matrix[i][j] + other.component(i, j) for j in range(self.__width) ] matrix.append(row) return Matrix(matrix, self.__width, self.__height) else: raise Exception("matrix must have the same dimension!") def __sub__(self, other: Matrix) -> Matrix: """ implements matrix subtraction. """ if self.__width == other.width() and self.__height == other.height(): matrix = [] for i in range(self.__height): row = [ self.__matrix[i][j] - other.component(i, j) for j in range(self.__width) ] matrix.append(row) return Matrix(matrix, self.__width, self.__height) else: raise Exception("matrices must have the same dimension!") @overload def __mul__(self, other: float) -> Matrix: ... @overload def __mul__(self, other: Vector) -> Vector: ... def __mul__(self, other: float | Vector) -> Vector | Matrix: """ implements the matrix-vector multiplication. implements the matrix-scalar multiplication """ if isinstance(other, Vector): # matrix-vector if len(other) == self.__width: ans = zero_vector(self.__height) for i in range(self.__height): prods = [ self.__matrix[i][j] * other.component(j) for j in range(self.__width) ] ans.change_component(i, sum(prods)) return ans else: raise Exception( "vector must have the same size as the " "number of columns of the matrix!" ) elif isinstance(other, int) or isinstance(other, float): # matrix-scalar matrix = [ [self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height) ] return Matrix(matrix, self.__width, self.__height) def height(self) -> int: """ getter for the height """ return self.__height def width(self) -> int: """ getter for the width """ return self.__width def component(self, x: int, y: int) -> float: """ returns the specified (x,y) component """ if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception("change_component: indices out of bounds") def change_component(self, x: int, y: int, value: float) -> None: """ changes the x-y component of this matrix """ if 0 <= x < self.__height and 0 <= y < self.__width: self.__matrix[x][y] = value else: raise Exception("change_component: indices out of bounds") def minor(self, x: int, y: int) -> float: """ returns the minor along (x, y) """ if self.__height != self.__width: raise Exception("Matrix is not square") minor = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(minor)): minor[i] = minor[i][:y] + minor[i][y + 1 :] return Matrix(minor, self.__width - 1, self.__height - 1).determinant() def cofactor(self, x: int, y: int) -> float: """ returns the cofactor (signed minor) along (x, y) """ if self.__height != self.__width: raise Exception("Matrix is not square") if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(x, y) else: raise Exception("Indices out of bounds") def determinant(self) -> float: """ returns the determinant of an nxn matrix using Laplace expansion """ if self.__height != self.__width: raise Exception("Matrix is not square") if self.__height < 1: raise Exception("Matrix has no element") elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: cofactor_prods = [ self.__matrix[0][y] * self.cofactor(0, y) for y in range(self.__width) ] return sum(cofactor_prods) def square_zero_matrix(n: int) -> Matrix: """ returns a square zero-matrix of dimension NxN """ ans: list[list[float]] = [[0] * n for _ in range(n)] return Matrix(ans, n, n) def random_matrix(width: int, height: int, a: int, b: int) -> Matrix: """ returns a random matrix WxH with integer components between 'a' and 'b' """ random.seed(None) matrix: list[list[float]] = [ [random.randint(a, b) for _ in range(width)] for _ in range(height) ] return Matrix(matrix, width, height)
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""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 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 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
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" In the game of darts a player throws three darts at a target board which is split into twenty equal sized sections numbered one to twenty.  The score of a dart is determined by the number of the region that the dart lands in. A dart landing outside the red/green outer ring scores zero. The black and cream regions inside this ring represent single scores. However, the red/green outer ring and middle ring score double and treble scores respectively. At the centre of the board are two concentric circles called the bull region, or bulls-eye. The outer bull is worth 25 points and the inner bull is a double, worth 50 points. There are many variations of rules but in the most popular game the players will begin with a score 301 or 501 and the first player to reduce their running total to zero is a winner. However, it is normal to play a "doubles out" system, which means that the player must land a double (including the double bulls-eye at the centre of the board) on their final dart to win; any other dart that would reduce their running total to one or lower means the score for that set of three darts is "bust". When a player is able to finish on their current score it is called a "checkout" and the highest checkout is 170: T20 T20 D25 (two treble 20s and double bull). There are exactly eleven distinct ways to checkout on a score of 6: D3 D1 D2 S2 D2 D2 D1 S4 D1 S1 S1 D2 S1 T1 D1 S1 S3 D1 D1 D1 D1 D1 S2 D1 S2 S2 D1 Note that D1 D2 is considered different to D2 D1 as they finish on different doubles. However, the combination S1 T1 D1 is considered the same as T1 S1 D1. In addition we shall not include misses in considering combinations; for example, D3 is the same as 0 D3 and 0 0 D3. Incredibly there are 42336 distinct ways of checking out in total. How many distinct ways can a player checkout with a score less than 100? Solution: We first construct a list of the possible dart values, separated by type. We then iterate through the doubles, followed by the possible 2 following throws. If the total of these three darts is less than the given limit, we increment the counter. """ from itertools import combinations_with_replacement def solution(limit: int = 100) -> int: """ Count the number of distinct ways a player can checkout with a score less than limit. >>> solution(171) 42336 >>> solution(50) 12577 """ singles: list[int] = list(range(1, 21)) + [25] doubles: list[int] = [2 * x for x in range(1, 21)] + [50] triples: list[int] = [3 * x for x in range(1, 21)] all_values: list[int] = singles + doubles + triples + [0] num_checkouts: int = 0 double: int throw1: int throw2: int checkout_total: int for double in doubles: for throw1, throw2 in combinations_with_replacement(all_values, 2): checkout_total = double + throw1 + throw2 if checkout_total < limit: num_checkouts += 1 return num_checkouts if __name__ == "__main__": print(f"{solution() = }")
""" In the game of darts a player throws three darts at a target board which is split into twenty equal sized sections numbered one to twenty.  The score of a dart is determined by the number of the region that the dart lands in. A dart landing outside the red/green outer ring scores zero. The black and cream regions inside this ring represent single scores. However, the red/green outer ring and middle ring score double and treble scores respectively. At the centre of the board are two concentric circles called the bull region, or bulls-eye. The outer bull is worth 25 points and the inner bull is a double, worth 50 points. There are many variations of rules but in the most popular game the players will begin with a score 301 or 501 and the first player to reduce their running total to zero is a winner. However, it is normal to play a "doubles out" system, which means that the player must land a double (including the double bulls-eye at the centre of the board) on their final dart to win; any other dart that would reduce their running total to one or lower means the score for that set of three darts is "bust". When a player is able to finish on their current score it is called a "checkout" and the highest checkout is 170: T20 T20 D25 (two treble 20s and double bull). There are exactly eleven distinct ways to checkout on a score of 6: D3 D1 D2 S2 D2 D2 D1 S4 D1 S1 S1 D2 S1 T1 D1 S1 S3 D1 D1 D1 D1 D1 S2 D1 S2 S2 D1 Note that D1 D2 is considered different to D2 D1 as they finish on different doubles. However, the combination S1 T1 D1 is considered the same as T1 S1 D1. In addition we shall not include misses in considering combinations; for example, D3 is the same as 0 D3 and 0 0 D3. Incredibly there are 42336 distinct ways of checking out in total. How many distinct ways can a player checkout with a score less than 100? Solution: We first construct a list of the possible dart values, separated by type. We then iterate through the doubles, followed by the possible 2 following throws. If the total of these three darts is less than the given limit, we increment the counter. """ from itertools import combinations_with_replacement def solution(limit: int = 100) -> int: """ Count the number of distinct ways a player can checkout with a score less than limit. >>> solution(171) 42336 >>> solution(50) 12577 """ singles: list[int] = list(range(1, 21)) + [25] doubles: list[int] = [2 * x for x in range(1, 21)] + [50] triples: list[int] = [3 * x for x in range(1, 21)] all_values: list[int] = singles + doubles + triples + [0] num_checkouts: int = 0 double: int throw1: int throw2: int checkout_total: int for double in doubles: for throw1, throw2 in combinations_with_replacement(all_values, 2): checkout_total = double + throw1 + throw2 if checkout_total < limit: num_checkouts += 1 return num_checkouts if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,262
refactor: Move constants outside of variable scope
### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T19:51:55Z"
"2022-10-16T09:33:29Z"
77764116217708933bdc65b29801092fa291398e
c6582b35bf8b8aba622c63096e3ab2f01aa36854
refactor: Move constants outside of variable scope. ### Describe your change: Moves constants outside of variable scope, removing the need for `noqa: N806` * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.3.0 hooks: - id: check-executables-have-shebangs - id: check-yaml - id: end-of-file-fixer types: [python] - id: trailing-whitespace exclude: | (?x)^( data_structures/heap/binomial_heap.py )$ - id: requirements-txt-fixer - repo: https://github.com/psf/black rev: 22.10.0 hooks: - id: black - repo: https://github.com/PyCQA/isort rev: 5.10.1 hooks: - id: isort args: - --profile=black - repo: https://github.com/asottile/pyupgrade rev: v3.0.0 hooks: - id: pyupgrade args: - --py310-plus - repo: https://github.com/PyCQA/flake8 rev: 5.0.4 hooks: - id: flake8 # See .flake8 for args additional_dependencies: - flake8-bugbear - flake8-builtins - pep8-naming - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.982 hooks: - id: mypy args: - --ignore-missing-imports - --install-types # See mirrors-mypy README.md - --non-interactive additional_dependencies: [types-requests] - repo: https://github.com/codespell-project/codespell rev: v2.2.1 hooks: - id: codespell args: - --ignore-words-list=ans,crate,damon,fo,followings,hist,iff,mater,secant,som,sur,tim,zar - --skip="./.*,./strings/dictionary.txt,./strings/words.txt,./project_euler/problem_022/p022_names.txt" exclude: | (?x)^( strings/dictionary.txt | strings/words.txt | project_euler/problem_022/p022_names.txt )$ - repo: local hooks: - id: validate-filenames name: Validate filenames entry: ./scripts/validate_filenames.py language: script pass_filenames: false
repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.3.0 hooks: - id: check-executables-have-shebangs - id: check-yaml - id: end-of-file-fixer types: [python] - id: trailing-whitespace exclude: | (?x)^( data_structures/heap/binomial_heap.py )$ - id: requirements-txt-fixer - repo: https://github.com/psf/black rev: 22.10.0 hooks: - id: black - repo: https://github.com/PyCQA/isort rev: 5.10.1 hooks: - id: isort args: - --profile=black - repo: https://github.com/asottile/pyupgrade rev: v3.0.0 hooks: - id: pyupgrade args: - --py310-plus - repo: https://github.com/PyCQA/flake8 rev: 5.0.4 hooks: - id: flake8 # See .flake8 for args additional_dependencies: - flake8-bugbear - flake8-builtins - flake8-comprehensions - pep8-naming - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.982 hooks: - id: mypy args: - --ignore-missing-imports - --install-types # See mirrors-mypy README.md - --non-interactive additional_dependencies: [types-requests] - repo: https://github.com/codespell-project/codespell rev: v2.2.1 hooks: - id: codespell args: - --ignore-words-list=ans,crate,damon,fo,followings,hist,iff,mater,secant,som,sur,tim,zar - --skip="./.*,./strings/dictionary.txt,./strings/words.txt,./project_euler/problem_022/p022_names.txt" exclude: | (?x)^( strings/dictionary.txt | strings/words.txt | project_euler/problem_022/p022_names.txt )$ - repo: local hooks: - id: validate-filenames name: Validate filenames entry: ./scripts/validate_filenames.py language: script pass_filenames: false
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import random class Onepad: @staticmethod def encrypt(text: str) -> tuple[list[int], list[int]]: """Function to encrypt text using pseudo-random numbers""" plain = [ord(i) for i in text] key = [] cipher = [] for i in plain: k = random.randint(1, 300) c = (i + k) * k cipher.append(c) key.append(k) return cipher, key @staticmethod def decrypt(cipher: list[int], key: list[int]) -> str: """Function to decrypt text using pseudo-random numbers.""" plain = [] for i in range(len(key)): p = int((cipher[i] - (key[i]) ** 2) / key[i]) plain.append(chr(p)) return "".join([i for i in plain]) if __name__ == "__main__": c, k = Onepad().encrypt("Hello") print(c, k) print(Onepad().decrypt(c, k))
import random class Onepad: @staticmethod def encrypt(text: str) -> tuple[list[int], list[int]]: """Function to encrypt text using pseudo-random numbers""" plain = [ord(i) for i in text] key = [] cipher = [] for i in plain: k = random.randint(1, 300) c = (i + k) * k cipher.append(c) key.append(k) return cipher, key @staticmethod def decrypt(cipher: list[int], key: list[int]) -> str: """Function to decrypt text using pseudo-random numbers.""" plain = [] for i in range(len(key)): p = int((cipher[i] - (key[i]) ** 2) / key[i]) plain.append(chr(p)) return "".join(plain) if __name__ == "__main__": c, k = Onepad().encrypt("Hello") print(c, k) print(Onepad().decrypt(c, k))
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Rail_fence_cipher """ def encrypt(input_string: str, key: int) -> str: """ Shuffles the character of a string by placing each of them in a grid (the height is dependent on the key) in a zigzag formation and reading it left to right. >>> encrypt("Hello World", 4) 'HWe olordll' >>> encrypt("This is a message", 0) Traceback (most recent call last): ... ValueError: Height of grid can't be 0 or negative >>> encrypt(b"This is a byte string", 5) Traceback (most recent call last): ... TypeError: sequence item 0: expected str instance, int found """ temp_grid: list[list[str]] = [[] for _ in range(key)] lowest = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative") if key == 1 or len(input_string) <= key: return input_string for position, character in enumerate(input_string): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern temp_grid[num].append(character) grid = ["".join(row) for row in temp_grid] output_string = "".join(grid) return output_string def decrypt(input_string: str, key: int) -> str: """ Generates a template based on the key and fills it in with the characters of the input string and then reading it in a zigzag formation. >>> decrypt("HWe olordll", 4) 'Hello World' >>> decrypt("This is a message", -10) Traceback (most recent call last): ... ValueError: Height of grid can't be 0 or negative >>> decrypt("My key is very big", 100) 'My key is very big' """ grid = [] lowest = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative") if key == 1: return input_string temp_grid: list[list[str]] = [[] for _ in range(key)] # generates template for position in range(len(input_string)): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern temp_grid[num].append("*") counter = 0 for row in temp_grid: # fills in the characters splice = input_string[counter : counter + len(row)] grid.append([character for character in splice]) counter += len(row) output_string = "" # reads as zigzag for position in range(len(input_string)): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0) return output_string def bruteforce(input_string: str) -> dict[int, str]: """Uses decrypt function by guessing every key >>> bruteforce("HWe olordll")[4] 'Hello World' """ results = {} for key_guess in range(1, len(input_string)): # tries every key results[key_guess] = decrypt(input_string, key_guess) return results if __name__ == "__main__": import doctest doctest.testmod()
""" https://en.wikipedia.org/wiki/Rail_fence_cipher """ def encrypt(input_string: str, key: int) -> str: """ Shuffles the character of a string by placing each of them in a grid (the height is dependent on the key) in a zigzag formation and reading it left to right. >>> encrypt("Hello World", 4) 'HWe olordll' >>> encrypt("This is a message", 0) Traceback (most recent call last): ... ValueError: Height of grid can't be 0 or negative >>> encrypt(b"This is a byte string", 5) Traceback (most recent call last): ... TypeError: sequence item 0: expected str instance, int found """ temp_grid: list[list[str]] = [[] for _ in range(key)] lowest = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative") if key == 1 or len(input_string) <= key: return input_string for position, character in enumerate(input_string): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern temp_grid[num].append(character) grid = ["".join(row) for row in temp_grid] output_string = "".join(grid) return output_string def decrypt(input_string: str, key: int) -> str: """ Generates a template based on the key and fills it in with the characters of the input string and then reading it in a zigzag formation. >>> decrypt("HWe olordll", 4) 'Hello World' >>> decrypt("This is a message", -10) Traceback (most recent call last): ... ValueError: Height of grid can't be 0 or negative >>> decrypt("My key is very big", 100) 'My key is very big' """ grid = [] lowest = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative") if key == 1: return input_string temp_grid: list[list[str]] = [[] for _ in range(key)] # generates template for position in range(len(input_string)): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern temp_grid[num].append("*") counter = 0 for row in temp_grid: # fills in the characters splice = input_string[counter : counter + len(row)] grid.append(list(splice)) counter += len(row) output_string = "" # reads as zigzag for position in range(len(input_string)): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0) return output_string def bruteforce(input_string: str) -> dict[int, str]: """Uses decrypt function by guessing every key >>> bruteforce("HWe olordll")[4] 'Hello World' """ results = {} for key_guess in range(1, len(input_string)): # tries every key results[key_guess] = decrypt(input_string, key_guess) return results if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 from .number_theory.prime_numbers import next_prime class HashTable: """ Basic Hash Table example with open addressing and linear probing """ def __init__( self, size_table: int, charge_factor: int | None = None, lim_charge: float | None = None, ) -> None: self.size_table = size_table self.values = [None] * self.size_table self.lim_charge = 0.75 if lim_charge is None else lim_charge self.charge_factor = 1 if charge_factor is None else charge_factor self.__aux_list: list = [] self._keys: dict = {} def keys(self): return self._keys def balanced_factor(self): return sum(1 for slot in self.values if slot is not None) / ( self.size_table * self.charge_factor ) def hash_function(self, key): return key % self.size_table def _step_by_step(self, step_ord): print(f"step {step_ord}") print([i for i in range(len(self.values))]) print(self.values) def bulk_insert(self, values): i = 1 self.__aux_list = values for value in values: self.insert_data(value) self._step_by_step(i) i += 1 def _set_value(self, key, data): self.values[key] = data self._keys[key] = data def _collision_resolution(self, key, data=None): new_key = self.hash_function(key + 1) while self.values[new_key] is not None and self.values[new_key] != key: if self.values.count(None) > 0: new_key = self.hash_function(new_key + 1) else: new_key = None break return new_key def rehashing(self): survivor_values = [value for value in self.values if value is not None] self.size_table = next_prime(self.size_table, factor=2) self._keys.clear() self.values = [None] * self.size_table # hell's pointers D: don't DRY ;/ for value in survivor_values: self.insert_data(value) def insert_data(self, data): key = self.hash_function(data) if self.values[key] is None: self._set_value(key, data) elif self.values[key] == data: pass else: collision_resolution = self._collision_resolution(key, data) if collision_resolution is not None: self._set_value(collision_resolution, data) else: self.rehashing() self.insert_data(data)
#!/usr/bin/env python3 from .number_theory.prime_numbers import next_prime class HashTable: """ Basic Hash Table example with open addressing and linear probing """ def __init__( self, size_table: int, charge_factor: int | None = None, lim_charge: float | None = None, ) -> None: self.size_table = size_table self.values = [None] * self.size_table self.lim_charge = 0.75 if lim_charge is None else lim_charge self.charge_factor = 1 if charge_factor is None else charge_factor self.__aux_list: list = [] self._keys: dict = {} def keys(self): return self._keys def balanced_factor(self): return sum(1 for slot in self.values if slot is not None) / ( self.size_table * self.charge_factor ) def hash_function(self, key): return key % self.size_table def _step_by_step(self, step_ord): print(f"step {step_ord}") print(list(range(len(self.values)))) print(self.values) def bulk_insert(self, values): i = 1 self.__aux_list = values for value in values: self.insert_data(value) self._step_by_step(i) i += 1 def _set_value(self, key, data): self.values[key] = data self._keys[key] = data def _collision_resolution(self, key, data=None): new_key = self.hash_function(key + 1) while self.values[new_key] is not None and self.values[new_key] != key: if self.values.count(None) > 0: new_key = self.hash_function(new_key + 1) else: new_key = None break return new_key def rehashing(self): survivor_values = [value for value in self.values if value is not None] self.size_table = next_prime(self.size_table, factor=2) self._keys.clear() self.values = [None] * self.size_table # hell's pointers D: don't DRY ;/ for value in survivor_values: self.insert_data(value) def insert_data(self, data): key = self.hash_function(data) if self.values[key] is None: self._set_value(key, data) elif self.values[key] == data: pass else: collision_resolution = self._collision_resolution(key, data) if collision_resolution is not None: self._set_value(collision_resolution, data) else: self.rehashing() self.insert_data(data)
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Algorithm that merges two sorted linked lists into one sorted linked list. """ from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1) test_data_even = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class Node: data: int next: Node | None class SortedLinkedList: def __init__(self, ints: Iterable[int]) -> None: self.head: Node | None = None for i in reversed(sorted(ints)): self.head = Node(i, self.head) def __iter__(self) -> Iterator[int]: """ >>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd)) True >>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even)) True """ node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ >>> for i in range(3): ... len(SortedLinkedList(range(i))) == i True True True >>> len(SortedLinkedList(test_data_odd)) 8 """ return len(tuple(iter(self))) def __str__(self) -> str: """ >>> str(SortedLinkedList([])) '' >>> str(SortedLinkedList(test_data_odd)) '-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9' >>> str(SortedLinkedList(test_data_even)) '-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10' """ return " -> ".join([str(node) for node in self]) def merge_lists( sll_one: SortedLinkedList, sll_two: SortedLinkedList ) -> SortedLinkedList: """ >>> SSL = SortedLinkedList >>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even)) >>> len(merged) 16 >>> str(merged) '-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10' >>> list(merged) == list(sorted(test_data_odd + test_data_even)) True """ return SortedLinkedList(list(sll_one) + list(sll_two)) if __name__ == "__main__": import doctest doctest.testmod() SSL = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
""" Algorithm that merges two sorted linked lists into one sorted linked list. """ from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1) test_data_even = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class Node: data: int next: Node | None class SortedLinkedList: def __init__(self, ints: Iterable[int]) -> None: self.head: Node | None = None for i in sorted(ints, reverse=True): self.head = Node(i, self.head) def __iter__(self) -> Iterator[int]: """ >>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd)) True >>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even)) True """ node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ >>> for i in range(3): ... len(SortedLinkedList(range(i))) == i True True True >>> len(SortedLinkedList(test_data_odd)) 8 """ return len(tuple(iter(self))) def __str__(self) -> str: """ >>> str(SortedLinkedList([])) '' >>> str(SortedLinkedList(test_data_odd)) '-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9' >>> str(SortedLinkedList(test_data_even)) '-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10' """ return " -> ".join([str(node) for node in self]) def merge_lists( sll_one: SortedLinkedList, sll_two: SortedLinkedList ) -> SortedLinkedList: """ >>> SSL = SortedLinkedList >>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even)) >>> len(merged) 16 >>> str(merged) '-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10' >>> list(merged) == list(sorted(test_data_odd + test_data_even)) True """ return SortedLinkedList(list(sll_one) + list(sll_two)) if __name__ == "__main__": import doctest doctest.testmod() SSL = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from bisect import bisect from itertools import accumulate def frac_knapsack(vl, wt, w, n): """ >>> frac_knapsack([60, 100, 120], [10, 20, 30], 50, 3) 240.0 """ r = list(sorted(zip(vl, wt), key=lambda x: x[0] / x[1], reverse=True)) vl, wt = [i[0] for i in r], [i[1] for i in r] acc = list(accumulate(wt)) k = bisect(acc, w) return ( 0 if k == 0 else sum(vl[:k]) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k]) ) if __name__ == "__main__": import doctest doctest.testmod()
from bisect import bisect from itertools import accumulate def frac_knapsack(vl, wt, w, n): """ >>> frac_knapsack([60, 100, 120], [10, 20, 30], 50, 3) 240.0 """ r = sorted(zip(vl, wt), key=lambda x: x[0] / x[1], reverse=True) vl, wt = [i[0] for i in r], [i[1] for i in r] acc = list(accumulate(wt)) k = bisect(acc, w) return ( 0 if k == 0 else sum(vl[:k]) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k]) ) if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def print_distance(distance: list[float], src): print(f"Vertex\tShortest Distance from vertex {src}") for i, d in enumerate(distance): print(f"{i}\t\t{d}") def check_negative_cycle( graph: list[dict[str, int]], distance: list[float], edge_count: int ): for j in range(edge_count): u, v, w = (graph[j][k] for k in ["src", "dst", "weight"]) if distance[u] != float("inf") and distance[u] + w < distance[v]: return True return False def bellman_ford( graph: list[dict[str, int]], vertex_count: int, edge_count: int, src: int ) -> list[float]: """ Returns shortest paths from a vertex src to all other vertices. >>> edges = [(2, 1, -10), (3, 2, 3), (0, 3, 5), (0, 1, 4)] >>> g = [{"src": s, "dst": d, "weight": w} for s, d, w in edges] >>> bellman_ford(g, 4, 4, 0) [0.0, -2.0, 8.0, 5.0] >>> g = [{"src": s, "dst": d, "weight": w} for s, d, w in edges + [(1, 3, 5)]] >>> bellman_ford(g, 4, 5, 0) Traceback (most recent call last): ... Exception: Negative cycle found """ distance = [float("inf")] * vertex_count distance[src] = 0.0 for _ in range(vertex_count - 1): for j in range(edge_count): u, v, w = (graph[j][k] for k in ["src", "dst", "weight"]) if distance[u] != float("inf") and distance[u] + w < distance[v]: distance[v] = distance[u] + w negative_cycle_exists = check_negative_cycle(graph, distance, edge_count) if negative_cycle_exists: raise Exception("Negative cycle found") return distance if __name__ == "__main__": import doctest doctest.testmod() V = int(input("Enter number of vertices: ").strip()) E = int(input("Enter number of edges: ").strip()) graph: list[dict[str, int]] = [dict() for j in range(E)] for i in range(E): print("Edge ", i + 1) src, dest, weight = ( int(x) for x in input("Enter source, destination, weight: ").strip().split(" ") ) graph[i] = {"src": src, "dst": dest, "weight": weight} source = int(input("\nEnter shortest path source:").strip()) shortest_distance = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
from __future__ import annotations def print_distance(distance: list[float], src): print(f"Vertex\tShortest Distance from vertex {src}") for i, d in enumerate(distance): print(f"{i}\t\t{d}") def check_negative_cycle( graph: list[dict[str, int]], distance: list[float], edge_count: int ): for j in range(edge_count): u, v, w = (graph[j][k] for k in ["src", "dst", "weight"]) if distance[u] != float("inf") and distance[u] + w < distance[v]: return True return False def bellman_ford( graph: list[dict[str, int]], vertex_count: int, edge_count: int, src: int ) -> list[float]: """ Returns shortest paths from a vertex src to all other vertices. >>> edges = [(2, 1, -10), (3, 2, 3), (0, 3, 5), (0, 1, 4)] >>> g = [{"src": s, "dst": d, "weight": w} for s, d, w in edges] >>> bellman_ford(g, 4, 4, 0) [0.0, -2.0, 8.0, 5.0] >>> g = [{"src": s, "dst": d, "weight": w} for s, d, w in edges + [(1, 3, 5)]] >>> bellman_ford(g, 4, 5, 0) Traceback (most recent call last): ... Exception: Negative cycle found """ distance = [float("inf")] * vertex_count distance[src] = 0.0 for _ in range(vertex_count - 1): for j in range(edge_count): u, v, w = (graph[j][k] for k in ["src", "dst", "weight"]) if distance[u] != float("inf") and distance[u] + w < distance[v]: distance[v] = distance[u] + w negative_cycle_exists = check_negative_cycle(graph, distance, edge_count) if negative_cycle_exists: raise Exception("Negative cycle found") return distance if __name__ == "__main__": import doctest doctest.testmod() V = int(input("Enter number of vertices: ").strip()) E = int(input("Enter number of edges: ").strip()) graph: list[dict[str, int]] = [{} for _ in range(E)] for i in range(E): print("Edge ", i + 1) src, dest, weight = ( int(x) for x in input("Enter source, destination, weight: ").strip().split(" ") ) graph[i] = {"src": src, "dst": dest, "weight": weight} source = int(input("\nEnter shortest path source:").strip()) shortest_distance = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" FP-GraphMiner - A Fast Frequent Pattern Mining Algorithm for Network Graphs A novel Frequent Pattern Graph Mining algorithm, FP-GraphMiner, that compactly represents a set of network graphs as a Frequent Pattern Graph (or FP-Graph). This graph can be used to efficiently mine frequent subgraphs including maximal frequent subgraphs and maximum common subgraphs. URL: https://www.researchgate.net/publication/235255851 """ # fmt: off edge_array = [ ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'bh-e12', 'cd-e2', 'ce-e4', 'de-e1', 'df-e8', 'dg-e5', 'dh-e10', 'ef-e3', 'eg-e2', 'fg-e6', 'gh-e6', 'hi-e3'], ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'cd-e2', 'de-e1', 'df-e8', 'ef-e3', 'eg-e2', 'fg-e6'], ['ab-e1', 'ac-e3', 'bc-e4', 'bd-e2', 'de-e1', 'df-e8', 'dg-e5', 'ef-e3', 'eg-e2', 'eh-e12', 'fg-e6', 'fh-e10', 'gh-e6'], ['ab-e1', 'ac-e3', 'bc-e4', 'bd-e2', 'bh-e12', 'cd-e2', 'df-e8', 'dh-e10'], ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'cd-e2', 'ce-e4', 'de-e1', 'df-e8', 'dg-e5', 'ef-e3', 'eg-e2', 'fg-e6'] ] # fmt: on def get_distinct_edge(edge_array): """ Return Distinct edges from edge array of multiple graphs >>> sorted(get_distinct_edge(edge_array)) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] """ distinct_edge = set() for row in edge_array: for item in row: distinct_edge.add(item[0]) return list(distinct_edge) def get_bitcode(edge_array, distinct_edge): """ Return bitcode of distinct_edge """ bitcode = ["0"] * len(edge_array) for i, row in enumerate(edge_array): for item in row: if distinct_edge in item[0]: bitcode[i] = "1" break return "".join(bitcode) def get_frequency_table(edge_array): """ Returns Frequency Table """ distinct_edge = get_distinct_edge(edge_array) frequency_table = {} for item in distinct_edge: bit = get_bitcode(edge_array, item) # print('bit',bit) # bt=''.join(bit) s = bit.count("1") frequency_table[item] = [s, bit] # Store [Distinct edge, WT(Bitcode), Bitcode] in descending order sorted_frequency_table = [ [k, v[0], v[1]] for k, v in sorted(frequency_table.items(), key=lambda v: v[1][0], reverse=True) ] return sorted_frequency_table def get_nodes(frequency_table): """ Returns nodes format nodes={bitcode:edges that represent the bitcode} >>> get_nodes([['ab', 5, '11111'], ['ac', 5, '11111'], ['df', 5, '11111'], ... ['bd', 5, '11111'], ['bc', 5, '11111']]) {'11111': ['ab', 'ac', 'df', 'bd', 'bc']} """ nodes = {} for _, item in enumerate(frequency_table): nodes.setdefault(item[2], []).append(item[0]) return nodes def get_cluster(nodes): """ Returns cluster format cluster:{WT(bitcode):nodes with same WT} """ cluster = {} for key, value in nodes.items(): cluster.setdefault(key.count("1"), {})[key] = value return cluster def get_support(cluster): """ Returns support >>> get_support({5: {'11111': ['ab', 'ac', 'df', 'bd', 'bc']}, ... 4: {'11101': ['ef', 'eg', 'de', 'fg'], '11011': ['cd']}, ... 3: {'11001': ['ad'], '10101': ['dg']}, ... 2: {'10010': ['dh', 'bh'], '11000': ['be'], '10100': ['gh'], ... '10001': ['ce']}, ... 1: {'00100': ['fh', 'eh'], '10000': ['hi']}}) [100.0, 80.0, 60.0, 40.0, 20.0] """ return [i * 100 / len(cluster) for i in cluster] def print_all() -> None: print("\nNodes\n") for key, value in nodes.items(): print(key, value) print("\nSupport\n") print(support) print("\n Cluster \n") for key, value in sorted(cluster.items(), reverse=True): print(key, value) print("\n Graph\n") for key, value in graph.items(): print(key, value) print("\n Edge List of Frequent subgraphs \n") for edge_list in freq_subgraph_edge_list: print(edge_list) def create_edge(nodes, graph, cluster, c1): """ create edge between the nodes """ for i in cluster[c1].keys(): count = 0 c2 = c1 + 1 while c2 < max(cluster.keys()): for j in cluster[c2].keys(): """ creates edge only if the condition satisfies """ if int(i, 2) & int(j, 2) == int(i, 2): if tuple(nodes[i]) in graph: graph[tuple(nodes[i])].append(nodes[j]) else: graph[tuple(nodes[i])] = [nodes[j]] count += 1 if count == 0: c2 = c2 + 1 else: break def construct_graph(cluster, nodes): x = cluster[max(cluster.keys())] cluster[max(cluster.keys()) + 1] = "Header" graph = {} for i in x: if tuple(["Header"]) in graph: graph[tuple(["Header"])].append(x[i]) else: graph[tuple(["Header"])] = [x[i]] for i in x: graph[tuple(x[i])] = [["Header"]] i = 1 while i < max(cluster) - 1: create_edge(nodes, graph, cluster, i) i = i + 1 return graph def my_dfs(graph, start, end, path=None): """ find different DFS walk from given node to Header node """ path = (path or []) + [start] if start == end: paths.append(path) for node in graph[start]: if tuple(node) not in path: my_dfs(graph, tuple(node), end, path) def find_freq_subgraph_given_support(s, cluster, graph): """ find edges of multiple frequent subgraphs """ k = int(s / 100 * (len(cluster) - 1)) for i in cluster[k].keys(): my_dfs(graph, tuple(cluster[k][i]), tuple(["Header"])) def freq_subgraphs_edge_list(paths): """ returns Edge list for frequent subgraphs """ freq_sub_el = [] for edges in paths: el = [] for j in range(len(edges) - 1): temp = list(edges[j]) for e in temp: edge = (e[0], e[1]) el.append(edge) freq_sub_el.append(el) return freq_sub_el def preprocess(edge_array): """ Preprocess the edge array >>> preprocess([['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'bh-e12', ... 'cd-e2', 'ce-e4', 'de-e1', 'df-e8', 'dg-e5', 'dh-e10', 'ef-e3', ... 'eg-e2', 'fg-e6', 'gh-e6', 'hi-e3']]) """ for i in range(len(edge_array)): for j in range(len(edge_array[i])): t = edge_array[i][j].split("-") edge_array[i][j] = t if __name__ == "__main__": preprocess(edge_array) frequency_table = get_frequency_table(edge_array) nodes = get_nodes(frequency_table) cluster = get_cluster(nodes) support = get_support(cluster) graph = construct_graph(cluster, nodes) find_freq_subgraph_given_support(60, cluster, graph) paths: list = [] freq_subgraph_edge_list = freq_subgraphs_edge_list(paths) print_all()
""" FP-GraphMiner - A Fast Frequent Pattern Mining Algorithm for Network Graphs A novel Frequent Pattern Graph Mining algorithm, FP-GraphMiner, that compactly represents a set of network graphs as a Frequent Pattern Graph (or FP-Graph). This graph can be used to efficiently mine frequent subgraphs including maximal frequent subgraphs and maximum common subgraphs. URL: https://www.researchgate.net/publication/235255851 """ # fmt: off edge_array = [ ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'bh-e12', 'cd-e2', 'ce-e4', 'de-e1', 'df-e8', 'dg-e5', 'dh-e10', 'ef-e3', 'eg-e2', 'fg-e6', 'gh-e6', 'hi-e3'], ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'cd-e2', 'de-e1', 'df-e8', 'ef-e3', 'eg-e2', 'fg-e6'], ['ab-e1', 'ac-e3', 'bc-e4', 'bd-e2', 'de-e1', 'df-e8', 'dg-e5', 'ef-e3', 'eg-e2', 'eh-e12', 'fg-e6', 'fh-e10', 'gh-e6'], ['ab-e1', 'ac-e3', 'bc-e4', 'bd-e2', 'bh-e12', 'cd-e2', 'df-e8', 'dh-e10'], ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'cd-e2', 'ce-e4', 'de-e1', 'df-e8', 'dg-e5', 'ef-e3', 'eg-e2', 'fg-e6'] ] # fmt: on def get_distinct_edge(edge_array): """ Return Distinct edges from edge array of multiple graphs >>> sorted(get_distinct_edge(edge_array)) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] """ distinct_edge = set() for row in edge_array: for item in row: distinct_edge.add(item[0]) return list(distinct_edge) def get_bitcode(edge_array, distinct_edge): """ Return bitcode of distinct_edge """ bitcode = ["0"] * len(edge_array) for i, row in enumerate(edge_array): for item in row: if distinct_edge in item[0]: bitcode[i] = "1" break return "".join(bitcode) def get_frequency_table(edge_array): """ Returns Frequency Table """ distinct_edge = get_distinct_edge(edge_array) frequency_table = {} for item in distinct_edge: bit = get_bitcode(edge_array, item) # print('bit',bit) # bt=''.join(bit) s = bit.count("1") frequency_table[item] = [s, bit] # Store [Distinct edge, WT(Bitcode), Bitcode] in descending order sorted_frequency_table = [ [k, v[0], v[1]] for k, v in sorted(frequency_table.items(), key=lambda v: v[1][0], reverse=True) ] return sorted_frequency_table def get_nodes(frequency_table): """ Returns nodes format nodes={bitcode:edges that represent the bitcode} >>> get_nodes([['ab', 5, '11111'], ['ac', 5, '11111'], ['df', 5, '11111'], ... ['bd', 5, '11111'], ['bc', 5, '11111']]) {'11111': ['ab', 'ac', 'df', 'bd', 'bc']} """ nodes = {} for _, item in enumerate(frequency_table): nodes.setdefault(item[2], []).append(item[0]) return nodes def get_cluster(nodes): """ Returns cluster format cluster:{WT(bitcode):nodes with same WT} """ cluster = {} for key, value in nodes.items(): cluster.setdefault(key.count("1"), {})[key] = value return cluster def get_support(cluster): """ Returns support >>> get_support({5: {'11111': ['ab', 'ac', 'df', 'bd', 'bc']}, ... 4: {'11101': ['ef', 'eg', 'de', 'fg'], '11011': ['cd']}, ... 3: {'11001': ['ad'], '10101': ['dg']}, ... 2: {'10010': ['dh', 'bh'], '11000': ['be'], '10100': ['gh'], ... '10001': ['ce']}, ... 1: {'00100': ['fh', 'eh'], '10000': ['hi']}}) [100.0, 80.0, 60.0, 40.0, 20.0] """ return [i * 100 / len(cluster) for i in cluster] def print_all() -> None: print("\nNodes\n") for key, value in nodes.items(): print(key, value) print("\nSupport\n") print(support) print("\n Cluster \n") for key, value in sorted(cluster.items(), reverse=True): print(key, value) print("\n Graph\n") for key, value in graph.items(): print(key, value) print("\n Edge List of Frequent subgraphs \n") for edge_list in freq_subgraph_edge_list: print(edge_list) def create_edge(nodes, graph, cluster, c1): """ create edge between the nodes """ for i in cluster[c1].keys(): count = 0 c2 = c1 + 1 while c2 < max(cluster.keys()): for j in cluster[c2].keys(): """ creates edge only if the condition satisfies """ if int(i, 2) & int(j, 2) == int(i, 2): if tuple(nodes[i]) in graph: graph[tuple(nodes[i])].append(nodes[j]) else: graph[tuple(nodes[i])] = [nodes[j]] count += 1 if count == 0: c2 = c2 + 1 else: break def construct_graph(cluster, nodes): x = cluster[max(cluster.keys())] cluster[max(cluster.keys()) + 1] = "Header" graph = {} for i in x: if (["Header"],) in graph: graph[(["Header"],)].append(x[i]) else: graph[(["Header"],)] = [x[i]] for i in x: graph[(x[i],)] = [["Header"]] i = 1 while i < max(cluster) - 1: create_edge(nodes, graph, cluster, i) i = i + 1 return graph def my_dfs(graph, start, end, path=None): """ find different DFS walk from given node to Header node """ path = (path or []) + [start] if start == end: paths.append(path) for node in graph[start]: if tuple(node) not in path: my_dfs(graph, tuple(node), end, path) def find_freq_subgraph_given_support(s, cluster, graph): """ find edges of multiple frequent subgraphs """ k = int(s / 100 * (len(cluster) - 1)) for i in cluster[k].keys(): my_dfs(graph, tuple(cluster[k][i]), (["Header"],)) def freq_subgraphs_edge_list(paths): """ returns Edge list for frequent subgraphs """ freq_sub_el = [] for edges in paths: el = [] for j in range(len(edges) - 1): temp = list(edges[j]) for e in temp: edge = (e[0], e[1]) el.append(edge) freq_sub_el.append(el) return freq_sub_el def preprocess(edge_array): """ Preprocess the edge array >>> preprocess([['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'bh-e12', ... 'cd-e2', 'ce-e4', 'de-e1', 'df-e8', 'dg-e5', 'dh-e10', 'ef-e3', ... 'eg-e2', 'fg-e6', 'gh-e6', 'hi-e3']]) """ for i in range(len(edge_array)): for j in range(len(edge_array[i])): t = edge_array[i][j].split("-") edge_array[i][j] = t if __name__ == "__main__": preprocess(edge_array) frequency_table = get_frequency_table(edge_array) nodes = get_nodes(frequency_table) cluster = get_cluster(nodes) support = get_support(cluster) graph = construct_graph(cluster, nodes) find_freq_subgraph_given_support(60, cluster, graph) paths: list = [] freq_subgraph_edge_list = freq_subgraphs_edge_list(paths) print_all()
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
alphabets = [chr(i) for i in range(32, 126)] gear_one = [i for i in range(len(alphabets))] gear_two = [i for i in range(len(alphabets))] gear_three = [i for i in range(len(alphabets))] reflector = [i for i in 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
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" 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 = [x for x in 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 == 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
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This program print the matrix in spiral form. This problem has been solved through recursive way. Matrix must satisfy below conditions i) matrix should be only one or two dimensional ii) number of column of all rows should be equal """ def check_matrix(matrix: list[list[int]]) -> bool: # must be matrix = list(list(row) for row in matrix) if matrix and isinstance(matrix, list): if isinstance(matrix[0], list): prev_len = 0 for row in matrix: if prev_len == 0: prev_len = len(row) result = True else: result = prev_len == len(row) else: result = True else: result = False return result def spiral_print_clockwise(a: list[list[int]]) -> None: """ >>> spiral_print_clockwise([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) 1 2 3 4 8 12 11 10 9 5 6 7 """ if check_matrix(a) and len(a) > 0: a = list(list(row) for row in a) mat_row = len(a) if isinstance(a[0], list): mat_col = len(a[0]) else: for dat in a: print(dat) return # horizotal printing increasing for i in range(0, mat_col): print(a[0][i]) # vertical printing down for i in range(1, mat_row): print(a[i][mat_col - 1]) # horizotal printing decreasing if mat_row > 1: for i in range(mat_col - 2, -1, -1): print(a[mat_row - 1][i]) # vertical printing up for i in range(mat_row - 2, 0, -1): print(a[i][0]) remain_mat = [row[1 : mat_col - 1] for row in a[1 : mat_row - 1]] if len(remain_mat) > 0: spiral_print_clockwise(remain_mat) else: return else: print("Not a valid matrix") return # driver code if __name__ == "__main__": a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] spiral_print_clockwise(a)
""" This program print the matrix in spiral form. This problem has been solved through recursive way. Matrix must satisfy below conditions i) matrix should be only one or two dimensional ii) number of column of all rows should be equal """ def check_matrix(matrix: list[list[int]]) -> bool: # must be matrix = [list(row) for row in matrix] if matrix and isinstance(matrix, list): if isinstance(matrix[0], list): prev_len = 0 for row in matrix: if prev_len == 0: prev_len = len(row) result = True else: result = prev_len == len(row) else: result = True else: result = False return result def spiral_print_clockwise(a: list[list[int]]) -> None: """ >>> spiral_print_clockwise([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) 1 2 3 4 8 12 11 10 9 5 6 7 """ if check_matrix(a) and len(a) > 0: a = [list(row) for row in a] mat_row = len(a) if isinstance(a[0], list): mat_col = len(a[0]) else: for dat in a: print(dat) return # horizotal printing increasing for i in range(0, mat_col): print(a[0][i]) # vertical printing down for i in range(1, mat_row): print(a[i][mat_col - 1]) # horizotal printing decreasing if mat_row > 1: for i in range(mat_col - 2, -1, -1): print(a[mat_row - 1][i]) # vertical printing up for i in range(mat_row - 2, 0, -1): print(a[i][0]) remain_mat = [row[1 : mat_col - 1] for row in a[1 : mat_row - 1]] if len(remain_mat) > 0: spiral_print_clockwise(remain_mat) else: return else: print("Not a valid matrix") return # driver code if __name__ == "__main__": a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] spiral_print_clockwise(a)
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 """ Davis–Putnam–Logemann–Loveland (DPLL) algorithm is a complete, backtracking-based search algorithm for deciding the satisfiability of propositional logic formulae in conjunctive normal form, i.e, for solving the Conjunctive Normal Form SATisfiability (CNF-SAT) problem. For more information about the algorithm: https://en.wikipedia.org/wiki/DPLL_algorithm """ from __future__ import annotations import random from 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 = [i for i in symbols] if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) unit_symbols, assignment = find_unit_clauses(clauses, model) p = None if len(unit_symbols) > 0: p, value = unit_symbols[0], assignment[unit_symbols[0]] if p: tmp_model = model tmp_model[p] = value tmp_symbols = [i for i in symbols] if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) p = symbols[0] rest = symbols[1:] tmp1, tmp2 = model, model tmp1[p], tmp2[p] = True, False return dpll_algorithm(clauses, rest, tmp1) or dpll_algorithm(clauses, rest, tmp2) if __name__ == "__main__": import doctest doctest.testmod() formula = generate_formula() print(f"The formula {formula} is", end=" ") clauses, symbols = generate_parameters(formula) solution, model = dpll_algorithm(clauses, symbols, {}) if solution: print(f"satisfiable with the assignment {model}.") else: print("not satisfiable.")
#!/usr/bin/env python3 """ Davis–Putnam–Logemann–Loveland (DPLL) algorithm is a complete, backtracking-based search algorithm for deciding the satisfiability of propositional logic formulae in conjunctive normal form, i.e, for solving the Conjunctive Normal Form SATisfiability (CNF-SAT) problem. For more information about the algorithm: https://en.wikipedia.org/wiki/DPLL_algorithm """ from __future__ import annotations import random from 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.")
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The 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 = list(map(lambda word: word.strip('"'), words.strip("\r\n").split(","))) words = list( filter( lambda word: word in TRIANGULAR_NUMBERS, map(lambda word: sum(map(lambda x: ord(x) - 64, word)), words), ) ) 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 = list( filter( lambda word: word in TRIANGULAR_NUMBERS, (sum(ord(x) - 64 for x in word) for word in words), ) ) return len(words) if __name__ == "__main__": print(solution())
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" 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(list(str(i))) == sorted(list(str(2 * i))) == sorted(list(str(3 * i))) == sorted(list(str(4 * i))) == sorted(list(str(5 * i))) == sorted(list(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
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler 62 https://projecteuler.net/problem=62 The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube. Find the smallest cube for which exactly five permutations of its digits are cube. """ from collections import defaultdict def solution(max_base: int = 5) -> int: """ Iterate through every possible cube and sort the cube's digits in ascending order. Sorting maintains an ordering of the digits that allows you to compare permutations. Store each sorted sequence of digits in a dictionary, whose key is the sequence of digits and value is a list of numbers that are the base of the cube. Once you find 5 numbers that produce the same sequence of digits, return the smallest one, which is at index 0 since we insert each base number in ascending order. >>> solution(2) 125 >>> solution(3) 41063625 """ freqs = defaultdict(list) num = 0 while True: digits = get_digits(num) freqs[digits].append(num) if len(freqs[digits]) == max_base: base = freqs[digits][0] ** 3 return base num += 1 def get_digits(num: int) -> str: """ Computes the sorted sequence of digits of the cube of num. >>> get_digits(3) '27' >>> get_digits(99) '027999' >>> get_digits(123) '0166788' """ return "".join(sorted(list(str(num**3)))) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler 62 https://projecteuler.net/problem=62 The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube. Find the smallest cube for which exactly five permutations of its digits are cube. """ from collections import defaultdict def solution(max_base: int = 5) -> int: """ Iterate through every possible cube and sort the cube's digits in ascending order. Sorting maintains an ordering of the digits that allows you to compare permutations. Store each sorted sequence of digits in a dictionary, whose key is the sequence of digits and value is a list of numbers that are the base of the cube. Once you find 5 numbers that produce the same sequence of digits, return the smallest one, which is at index 0 since we insert each base number in ascending order. >>> solution(2) 125 >>> solution(3) 41063625 """ freqs = defaultdict(list) num = 0 while True: digits = get_digits(num) freqs[digits].append(num) if len(freqs[digits]) == max_base: base = freqs[digits][0] ** 3 return base num += 1 def get_digits(num: int) -> str: """ Computes the sorted sequence of digits of the cube of num. >>> get_digits(3) '27' >>> get_digits(99) '027999' >>> get_digits(123) '0166788' """ return "".join(sorted(str(num**3))) if __name__ == "__main__": print(f"{solution() = }")
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem Statement: By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. """ import os def solution(): """ Finds the maximum total in a triangle as described by the problem statement above. >>> solution() 7273 """ script_dir = os.path.dirname(os.path.realpath(__file__)) triangle = os.path.join(script_dir, "triangle.txt") with open(triangle) as f: triangle = f.readlines() a = map(lambda x: x.rstrip("\r\n").split(" "), triangle) a = list(map(lambda x: list(map(int, x)), a)) for i in range(1, len(a)): for j in range(len(a[i])): if j != len(a[i - 1]): number1 = a[i - 1][j] else: number1 = 0 if j > 0: number2 = a[i - 1][j - 1] else: number2 = 0 a[i][j] += max(number1, number2) return max(a[-1]) if __name__ == "__main__": print(solution())
""" Problem Statement: By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. """ import os def solution(): """ Finds the maximum total in a triangle as described by the problem statement above. >>> solution() 7273 """ script_dir = os.path.dirname(os.path.realpath(__file__)) triangle = os.path.join(script_dir, "triangle.txt") with open(triangle) as f: triangle = f.readlines() a = (x.rstrip("\r\n").split(" ") for x in triangle) a = [list(map(int, x)) for x in a] for i in range(1, len(a)): for j in range(len(a[i])): if j != len(a[i - 1]): number1 = a[i - 1][j] else: number1 = 0 if j > 0: number2 = a[i - 1][j - 1] else: number2 = 0 a[i][j] += max(number1, number2) return max(a[-1]) if __name__ == "__main__": print(solution())
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" In the game of darts a player throws three darts at a target board which is split into twenty equal sized sections numbered one to twenty.  The score of a dart is determined by the number of the region that the dart lands in. A dart landing outside the red/green outer ring scores zero. The black and cream regions inside this ring represent single scores. However, the red/green outer ring and middle ring score double and treble scores respectively. At the centre of the board are two concentric circles called the bull region, or bulls-eye. The outer bull is worth 25 points and the inner bull is a double, worth 50 points. There are many variations of rules but in the most popular game the players will begin with a score 301 or 501 and the first player to reduce their running total to zero is a winner. However, it is normal to play a "doubles out" system, which means that the player must land a double (including the double bulls-eye at the centre of the board) on their final dart to win; any other dart that would reduce their running total to one or lower means the score for that set of three darts is "bust". When a player is able to finish on their current score it is called a "checkout" and the highest checkout is 170: T20 T20 D25 (two treble 20s and double bull). There are exactly eleven distinct ways to checkout on a score of 6: D3 D1 D2 S2 D2 D2 D1 S4 D1 S1 S1 D2 S1 T1 D1 S1 S3 D1 D1 D1 D1 D1 S2 D1 S2 S2 D1 Note that D1 D2 is considered different to D2 D1 as they finish on different doubles. However, the combination S1 T1 D1 is considered the same as T1 S1 D1. In addition we shall not include misses in considering combinations; for example, D3 is the same as 0 D3 and 0 0 D3. Incredibly there are 42336 distinct ways of checking out in total. How many distinct ways can a player checkout with a score less than 100? Solution: We first construct a list of the possible dart values, separated by type. We then iterate through the doubles, followed by the possible 2 following throws. If the total of these three darts is less than the given limit, we increment the counter. """ from itertools import combinations_with_replacement def solution(limit: int = 100) -> int: """ Count the number of distinct ways a player can checkout with a score less than limit. >>> solution(171) 42336 >>> solution(50) 12577 """ singles: list[int] = [x for x in range(1, 21)] + [25] doubles: list[int] = [2 * x for x in range(1, 21)] + [50] triples: list[int] = [3 * x for x in range(1, 21)] all_values: list[int] = singles + doubles + triples + [0] num_checkouts: int = 0 double: int throw1: int throw2: int checkout_total: int for double in doubles: for throw1, throw2 in combinations_with_replacement(all_values, 2): checkout_total = double + throw1 + throw2 if checkout_total < limit: num_checkouts += 1 return num_checkouts if __name__ == "__main__": print(f"{solution() = }")
""" In the game of darts a player throws three darts at a target board which is split into twenty equal sized sections numbered one to twenty.  The score of a dart is determined by the number of the region that the dart lands in. A dart landing outside the red/green outer ring scores zero. The black and cream regions inside this ring represent single scores. However, the red/green outer ring and middle ring score double and treble scores respectively. At the centre of the board are two concentric circles called the bull region, or bulls-eye. The outer bull is worth 25 points and the inner bull is a double, worth 50 points. There are many variations of rules but in the most popular game the players will begin with a score 301 or 501 and the first player to reduce their running total to zero is a winner. However, it is normal to play a "doubles out" system, which means that the player must land a double (including the double bulls-eye at the centre of the board) on their final dart to win; any other dart that would reduce their running total to one or lower means the score for that set of three darts is "bust". When a player is able to finish on their current score it is called a "checkout" and the highest checkout is 170: T20 T20 D25 (two treble 20s and double bull). There are exactly eleven distinct ways to checkout on a score of 6: D3 D1 D2 S2 D2 D2 D1 S4 D1 S1 S1 D2 S1 T1 D1 S1 S3 D1 D1 D1 D1 D1 S2 D1 S2 S2 D1 Note that D1 D2 is considered different to D2 D1 as they finish on different doubles. However, the combination S1 T1 D1 is considered the same as T1 S1 D1. In addition we shall not include misses in considering combinations; for example, D3 is the same as 0 D3 and 0 0 D3. Incredibly there are 42336 distinct ways of checking out in total. How many distinct ways can a player checkout with a score less than 100? Solution: We first construct a list of the possible dart values, separated by type. We then iterate through the doubles, followed by the possible 2 following throws. If the total of these three darts is less than the given limit, we increment the counter. """ from itertools import combinations_with_replacement def solution(limit: int = 100) -> int: """ Count the number of distinct ways a player can checkout with a score less than limit. >>> solution(171) 42336 >>> solution(50) 12577 """ singles: list[int] = list(range(1, 21)) + [25] doubles: list[int] = [2 * x for x in range(1, 21)] + [50] triples: list[int] = [3 * x for x in range(1, 21)] all_values: list[int] = singles + doubles + triples + [0] num_checkouts: int = 0 double: int throw1: int throw2: int checkout_total: int for double in doubles: for throw1, throw2 in combinations_with_replacement(all_values, 2): checkout_total = double + throw1 + throw2 if checkout_total < limit: num_checkouts += 1 return num_checkouts if __name__ == "__main__": print(f"{solution() = }")
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Sum of digits sequence Problem 551 Let a(0), a(1),... be an integer sequence defined by: a(0) = 1 for n >= 1, a(n) is the sum of the digits of all preceding terms The sequence starts with 1, 1, 2, 4, 8, ... You are given a(10^6) = 31054319. Find a(10^15) """ ks = [k for k in range(2, 20 + 1)] base = [10**k for k in range(ks[-1] + 1)] memo: dict[int, dict[int, list[list[int]]]] = {} def next_term(a_i, k, i, n): """ Calculates and updates a_i in-place to either the n-th term or the smallest term for which c > 10^k when the terms are written in the form: a(i) = b * 10^k + c For any a(i), if digitsum(b) and c have the same value, the difference between subsequent terms will be the same until c >= 10^k. This difference is cached to greatly speed up the computation. Arguments: a_i -- array of digits starting from the one's place that represent the i-th term in the sequence k -- k when terms are written in the from a(i) = b*10^k + c. Term are calulcated until c > 10^k or the n-th term is reached. i -- position along the sequence n -- term to calculate up to if k is large enough Return: a tuple of difference between ending term and starting term, and the number of terms calculated. ex. if starting term is a_0=1, and ending term is a_10=62, then (61, 9) is returned. """ # ds_b - digitsum(b) ds_b = sum(a_i[j] for j in range(k, len(a_i))) c = sum(a_i[j] * base[j] for j in range(min(len(a_i), k))) diff, dn = 0, 0 max_dn = n - i sub_memo = memo.get(ds_b) if sub_memo is not None: jumps = sub_memo.get(c) if jumps is not None and len(jumps) > 0: # find and make the largest jump without going over max_jump = -1 for _k in range(len(jumps) - 1, -1, -1): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: max_jump = _k break if max_jump >= 0: diff, dn, _kk = jumps[max_jump] # since the difference between jumps is cached, add c new_c = diff + c for j in range(min(k, len(a_i))): new_c, a_i[j] = divmod(new_c, 10) if new_c > 0: add(a_i, k, new_c) else: sub_memo[c] = [] else: sub_memo = {c: []} memo[ds_b] = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps _diff, terms_jumped = next_term(a_i, k - 1, i + dn, n) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead _diff, terms_jumped = compute(a_i, k, i + dn, n) diff += _diff dn += terms_jumped jumps = sub_memo[c] # keep jumps sorted by # of terms skipped j = 0 while j < len(jumps): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(j, (diff, dn, k)) return (diff, dn) def compute(a_i, k, i, n): """ same as next_term(a_i, k, i, n) but computes terms without memoizing results. """ if i >= n: return 0, i if k > len(a_i): a_i.extend([0 for _ in range(k - len(a_i))]) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) start_i = i ds_b, ds_c, diff = 0, 0, 0 for j in range(len(a_i)): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 addend = ds_c + ds_b diff += addend ds_c = 0 for j in range(k): s = a_i[j] + addend addend, a_i[j] = divmod(s, 10) ds_c += a_i[j] if addend > 0: break if addend > 0: add(a_i, k, addend) return diff, i - start_i def add(digits, k, addend): """ adds addend to digit array given in digits starting at index k """ for j in range(k, len(digits)): s = digits[j] + addend if s >= 10: quotient, digits[j] = divmod(s, 10) addend = addend // 10 + quotient else: digits[j] = s addend = addend // 10 if addend == 0: break while addend > 0: addend, digit = divmod(addend, 10) digits.append(digit) def solution(n: int = 10**15) -> int: """ returns n-th term of sequence >>> solution(10) 62 >>> solution(10**6) 31054319 >>> solution(10**15) 73597483551591773 """ digits = [1] i = 1 dn = 0 while True: diff, terms_jumped = next_term(digits, 20, i + dn, n) dn += terms_jumped if dn == n - i: break a_n = 0 for j in range(len(digits)): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f"{solution() = }")
""" Sum of digits sequence Problem 551 Let a(0), a(1),... be an integer sequence defined by: a(0) = 1 for n >= 1, a(n) is the sum of the digits of all preceding terms The sequence starts with 1, 1, 2, 4, 8, ... You are given a(10^6) = 31054319. Find a(10^15) """ ks = range(2, 20 + 1) base = [10**k for k in range(ks[-1] + 1)] memo: dict[int, dict[int, list[list[int]]]] = {} def next_term(a_i, k, i, n): """ Calculates and updates a_i in-place to either the n-th term or the smallest term for which c > 10^k when the terms are written in the form: a(i) = b * 10^k + c For any a(i), if digitsum(b) and c have the same value, the difference between subsequent terms will be the same until c >= 10^k. This difference is cached to greatly speed up the computation. Arguments: a_i -- array of digits starting from the one's place that represent the i-th term in the sequence k -- k when terms are written in the from a(i) = b*10^k + c. Term are calulcated until c > 10^k or the n-th term is reached. i -- position along the sequence n -- term to calculate up to if k is large enough Return: a tuple of difference between ending term and starting term, and the number of terms calculated. ex. if starting term is a_0=1, and ending term is a_10=62, then (61, 9) is returned. """ # ds_b - digitsum(b) ds_b = sum(a_i[j] for j in range(k, len(a_i))) c = sum(a_i[j] * base[j] for j in range(min(len(a_i), k))) diff, dn = 0, 0 max_dn = n - i sub_memo = memo.get(ds_b) if sub_memo is not None: jumps = sub_memo.get(c) if jumps is not None and len(jumps) > 0: # find and make the largest jump without going over max_jump = -1 for _k in range(len(jumps) - 1, -1, -1): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: max_jump = _k break if max_jump >= 0: diff, dn, _kk = jumps[max_jump] # since the difference between jumps is cached, add c new_c = diff + c for j in range(min(k, len(a_i))): new_c, a_i[j] = divmod(new_c, 10) if new_c > 0: add(a_i, k, new_c) else: sub_memo[c] = [] else: sub_memo = {c: []} memo[ds_b] = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps _diff, terms_jumped = next_term(a_i, k - 1, i + dn, n) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead _diff, terms_jumped = compute(a_i, k, i + dn, n) diff += _diff dn += terms_jumped jumps = sub_memo[c] # keep jumps sorted by # of terms skipped j = 0 while j < len(jumps): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(j, (diff, dn, k)) return (diff, dn) def compute(a_i, k, i, n): """ same as next_term(a_i, k, i, n) but computes terms without memoizing results. """ if i >= n: return 0, i if k > len(a_i): a_i.extend([0 for _ in range(k - len(a_i))]) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) start_i = i ds_b, ds_c, diff = 0, 0, 0 for j in range(len(a_i)): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 addend = ds_c + ds_b diff += addend ds_c = 0 for j in range(k): s = a_i[j] + addend addend, a_i[j] = divmod(s, 10) ds_c += a_i[j] if addend > 0: break if addend > 0: add(a_i, k, addend) return diff, i - start_i def add(digits, k, addend): """ adds addend to digit array given in digits starting at index k """ for j in range(k, len(digits)): s = digits[j] + addend if s >= 10: quotient, digits[j] = divmod(s, 10) addend = addend // 10 + quotient else: digits[j] = s addend = addend // 10 if addend == 0: break while addend > 0: addend, digit = divmod(addend, 10) digits.append(digit) def solution(n: int = 10**15) -> int: """ returns n-th term of sequence >>> solution(10) 62 >>> solution(10**6) 31054319 >>> solution(10**15) 73597483551591773 """ digits = [1] i = 1 dn = 0 while True: diff, terms_jumped = next_term(digits, 20, i + dn, n) dn += terms_jumped if dn == n - i: break a_n = 0 for j in range(len(digits)): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f"{solution() = }")
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a pure Python implementation of the radix sort algorithm Source: https://en.wikipedia.org/wiki/Radix_sort """ from __future__ import annotations def radix_sort(list_of_ints: list[int]) -> list[int]: """ Examples: >>> radix_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> radix_sort(list(range(15))) == sorted(range(15)) True >>> radix_sort(list(range(14,-1,-1))) == sorted(range(15)) True >>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000]) True """ RADIX = 10 # noqa: N806 placement = 1 max_digit = max(list_of_ints) while placement <= max_digit: # declare and initialize empty buckets buckets: list[list] = [list() for _ in range(RADIX)] # split list_of_ints between the buckets for i in list_of_ints: tmp = int((i / placement) % RADIX) buckets[tmp].append(i) # put each buckets' contents into list_of_ints a = 0 for b in range(RADIX): for i in buckets[b]: list_of_ints[a] = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
""" This is a pure Python implementation of the radix sort algorithm Source: https://en.wikipedia.org/wiki/Radix_sort """ from __future__ import annotations def radix_sort(list_of_ints: list[int]) -> list[int]: """ Examples: >>> radix_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> radix_sort(list(range(15))) == sorted(range(15)) True >>> radix_sort(list(range(14,-1,-1))) == sorted(range(15)) True >>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000]) True """ RADIX = 10 # noqa: N806 placement = 1 max_digit = max(list_of_ints) while placement <= max_digit: # declare and initialize empty buckets buckets: list[list] = [[] for _ in range(RADIX)] # split list_of_ints between the buckets for i in list_of_ints: tmp = int((i / placement) % RADIX) buckets[tmp].append(i) # put each buckets' contents into list_of_ints a = 0 for b in range(RADIX): for i in buckets[b]: list_of_ints[a] = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from collections import deque class Automaton: def __init__(self, keywords: list[str]): self.adlist: list[dict] = [] self.adlist.append( {"value": "", "next_states": [], "fail_state": 0, "output": []} ) for keyword in keywords: self.add_keyword(keyword) self.set_fail_transitions() def find_next_state(self, current_state: int, char: str) -> int | None: for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def add_keyword(self, keyword: str) -> None: current_state = 0 for character in keyword: next_state = self.find_next_state(current_state, character) if next_state is None: self.adlist.append( { "value": character, "next_states": [], "fail_state": 0, "output": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist) - 1) current_state = len(self.adlist) - 1 else: current_state = next_state self.adlist[current_state]["output"].append(keyword) def set_fail_transitions(self) -> None: q: deque = deque() for node in self.adlist[0]["next_states"]: q.append(node) self.adlist[node]["fail_state"] = 0 while q: r = q.popleft() for child in self.adlist[r]["next_states"]: q.append(child) state = self.adlist[r]["fail_state"] while ( self.find_next_state(state, self.adlist[child]["value"]) is None and state != 0 ): state = self.adlist[state]["fail_state"] self.adlist[child]["fail_state"] = self.find_next_state( state, self.adlist[child]["value"] ) if self.adlist[child]["fail_state"] is None: self.adlist[child]["fail_state"] = 0 self.adlist[child]["output"] = ( self.adlist[child]["output"] + self.adlist[self.adlist[child]["fail_state"]]["output"] ) def search_in(self, string: str) -> dict[str, list[int]]: """ >>> A = Automaton(["what", "hat", "ver", "er"]) >>> A.search_in("whatever, err ... , wherever") {'what': [0], 'hat': [1], 'ver': [5, 25], 'er': [6, 10, 22, 26]} """ result: dict = ( dict() ) # returns a dict with keywords and list of its occurrences current_state = 0 for i in range(len(string)): while ( self.find_next_state(current_state, string[i]) is None and current_state != 0 ): current_state = self.adlist[current_state]["fail_state"] next_state = self.find_next_state(current_state, string[i]) if next_state is None: current_state = 0 else: current_state = next_state for key in self.adlist[current_state]["output"]: if not (key in result): result[key] = [] result[key].append(i - len(key) + 1) return result if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations from collections import deque class Automaton: def __init__(self, keywords: list[str]): self.adlist: list[dict] = [] self.adlist.append( {"value": "", "next_states": [], "fail_state": 0, "output": []} ) for keyword in keywords: self.add_keyword(keyword) self.set_fail_transitions() def find_next_state(self, current_state: int, char: str) -> int | None: for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def add_keyword(self, keyword: str) -> None: current_state = 0 for character in keyword: next_state = self.find_next_state(current_state, character) if next_state is None: self.adlist.append( { "value": character, "next_states": [], "fail_state": 0, "output": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist) - 1) current_state = len(self.adlist) - 1 else: current_state = next_state self.adlist[current_state]["output"].append(keyword) def set_fail_transitions(self) -> None: q: deque = deque() for node in self.adlist[0]["next_states"]: q.append(node) self.adlist[node]["fail_state"] = 0 while q: r = q.popleft() for child in self.adlist[r]["next_states"]: q.append(child) state = self.adlist[r]["fail_state"] while ( self.find_next_state(state, self.adlist[child]["value"]) is None and state != 0 ): state = self.adlist[state]["fail_state"] self.adlist[child]["fail_state"] = self.find_next_state( state, self.adlist[child]["value"] ) if self.adlist[child]["fail_state"] is None: self.adlist[child]["fail_state"] = 0 self.adlist[child]["output"] = ( self.adlist[child]["output"] + self.adlist[self.adlist[child]["fail_state"]]["output"] ) def search_in(self, string: str) -> dict[str, list[int]]: """ >>> A = Automaton(["what", "hat", "ver", "er"]) >>> A.search_in("whatever, err ... , wherever") {'what': [0], 'hat': [1], 'ver': [5, 25], 'er': [6, 10, 22, 26]} """ result: dict = {} # returns a dict with keywords and list of its occurrences current_state = 0 for i in range(len(string)): while ( self.find_next_state(current_state, string[i]) is None and current_state != 0 ): current_state = self.adlist[current_state]["fail_state"] next_state = self.find_next_state(current_state, string[i]) if next_state is None: current_state = 0 else: current_state = next_state for key in self.adlist[current_state]["output"]: if not (key in result): result[key] = [] result[key].append(i - len(key) + 1) return result if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def double_linear_search(array: list[int], search_item: int) -> int: """ Iterate through the array from both sides to find the index of search_item. :param array: the array to be searched :param search_item: the item to be searched :return the index of search_item, if search_item is in array, else -1 Examples: >>> double_linear_search([1, 5, 5, 10], 1) 0 >>> double_linear_search([1, 5, 5, 10], 5) 1 >>> double_linear_search([1, 5, 5, 10], 100) -1 >>> double_linear_search([1, 5, 5, 10], 10) 3 """ # define the start and end index of the given array start_ind, end_ind = 0, len(array) - 1 while start_ind <= end_ind: if array[start_ind] == search_item: return start_ind elif array[end_ind] == search_item: return end_ind else: start_ind += 1 end_ind -= 1 # returns -1 if search_item is not found in array return -1 if __name__ == "__main__": print(double_linear_search(list(range(100)), 40))
from __future__ import annotations def double_linear_search(array: list[int], search_item: int) -> int: """ Iterate through the array from both sides to find the index of search_item. :param array: the array to be searched :param search_item: the item to be searched :return the index of search_item, if search_item is in array, else -1 Examples: >>> double_linear_search([1, 5, 5, 10], 1) 0 >>> double_linear_search([1, 5, 5, 10], 5) 1 >>> double_linear_search([1, 5, 5, 10], 100) -1 >>> double_linear_search([1, 5, 5, 10], 10) 3 """ # define the start and end index of the given array start_ind, end_ind = 0, len(array) - 1 while start_ind <= end_ind: if array[start_ind] == search_item: return start_ind elif array[end_ind] == search_item: return end_ind else: start_ind += 1 end_ind -= 1 # returns -1 if search_item is not found in array return -1 if __name__ == "__main__": print(double_linear_search(list(range(100)), 40))
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def max_subarray(nums: list[int]) -> int: """ Returns the subarray with maximum sum >>> max_subarray([1,2,3,4,-2]) 10 >>> max_subarray([-2,1,-3,4,-1,2,1,-5,4]) 6 """ curr_max = ans = nums[0] for i in range(1, len(nums)): if curr_max >= 0: curr_max = curr_max + nums[i] else: curr_max = nums[i] ans = max(curr_max, ans) return ans if __name__ == "__main__": n = int(input("Enter number of elements : ").strip()) array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n] print(max_subarray(array))
def max_subarray(nums: list[int]) -> int: """ Returns the subarray with maximum sum >>> max_subarray([1,2,3,4,-2]) 10 >>> max_subarray([-2,1,-3,4,-1,2,1,-5,4]) 6 """ curr_max = ans = nums[0] for i in range(1, len(nums)): if curr_max >= 0: curr_max = curr_max + nums[i] else: curr_max = nums[i] ans = max(curr_max, ans) return ans if __name__ == "__main__": n = int(input("Enter number of elements : ").strip()) array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n] print(max_subarray(array))
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 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 < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution() 31875000 """ for a in range(300): for b in range(a + 1, 400): for c in range(b + 1, 500): if (a + b + c) == 1000: if (a**2) + (b**2) == (c**2): return a * b * c return -1 def solution_fast() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution_fast() 31875000 """ for a in range(300): for b in range(400): c = 1000 - a - b if a < b < c and (a**2) + (b**2) == (c**2): return a * b * c return -1 def benchmark() -> None: """ Benchmark code comparing two different version function. """ import timeit print( timeit.timeit("solution()", setup="from __main__ import solution", number=1000) ) print( timeit.timeit( "solution_fast()", setup="from __main__ import solution_fast", number=1000 ) ) 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 < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution() 31875000 """ for a in range(300): for b in range(a + 1, 400): for c in range(b + 1, 500): if (a + b + c) == 1000: if (a**2) + (b**2) == (c**2): return a * b * c return -1 def solution_fast() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution_fast() 31875000 """ for a in range(300): for b in range(400): c = 1000 - a - b if a < b < c and (a**2) + (b**2) == (c**2): return a * b * c return -1 def benchmark() -> None: """ Benchmark code comparing two different version function. """ import timeit print( timeit.timeit("solution()", setup="from __main__ import solution", number=1000) ) print( timeit.timeit( "solution_fast()", setup="from __main__ import solution_fast", number=1000 ) ) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 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
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ 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
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from collections.abc import Sequence def compare_string(string1: str, string2: str) -> str: """ >>> compare_string('0010','0110') '0_10' >>> compare_string('0110','1101') 'X' """ list1 = list(string1) list2 = list(string2) count = 0 for i in range(len(list1)): if list1[i] != list2[i]: count += 1 list1[i] = "_" if count > 1: return "X" else: return "".join(list1) def check(binary: list[str]) -> list[str]: """ >>> check(['0.00.01.5']) ['0.00.01.5'] """ pi = [] while True: check1 = ["$"] * len(binary) temp = [] for i in range(len(binary)): for j in range(i + 1, len(binary)): k = compare_string(binary[i], binary[j]) if k != "X": check1[i] = "*" check1[j] = "*" temp.append(k) for i in range(len(binary)): if check1[i] == "$": pi.append(binary[i]) if len(temp) == 0: return pi binary = list(set(temp)) def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]: """ >>> decimal_to_binary(3,[1.5]) ['0.00.01.5'] """ temp = [] for minterm in minterms: string = "" for _ in range(no_of_variable): string = str(minterm % 2) + string minterm //= 2 temp.append(string) return temp def is_for_table(string1: str, string2: str, count: int) -> bool: """ >>> is_for_table('__1','011',2) True >>> is_for_table('01_','001',1) False """ list1 = list(string1) list2 = list(string2) count_n = 0 for i in range(len(list1)): if list1[i] != list2[i]: count_n += 1 return count_n == count def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]: """ >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] """ temp = [] select = [0] * len(chart) for i in range(len(chart[0])): count = 0 rem = -1 for j in range(len(chart)): if chart[j][i] == 1: count += 1 rem = j if count == 1: select[rem] = 1 for i in range(len(select)): if select[i] == 1: for j in range(len(chart[0])): if chart[i][j] == 1: for k in range(len(chart)): chart[k][j] = 0 temp.append(prime_implicants[i]) while True: max_n = 0 rem = -1 count_n = 0 for i in range(len(chart)): count_n = chart[i].count(1) if count_n > max_n: max_n = count_n rem = i if max_n == 0: return temp temp.append(prime_implicants[rem]) for i in range(len(chart[0])): if chart[rem][i] == 1: for j in range(len(chart)): chart[j][i] = 0 def prime_implicant_chart( prime_implicants: list[str], binary: list[str] ) -> list[list[int]]: """ >>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5']) [[1]] """ chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))] for i in range(len(prime_implicants)): count = prime_implicants[i].count("_") for j in range(len(binary)): if is_for_table(prime_implicants[i], binary[j], count): chart[i][j] = 1 return chart def main() -> None: no_of_variable = int(input("Enter the no. of variables\n")) minterms = [ float(x) for x in input( "Enter the decimal representation of Minterms 'Spaces Separated'\n" ).split() ] binary = decimal_to_binary(no_of_variable, minterms) prime_implicants = check(binary) print("Prime Implicants are:") print(prime_implicants) chart = prime_implicant_chart(prime_implicants, binary) essential_prime_implicants = selection(chart, prime_implicants) print("Essential Prime Implicants are:") print(essential_prime_implicants) if __name__ == "__main__": import doctest doctest.testmod() main()
from __future__ import annotations from collections.abc import Sequence def compare_string(string1: str, string2: str) -> str: """ >>> compare_string('0010','0110') '0_10' >>> compare_string('0110','1101') 'X' """ list1 = list(string1) list2 = list(string2) count = 0 for i in range(len(list1)): if list1[i] != list2[i]: count += 1 list1[i] = "_" if count > 1: return "X" else: return "".join(list1) def check(binary: list[str]) -> list[str]: """ >>> check(['0.00.01.5']) ['0.00.01.5'] """ pi = [] while True: check1 = ["$"] * len(binary) temp = [] for i in range(len(binary)): for j in range(i + 1, len(binary)): k = compare_string(binary[i], binary[j]) if k != "X": check1[i] = "*" check1[j] = "*" temp.append(k) for i in range(len(binary)): if check1[i] == "$": pi.append(binary[i]) if len(temp) == 0: return pi binary = list(set(temp)) def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]: """ >>> decimal_to_binary(3,[1.5]) ['0.00.01.5'] """ temp = [] for minterm in minterms: string = "" for _ in range(no_of_variable): string = str(minterm % 2) + string minterm //= 2 temp.append(string) return temp def is_for_table(string1: str, string2: str, count: int) -> bool: """ >>> is_for_table('__1','011',2) True >>> is_for_table('01_','001',1) False """ list1 = list(string1) list2 = list(string2) count_n = 0 for i in range(len(list1)): if list1[i] != list2[i]: count_n += 1 return count_n == count def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]: """ >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] """ temp = [] select = [0] * len(chart) for i in range(len(chart[0])): count = 0 rem = -1 for j in range(len(chart)): if chart[j][i] == 1: count += 1 rem = j if count == 1: select[rem] = 1 for i in range(len(select)): if select[i] == 1: for j in range(len(chart[0])): if chart[i][j] == 1: for k in range(len(chart)): chart[k][j] = 0 temp.append(prime_implicants[i]) while True: max_n = 0 rem = -1 count_n = 0 for i in range(len(chart)): count_n = chart[i].count(1) if count_n > max_n: max_n = count_n rem = i if max_n == 0: return temp temp.append(prime_implicants[rem]) for i in range(len(chart[0])): if chart[rem][i] == 1: for j in range(len(chart)): chart[j][i] = 0 def prime_implicant_chart( prime_implicants: list[str], binary: list[str] ) -> list[list[int]]: """ >>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5']) [[1]] """ chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))] for i in range(len(prime_implicants)): count = prime_implicants[i].count("_") for j in range(len(binary)): if is_for_table(prime_implicants[i], binary[j], count): chart[i][j] = 1 return chart def main() -> None: no_of_variable = int(input("Enter the no. of variables\n")) minterms = [ float(x) for x in input( "Enter the decimal representation of Minterms 'Spaces Separated'\n" ).split() ] binary = decimal_to_binary(no_of_variable, minterms) prime_implicants = check(binary) print("Prime Implicants are:") print(prime_implicants) chart = prime_implicant_chart(prime_implicants, binary) essential_prime_implicants = selection(chart, prime_implicants) print("Essential Prime Implicants are:") print(essential_prime_implicants) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 # This Python program implements an optimal binary search tree (abbreviated BST) # building dynamic programming algorithm that delivers O(n^2) performance. # # The goal of the optimal BST problem is to build a low-cost BST for a # given set of nodes, each with its own key and frequency. The frequency # of the node is defined as how many time the node is being searched. # The search cost of binary search tree is given by this formula: # # cost(1, n) = sum{i = 1 to n}((depth(node_i) + 1) * node_i_freq) # # where n is number of nodes in the BST. The characteristic of low-cost # BSTs is having a faster overall search time than other implementations. # The reason for their fast search time is that the nodes with high # frequencies will be placed near the root of the tree while the nodes # with low frequencies will be placed near the leaves of the tree thus # reducing search time in the most frequent instances. import sys from random import randint class Node: """Binary Search Tree Node""" def __init__(self, key, freq): self.key = key self.freq = freq def __str__(self): """ >>> str(Node(1, 2)) 'Node(key=1, freq=2)' """ return f"Node(key={self.key}, freq={self.freq})" def print_binary_search_tree(root, key, i, j, parent, is_left): """ Recursive function to print a BST from a root table. >>> key = [3, 8, 9, 10, 17, 21] >>> root = [[0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 3], [0, 0, 2, 3, 3, 3], \ [0, 0, 0, 3, 3, 3], [0, 0, 0, 0, 4, 5], [0, 0, 0, 0, 0, 5]] >>> print_binary_search_tree(root, key, 0, 5, -1, False) 8 is the root of the binary search tree. 3 is the left child of key 8. 10 is the right child of key 8. 9 is the left child of key 10. 21 is the right child of key 10. 17 is the left child of key 21. """ if i > j or i < 0 or j > len(root) - 1: return node = root[i][j] if parent == -1: # root does not have a parent print(f"{key[node]} is the root of the binary search tree.") elif is_left: print(f"{key[node]} is the left child of key {parent}.") else: print(f"{key[node]} is the right child of key {parent}.") print_binary_search_tree(root, key, i, node - 1, key[node], True) print_binary_search_tree(root, key, node + 1, j, key[node], False) def find_optimal_binary_search_tree(nodes): """ This function calculates and prints the optimal binary search tree. The dynamic programming algorithm below runs in O(n^2) time. Implemented from CLRS (Introduction to Algorithms) book. https://en.wikipedia.org/wiki/Introduction_to_Algorithms >>> find_optimal_binary_search_tree([Node(12, 8), Node(10, 34), Node(20, 50), \ Node(42, 3), Node(25, 40), Node(37, 30)]) Binary search tree nodes: Node(key=10, freq=34) Node(key=12, freq=8) Node(key=20, freq=50) Node(key=25, freq=40) Node(key=37, freq=30) Node(key=42, freq=3) <BLANKLINE> The cost of optimal BST for given tree nodes is 324. 20 is the root of the binary search tree. 10 is the left child of key 20. 12 is the right child of key 10. 25 is the right child of key 20. 37 is the right child of key 25. 42 is the right child of key 37. """ # Tree nodes must be sorted first, the code below sorts the keys in # increasing order and rearrange its frequencies accordingly. nodes.sort(key=lambda node: node.key) n = len(nodes) keys = [nodes[i].key for i in range(n)] freqs = [nodes[i].freq for i in range(n)] # This 2D array stores the overall tree cost (which's as minimized as possible); # for a single key, cost is equal to frequency of the key. dp = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # sum[i][j] stores the sum of key frequencies between i and j inclusive in nodes # array total = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # stores tree roots that will be used later for constructing binary search tree root = [[i if i == j else 0 for j in range(n)] for i in range(n)] for interval_length in range(2, n + 1): for i in range(n - interval_length + 1): j = i + interval_length - 1 dp[i][j] = sys.maxsize # set the value to "infinity" total[i][j] = total[i][j - 1] + freqs[j] # Apply Knuth's optimization # Loop without optimization: for r in range(i, j + 1): for r in range(root[i][j - 1], root[i + 1][j] + 1): # r is a temporal root left = dp[i][r - 1] if r != i else 0 # optimal cost for left subtree right = dp[r + 1][j] if r != j else 0 # optimal cost for right subtree cost = left + total[i][j] + right if dp[i][j] > cost: dp[i][j] = cost root[i][j] = r print("Binary search tree nodes:") for node in nodes: print(node) print(f"\nThe cost of optimal BST for given tree nodes is {dp[0][n - 1]}.") print_binary_search_tree(root, keys, 0, n - 1, -1, False) def main(): # A sample binary search tree nodes = [Node(i, randint(1, 50)) for i in range(10, 0, -1)] find_optimal_binary_search_tree(nodes) if __name__ == "__main__": main()
#!/usr/bin/env python3 # This Python program implements an optimal binary search tree (abbreviated BST) # building dynamic programming algorithm that delivers O(n^2) performance. # # The goal of the optimal BST problem is to build a low-cost BST for a # given set of nodes, each with its own key and frequency. The frequency # of the node is defined as how many time the node is being searched. # The search cost of binary search tree is given by this formula: # # cost(1, n) = sum{i = 1 to n}((depth(node_i) + 1) * node_i_freq) # # where n is number of nodes in the BST. The characteristic of low-cost # BSTs is having a faster overall search time than other implementations. # The reason for their fast search time is that the nodes with high # frequencies will be placed near the root of the tree while the nodes # with low frequencies will be placed near the leaves of the tree thus # reducing search time in the most frequent instances. import sys from random import randint class Node: """Binary Search Tree Node""" def __init__(self, key, freq): self.key = key self.freq = freq def __str__(self): """ >>> str(Node(1, 2)) 'Node(key=1, freq=2)' """ return f"Node(key={self.key}, freq={self.freq})" def print_binary_search_tree(root, key, i, j, parent, is_left): """ Recursive function to print a BST from a root table. >>> key = [3, 8, 9, 10, 17, 21] >>> root = [[0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 3], [0, 0, 2, 3, 3, 3], \ [0, 0, 0, 3, 3, 3], [0, 0, 0, 0, 4, 5], [0, 0, 0, 0, 0, 5]] >>> print_binary_search_tree(root, key, 0, 5, -1, False) 8 is the root of the binary search tree. 3 is the left child of key 8. 10 is the right child of key 8. 9 is the left child of key 10. 21 is the right child of key 10. 17 is the left child of key 21. """ if i > j or i < 0 or j > len(root) - 1: return node = root[i][j] if parent == -1: # root does not have a parent print(f"{key[node]} is the root of the binary search tree.") elif is_left: print(f"{key[node]} is the left child of key {parent}.") else: print(f"{key[node]} is the right child of key {parent}.") print_binary_search_tree(root, key, i, node - 1, key[node], True) print_binary_search_tree(root, key, node + 1, j, key[node], False) def find_optimal_binary_search_tree(nodes): """ This function calculates and prints the optimal binary search tree. The dynamic programming algorithm below runs in O(n^2) time. Implemented from CLRS (Introduction to Algorithms) book. https://en.wikipedia.org/wiki/Introduction_to_Algorithms >>> find_optimal_binary_search_tree([Node(12, 8), Node(10, 34), Node(20, 50), \ Node(42, 3), Node(25, 40), Node(37, 30)]) Binary search tree nodes: Node(key=10, freq=34) Node(key=12, freq=8) Node(key=20, freq=50) Node(key=25, freq=40) Node(key=37, freq=30) Node(key=42, freq=3) <BLANKLINE> The cost of optimal BST for given tree nodes is 324. 20 is the root of the binary search tree. 10 is the left child of key 20. 12 is the right child of key 10. 25 is the right child of key 20. 37 is the right child of key 25. 42 is the right child of key 37. """ # Tree nodes must be sorted first, the code below sorts the keys in # increasing order and rearrange its frequencies accordingly. nodes.sort(key=lambda node: node.key) n = len(nodes) keys = [nodes[i].key for i in range(n)] freqs = [nodes[i].freq for i in range(n)] # This 2D array stores the overall tree cost (which's as minimized as possible); # for a single key, cost is equal to frequency of the key. dp = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # sum[i][j] stores the sum of key frequencies between i and j inclusive in nodes # array total = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] # stores tree roots that will be used later for constructing binary search tree root = [[i if i == j else 0 for j in range(n)] for i in range(n)] for interval_length in range(2, n + 1): for i in range(n - interval_length + 1): j = i + interval_length - 1 dp[i][j] = sys.maxsize # set the value to "infinity" total[i][j] = total[i][j - 1] + freqs[j] # Apply Knuth's optimization # Loop without optimization: for r in range(i, j + 1): for r in range(root[i][j - 1], root[i + 1][j] + 1): # r is a temporal root left = dp[i][r - 1] if r != i else 0 # optimal cost for left subtree right = dp[r + 1][j] if r != j else 0 # optimal cost for right subtree cost = left + total[i][j] + right if dp[i][j] > cost: dp[i][j] = cost root[i][j] = r print("Binary search tree nodes:") for node in nodes: print(node) print(f"\nThe cost of optimal BST for given tree nodes is {dp[0][n - 1]}.") print_binary_search_tree(root, keys, 0, n - 1, -1, False) def main(): # A sample binary search tree nodes = [Node(i, randint(1, 50)) for i in range(10, 0, -1)] find_optimal_binary_search_tree(nodes) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a pure Python implementation of the heap sort algorithm. For doctests run following command: python -m doctest -v heap_sort.py or python3 -m doctest -v heap_sort.py For manual testing run: python heap_sort.py """ def heapify(unsorted, index, heap_size): largest = index left_index = 2 * index + 1 right_index = 2 * index + 2 if left_index < heap_size and unsorted[left_index] > unsorted[largest]: largest = left_index if right_index < heap_size and unsorted[right_index] > unsorted[largest]: largest = right_index if largest != index: unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest] heapify(unsorted, largest, heap_size) def heap_sort(unsorted): """ Pure implementation of the heap sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> heap_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> heap_sort([]) [] >>> heap_sort([-2, -5, -45]) [-45, -5, -2] """ n = len(unsorted) for i in range(n // 2 - 1, -1, -1): heapify(unsorted, i, n) for i in range(n - 1, 0, -1): unsorted[0], unsorted[i] = unsorted[i], unsorted[0] heapify(unsorted, 0, i) return unsorted if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(heap_sort(unsorted))
""" This is a pure Python implementation of the heap sort algorithm. For doctests run following command: python -m doctest -v heap_sort.py or python3 -m doctest -v heap_sort.py For manual testing run: python heap_sort.py """ def heapify(unsorted, index, heap_size): largest = index left_index = 2 * index + 1 right_index = 2 * index + 2 if left_index < heap_size and unsorted[left_index] > unsorted[largest]: largest = left_index if right_index < heap_size and unsorted[right_index] > unsorted[largest]: largest = right_index if largest != index: unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest] heapify(unsorted, largest, heap_size) def heap_sort(unsorted): """ Pure implementation of the heap sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> heap_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> heap_sort([]) [] >>> heap_sort([-2, -5, -45]) [-45, -5, -2] """ n = len(unsorted) for i in range(n // 2 - 1, -1, -1): heapify(unsorted, i, n) for i in range(n - 1, 0, -1): unsorted[0], unsorted[i] = unsorted[i], unsorted[0] heapify(unsorted, 0, i) return unsorted if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(heap_sort(unsorted))
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Pure Python implementation of a binary search algorithm. For doctests run following command: python3 -m doctest -v simple_binary_search.py For manual testing run: python3 simple_binary_search.py """ from __future__ import annotations def binary_search(a_list: list[int], item: int) -> bool: """ >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> print(binary_search(test_list, 3)) False >>> print(binary_search(test_list, 13)) True >>> print(binary_search([4, 4, 5, 6, 7], 4)) True >>> print(binary_search([4, 4, 5, 6, 7], -10)) False >>> print(binary_search([-18, 2], -18)) True >>> print(binary_search([5], 5)) True >>> print(binary_search(['a', 'c', 'd'], 'c')) True >>> print(binary_search(['a', 'c', 'd'], 'f')) False >>> print(binary_search([], 1)) False >>> print(binary_search([-.1, .1 , .8], .1)) True >>> binary_search(range(-5000, 5000, 10), 80) True >>> binary_search(range(-5000, 5000, 10), 1255) False >>> binary_search(range(0, 10000, 5), 2) False """ if len(a_list) == 0: return False midpoint = len(a_list) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint], item) else: return binary_search(a_list[midpoint + 1 :], item) if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item.strip()) for item in user_input.split(",")] target = int(input("Enter the number to be found in the list:\n").strip()) not_str = "" if binary_search(sequence, target) else "not " print(f"{target} was {not_str}found in {sequence}")
""" Pure Python implementation of a binary search algorithm. For doctests run following command: python3 -m doctest -v simple_binary_search.py For manual testing run: python3 simple_binary_search.py """ from __future__ import annotations def binary_search(a_list: list[int], item: int) -> bool: """ >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> print(binary_search(test_list, 3)) False >>> print(binary_search(test_list, 13)) True >>> print(binary_search([4, 4, 5, 6, 7], 4)) True >>> print(binary_search([4, 4, 5, 6, 7], -10)) False >>> print(binary_search([-18, 2], -18)) True >>> print(binary_search([5], 5)) True >>> print(binary_search(['a', 'c', 'd'], 'c')) True >>> print(binary_search(['a', 'c', 'd'], 'f')) False >>> print(binary_search([], 1)) False >>> print(binary_search([-.1, .1 , .8], .1)) True >>> binary_search(range(-5000, 5000, 10), 80) True >>> binary_search(range(-5000, 5000, 10), 1255) False >>> binary_search(range(0, 10000, 5), 2) False """ if len(a_list) == 0: return False midpoint = len(a_list) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint], item) else: return binary_search(a_list[midpoint + 1 :], item) if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item.strip()) for item in user_input.split(",")] target = int(input("Enter the number to be found in the list:\n").strip()) not_str = "" if binary_search(sequence, target) else "not " print(f"{target} was {not_str}found in {sequence}")
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def reverse_letters(input_str: str) -> str: """ Reverses letters in a given string without adjusting the position of the words >>> reverse_letters('The cat in the hat') 'ehT tac ni eht tah' >>> reverse_letters('The quick brown fox jumped over the lazy dog.') 'ehT kciuq nworb xof depmuj revo eht yzal .god' >>> reverse_letters('Is this true?') 'sI siht ?eurt' >>> reverse_letters("I love Python") 'I evol nohtyP' """ return " ".join([word[::-1] for word in input_str.split()]) if __name__ == "__main__": import doctest doctest.testmod()
def reverse_letters(input_str: str) -> str: """ Reverses letters in a given string without adjusting the position of the words >>> reverse_letters('The cat in the hat') 'ehT tac ni eht tah' >>> reverse_letters('The quick brown fox jumped over the lazy dog.') 'ehT kciuq nworb xof depmuj revo eht yzal .god' >>> reverse_letters('Is this true?') 'sI siht ?eurt' >>> reverse_letters("I love Python") 'I evol nohtyP' """ return " ".join([word[::-1] for word in input_str.split()]) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def stooge_sort(arr): """ Examples: >>> stooge_sort([18.1, 0, -7.1, -1, 2, 2]) [-7.1, -1, 0, 2, 2, 18.1] >>> stooge_sort([]) [] """ stooge(arr, 0, len(arr) - 1) return arr def stooge(arr, i, h): if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: arr[i], arr[h] = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: t = (int)((h - i + 1) / 3) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) # Recursively sort last 2/3 elements stooge(arr, i + t, (h)) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(stooge_sort(unsorted))
def stooge_sort(arr): """ Examples: >>> stooge_sort([18.1, 0, -7.1, -1, 2, 2]) [-7.1, -1, 0, 2, 2, 18.1] >>> stooge_sort([]) [] """ stooge(arr, 0, len(arr) - 1) return arr def stooge(arr, i, h): if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: arr[i], arr[h] = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: t = (int)((h - i + 1) / 3) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) # Recursively sort last 2/3 elements stooge(arr, i + t, (h)) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(stooge_sort(unsorted))
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 206: https://projecteuler.net/problem=206 Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0, where each “_” is a single digit. ----- Instead of computing every single permutation of that number and going through a 10^9 search space, we can narrow it down considerably. If the square ends in a 0, then the square root must also end in a 0. Thus, the last missing digit must be 0 and the square root is a multiple of 10. We can narrow the search space down to the first 8 digits and multiply the result of that by 10 at the end. Now the last digit is a 9, which can only happen if the square root ends in a 3 or 7. From this point, we can try one of two different methods to find the answer: 1. Start at the lowest possible base number whose square would be in the format, and count up. The base we would start at is 101010103, whose square is the closest number to 10203040506070809. Alternate counting up by 4 and 6 so the last digit of the base is always a 3 or 7. 2. Start at the highest possible base number whose square would be in the format, and count down. That base would be 138902663, whose square is the closest number to 1929394959697989. Alternate counting down by 6 and 4 so the last digit of the base is always a 3 or 7. The solution does option 2 because the answer happens to be much closer to the starting point. """ def is_square_form(num: int) -> bool: """ Determines if num is in the form 1_2_3_4_5_6_7_8_9 >>> is_square_form(1) False >>> is_square_form(112233445566778899) True >>> is_square_form(123456789012345678) False """ digit = 9 while num > 0: if num % 10 != digit: return False num //= 100 digit -= 1 return True def solution() -> int: """ Returns the first integer whose square is of the form 1_2_3_4_5_6_7_8_9_0 """ num = 138902663 while not is_square_form(num * num): if num % 10 == 3: num -= 6 # (3 - 6) % 10 = 7 else: num -= 4 # (7 - 4) % 10 = 3 return num * 10 if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 206: https://projecteuler.net/problem=206 Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0, where each “_” is a single digit. ----- Instead of computing every single permutation of that number and going through a 10^9 search space, we can narrow it down considerably. If the square ends in a 0, then the square root must also end in a 0. Thus, the last missing digit must be 0 and the square root is a multiple of 10. We can narrow the search space down to the first 8 digits and multiply the result of that by 10 at the end. Now the last digit is a 9, which can only happen if the square root ends in a 3 or 7. From this point, we can try one of two different methods to find the answer: 1. Start at the lowest possible base number whose square would be in the format, and count up. The base we would start at is 101010103, whose square is the closest number to 10203040506070809. Alternate counting up by 4 and 6 so the last digit of the base is always a 3 or 7. 2. Start at the highest possible base number whose square would be in the format, and count down. That base would be 138902663, whose square is the closest number to 1929394959697989. Alternate counting down by 6 and 4 so the last digit of the base is always a 3 or 7. The solution does option 2 because the answer happens to be much closer to the starting point. """ def is_square_form(num: int) -> bool: """ Determines if num is in the form 1_2_3_4_5_6_7_8_9 >>> is_square_form(1) False >>> is_square_form(112233445566778899) True >>> is_square_form(123456789012345678) False """ digit = 9 while num > 0: if num % 10 != digit: return False num //= 100 digit -= 1 return True def solution() -> int: """ Returns the first integer whose square is of the form 1_2_3_4_5_6_7_8_9_0 """ num = 138902663 while not is_square_form(num * num): if num % 10 == 3: num -= 6 # (3 - 6) % 10 = 7 else: num -= 4 # (7 - 4) % 10 = 3 return num * 10 if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 13: https://projecteuler.net/problem=13 Problem Statement: Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. """ import os def solution(): """ Returns the first ten digits of the sum of the array elements from the file num.txt >>> solution() '5537376230' """ file_path = os.path.join(os.path.dirname(__file__), "num.txt") with open(file_path) as file_hand: return str(sum(int(line) for line in file_hand))[:10] if __name__ == "__main__": print(solution())
""" Problem 13: https://projecteuler.net/problem=13 Problem Statement: Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. """ import os def solution(): """ Returns the first ten digits of the sum of the array elements from the file num.txt >>> solution() '5537376230' """ file_path = os.path.join(os.path.dirname(__file__), "num.txt") with open(file_path) as file_hand: return str(sum(int(line) for line in file_hand))[:10] if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def decrypt(message: str) -> None: """ >>> decrypt('TMDETUX PMDVU') Decryption using Key #0: TMDETUX PMDVU Decryption using Key #1: SLCDSTW OLCUT Decryption using Key #2: RKBCRSV NKBTS Decryption using Key #3: QJABQRU MJASR Decryption using Key #4: PIZAPQT LIZRQ Decryption using Key #5: OHYZOPS KHYQP Decryption using Key #6: NGXYNOR JGXPO Decryption using Key #7: MFWXMNQ IFWON Decryption using Key #8: LEVWLMP HEVNM Decryption using Key #9: KDUVKLO GDUML Decryption using Key #10: JCTUJKN FCTLK Decryption using Key #11: IBSTIJM EBSKJ Decryption using Key #12: HARSHIL DARJI Decryption using Key #13: GZQRGHK CZQIH Decryption using Key #14: FYPQFGJ BYPHG Decryption using Key #15: EXOPEFI AXOGF Decryption using Key #16: DWNODEH ZWNFE Decryption using Key #17: CVMNCDG YVMED Decryption using Key #18: BULMBCF XULDC Decryption using Key #19: ATKLABE WTKCB Decryption using Key #20: ZSJKZAD VSJBA Decryption using Key #21: YRIJYZC URIAZ Decryption using Key #22: XQHIXYB TQHZY Decryption using Key #23: WPGHWXA SPGYX Decryption using Key #24: VOFGVWZ ROFXW Decryption using Key #25: UNEFUVY QNEWV """ LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # noqa: N806 for key in range(len(LETTERS)): translated = "" for symbol in message: if symbol in LETTERS: num = LETTERS.find(symbol) num = num - key if num < 0: num = num + len(LETTERS) translated = translated + LETTERS[num] else: translated = translated + symbol print(f"Decryption using Key #{key}: {translated}") def main() -> None: message = input("Encrypted message: ") message = message.upper() decrypt(message) if __name__ == "__main__": import doctest doctest.testmod() main()
def decrypt(message: str) -> None: """ >>> decrypt('TMDETUX PMDVU') Decryption using Key #0: TMDETUX PMDVU Decryption using Key #1: SLCDSTW OLCUT Decryption using Key #2: RKBCRSV NKBTS Decryption using Key #3: QJABQRU MJASR Decryption using Key #4: PIZAPQT LIZRQ Decryption using Key #5: OHYZOPS KHYQP Decryption using Key #6: NGXYNOR JGXPO Decryption using Key #7: MFWXMNQ IFWON Decryption using Key #8: LEVWLMP HEVNM Decryption using Key #9: KDUVKLO GDUML Decryption using Key #10: JCTUJKN FCTLK Decryption using Key #11: IBSTIJM EBSKJ Decryption using Key #12: HARSHIL DARJI Decryption using Key #13: GZQRGHK CZQIH Decryption using Key #14: FYPQFGJ BYPHG Decryption using Key #15: EXOPEFI AXOGF Decryption using Key #16: DWNODEH ZWNFE Decryption using Key #17: CVMNCDG YVMED Decryption using Key #18: BULMBCF XULDC Decryption using Key #19: ATKLABE WTKCB Decryption using Key #20: ZSJKZAD VSJBA Decryption using Key #21: YRIJYZC URIAZ Decryption using Key #22: XQHIXYB TQHZY Decryption using Key #23: WPGHWXA SPGYX Decryption using Key #24: VOFGVWZ ROFXW Decryption using Key #25: UNEFUVY QNEWV """ LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # noqa: N806 for key in range(len(LETTERS)): translated = "" for symbol in message: if symbol in LETTERS: num = LETTERS.find(symbol) num = num - key if num < 0: num = num + len(LETTERS) translated = translated + LETTERS[num] else: translated = translated + symbol print(f"Decryption using Key #{key}: {translated}") def main() -> None: message = input("Encrypted message: ") message = message.upper() decrypt(message) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of Bilateral filter Inputs: img: A 2d image with values in between 0 and 1 varS: variance in space dimension. varI: variance in Intensity. N: Kernel size(Must be an odd number) Output: img:A 2d zero padded image with values in between 0 and 1 """ import math import sys import cv2 import numpy as np def vec_gaussian(img: np.ndarray, variance: float) -> np.ndarray: # For applying gaussian function for each element in matrix. sigma = math.sqrt(variance) cons = 1 / (sigma * math.sqrt(2 * math.pi)) return cons * np.exp(-((img / sigma) ** 2) * 0.5) def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray: half = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray: # Creates a gaussian kernel of given dimension. arr = np.zeros((kernel_size, kernel_size)) for i in range(0, kernel_size): for j in range(0, kernel_size): arr[i, j] = math.sqrt( abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2 ) return vec_gaussian(arr, spatial_variance) def bilateral_filter( img: np.ndarray, spatial_variance: float, intensity_variance: float, kernel_size: int, ) -> np.ndarray: img2 = np.zeros(img.shape) gauss_ker = get_gauss_kernel(kernel_size, spatial_variance) size_x, size_y = img.shape for i in range(kernel_size // 2, size_x - kernel_size // 2): for j in range(kernel_size // 2, size_y - kernel_size // 2): img_s = get_slice(img, i, j, kernel_size) img_i = img_s - img_s[kernel_size // 2, kernel_size // 2] img_ig = vec_gaussian(img_i, intensity_variance) weights = np.multiply(gauss_ker, img_ig) vals = np.multiply(img_s, weights) val = np.sum(vals) / np.sum(weights) img2[i, j] = val return img2 def parse_args(args: list) -> tuple: filename = args[1] if args[1:] else "../image_data/lena.jpg" spatial_variance = float(args[2]) if args[2:] else 1.0 intensity_variance = float(args[3]) if args[3:] else 1.0 if args[4:]: kernel_size = int(args[4]) kernel_size = kernel_size + abs(kernel_size % 2 - 1) else: kernel_size = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": filename, spatial_variance, intensity_variance, kernel_size = parse_args(sys.argv) img = cv2.imread(filename, 0) cv2.imshow("input image", img) out = img / 255 out = out.astype("float32") out = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) out = out * 255 out = np.uint8(out) cv2.imshow("output image", out) cv2.waitKey(0) cv2.destroyAllWindows()
""" Implementation of Bilateral filter Inputs: img: A 2d image with values in between 0 and 1 varS: variance in space dimension. varI: variance in Intensity. N: Kernel size(Must be an odd number) Output: img:A 2d zero padded image with values in between 0 and 1 """ import math import sys import cv2 import numpy as np def vec_gaussian(img: np.ndarray, variance: float) -> np.ndarray: # For applying gaussian function for each element in matrix. sigma = math.sqrt(variance) cons = 1 / (sigma * math.sqrt(2 * math.pi)) return cons * np.exp(-((img / sigma) ** 2) * 0.5) def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray: half = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray: # Creates a gaussian kernel of given dimension. arr = np.zeros((kernel_size, kernel_size)) for i in range(0, kernel_size): for j in range(0, kernel_size): arr[i, j] = math.sqrt( abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2 ) return vec_gaussian(arr, spatial_variance) def bilateral_filter( img: np.ndarray, spatial_variance: float, intensity_variance: float, kernel_size: int, ) -> np.ndarray: img2 = np.zeros(img.shape) gauss_ker = get_gauss_kernel(kernel_size, spatial_variance) size_x, size_y = img.shape for i in range(kernel_size // 2, size_x - kernel_size // 2): for j in range(kernel_size // 2, size_y - kernel_size // 2): img_s = get_slice(img, i, j, kernel_size) img_i = img_s - img_s[kernel_size // 2, kernel_size // 2] img_ig = vec_gaussian(img_i, intensity_variance) weights = np.multiply(gauss_ker, img_ig) vals = np.multiply(img_s, weights) val = np.sum(vals) / np.sum(weights) img2[i, j] = val return img2 def parse_args(args: list) -> tuple: filename = args[1] if args[1:] else "../image_data/lena.jpg" spatial_variance = float(args[2]) if args[2:] else 1.0 intensity_variance = float(args[3]) if args[3:] else 1.0 if args[4:]: kernel_size = int(args[4]) kernel_size = kernel_size + abs(kernel_size % 2 - 1) else: kernel_size = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": filename, spatial_variance, intensity_variance, kernel_size = parse_args(sys.argv) img = cv2.imread(filename, 0) cv2.imshow("input image", img) out = img / 255 out = out.astype("float32") out = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) out = out * 255 out = np.uint8(out) cv2.imshow("output image", out) cv2.waitKey(0) cv2.destroyAllWindows()
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 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 True if n == n[::-1] else False 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 True if n == n[::-1] else False 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
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a pure Python implementation of the Harmonic Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics) For doctests run following command: python -m doctest -v harmonic_series.py or python3 -m doctest -v harmonic_series.py For manual testing run: python3 harmonic_series.py """ def harmonic_series(n_term: str) -> list: """Pure Python implementation of Harmonic Series algorithm :param n_term: The last (nth) term of Harmonic Series :return: The Harmonic Series starting from 1 to last (nth) term Examples: >>> harmonic_series(5) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(5.0) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(5.1) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(-5) [] >>> harmonic_series(0) [] >>> harmonic_series(1) ['1'] """ if n_term == "": return [] series: list = [] for temp in range(int(n_term)): series.append(f"1/{temp + 1}" if series else "1") return series if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
""" This is a pure Python implementation of the Harmonic Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics) For doctests run following command: python -m doctest -v harmonic_series.py or python3 -m doctest -v harmonic_series.py For manual testing run: python3 harmonic_series.py """ def harmonic_series(n_term: str) -> list: """Pure Python implementation of Harmonic Series algorithm :param n_term: The last (nth) term of Harmonic Series :return: The Harmonic Series starting from 1 to last (nth) term Examples: >>> harmonic_series(5) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(5.0) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(5.1) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(-5) [] >>> harmonic_series(0) [] >>> harmonic_series(1) ['1'] """ if n_term == "": return [] series: list = [] for temp in range(int(n_term)): series.append(f"1/{temp + 1}" if series else "1") return series if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import requests from bs4 import BeautifulSoup def stock_price(symbol: str = "AAPL") -> str: url = f"https://in.finance.yahoo.com/quote/{symbol}?s={symbol}" soup = BeautifulSoup(requests.get(url).text, "html.parser") class_ = "My(6px) Pos(r) smartphone_Mt(6px)" return soup.find("div", class_=class_).find("span").text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(f"Current {symbol:<4} stock price is {stock_price(symbol):>8}")
import requests from bs4 import BeautifulSoup def stock_price(symbol: str = "AAPL") -> str: url = f"https://in.finance.yahoo.com/quote/{symbol}?s={symbol}" soup = BeautifulSoup(requests.get(url).text, "html.parser") class_ = "My(6px) Pos(r) smartphone_Mt(6px)" return soup.find("div", class_=class_).find("span").text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(f"Current {symbol:<4} stock price is {stock_price(symbol):>8}")
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Horizontal Projectile Motion problem in physics. This algorithm solves a specific problem in which the motion starts from the ground as can be seen below: (v = 0) ** * * * * * * * * * * GROUND GROUND For more info: https://en.wikipedia.org/wiki/Projectile_motion """ # Importing packages from math import radians as angle_to_radians from math import sin # Acceleration Constant on Earth (unit m/s^2) g = 9.80665 def check_args(init_velocity: float, angle: float) -> None: """ Check that the arguments are valid """ # Ensure valid instance if not isinstance(init_velocity, (int, float)): raise TypeError("Invalid velocity. Should be a positive number.") if not isinstance(angle, (int, float)): raise TypeError("Invalid angle. Range is 1-90 degrees.") # Ensure valid angle if angle > 90 or angle < 1: raise ValueError("Invalid angle. Range is 1-90 degrees.") # Ensure valid velocity if init_velocity < 0: raise ValueError("Invalid velocity. Should be a positive number.") def horizontal_distance(init_velocity: float, angle: float) -> float: """ Returns the horizontal distance that the object cover Formula: v_0^2 * sin(2 * alpha) --------------------- g v_0 - initial velocity alpha - angle >>> horizontal_distance(30, 45) 91.77 >>> horizontal_distance(100, 78) 414.76 >>> horizontal_distance(-1, 20) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, -20) Traceback (most recent call last): ... ValueError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(2 * angle) return round(init_velocity**2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: """ Returns the maximum height that the object reach Formula: v_0^2 * sin^2(alpha) -------------------- 2g v_0 - initial velocity alpha - angle >>> max_height(30, 45) 22.94 >>> max_height(100, 78) 487.82 >>> max_height("a", 20) Traceback (most recent call last): ... TypeError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: """ Returns total time of the motion Formula: 2 * v_0 * sin(alpha) -------------------- g v_0 - initial velocity alpha - angle >>> total_time(30, 45) 4.33 >>> total_time(100, 78) 19.95 >>> total_time(-10, 40) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> total_time(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(2 * init_velocity * sin(radians) / g, 2) def test_motion() -> None: """ >>> test_motion() """ v0, angle = 25, 20 assert horizontal_distance(v0, angle) == 40.97 assert max_height(v0, angle) == 3.73 assert total_time(v0, angle) == 1.74 if __name__ == "__main__": from doctest import testmod testmod() # Get input from user init_vel = float(input("Initial Velocity: ").strip()) # Get input from user angle = float(input("angle: ").strip()) # Print results print() print("Results: ") print(f"Horizontal Distance: {str(horizontal_distance(init_vel, angle))} [m]") print(f"Maximum Height: {str(max_height(init_vel, angle))} [m]") print(f"Total Time: {str(total_time(init_vel, angle))} [s]")
""" Horizontal Projectile Motion problem in physics. This algorithm solves a specific problem in which the motion starts from the ground as can be seen below: (v = 0) ** * * * * * * * * * * GROUND GROUND For more info: https://en.wikipedia.org/wiki/Projectile_motion """ # Importing packages from math import radians as angle_to_radians from math import sin # Acceleration Constant on Earth (unit m/s^2) g = 9.80665 def check_args(init_velocity: float, angle: float) -> None: """ Check that the arguments are valid """ # Ensure valid instance if not isinstance(init_velocity, (int, float)): raise TypeError("Invalid velocity. Should be a positive number.") if not isinstance(angle, (int, float)): raise TypeError("Invalid angle. Range is 1-90 degrees.") # Ensure valid angle if angle > 90 or angle < 1: raise ValueError("Invalid angle. Range is 1-90 degrees.") # Ensure valid velocity if init_velocity < 0: raise ValueError("Invalid velocity. Should be a positive number.") def horizontal_distance(init_velocity: float, angle: float) -> float: """ Returns the horizontal distance that the object cover Formula: v_0^2 * sin(2 * alpha) --------------------- g v_0 - initial velocity alpha - angle >>> horizontal_distance(30, 45) 91.77 >>> horizontal_distance(100, 78) 414.76 >>> horizontal_distance(-1, 20) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, -20) Traceback (most recent call last): ... ValueError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(2 * angle) return round(init_velocity**2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: """ Returns the maximum height that the object reach Formula: v_0^2 * sin^2(alpha) -------------------- 2g v_0 - initial velocity alpha - angle >>> max_height(30, 45) 22.94 >>> max_height(100, 78) 487.82 >>> max_height("a", 20) Traceback (most recent call last): ... TypeError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: """ Returns total time of the motion Formula: 2 * v_0 * sin(alpha) -------------------- g v_0 - initial velocity alpha - angle >>> total_time(30, 45) 4.33 >>> total_time(100, 78) 19.95 >>> total_time(-10, 40) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> total_time(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(2 * init_velocity * sin(radians) / g, 2) def test_motion() -> None: """ >>> test_motion() """ v0, angle = 25, 20 assert horizontal_distance(v0, angle) == 40.97 assert max_height(v0, angle) == 3.73 assert total_time(v0, angle) == 1.74 if __name__ == "__main__": from doctest import testmod testmod() # Get input from user init_vel = float(input("Initial Velocity: ").strip()) # Get input from user angle = float(input("angle: ").strip()) # Print results print() print("Results: ") print(f"Horizontal Distance: {str(horizontal_distance(init_vel, angle))} [m]") print(f"Maximum Height: {str(max_height(init_vel, angle))} [m]") print(f"Total Time: {str(total_time(init_vel, angle))} [s]")
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import base64 def base16_encode(inp: str) -> bytes: """ Encodes a given utf-8 string into base-16. >>> base16_encode('Hello World!') b'48656C6C6F20576F726C6421' >>> base16_encode('HELLO WORLD!') b'48454C4C4F20574F524C4421' >>> base16_encode('') b'' """ # encode the input into a bytes-like object and then encode b16encode that return base64.b16encode(inp.encode("utf-8")) def base16_decode(b16encoded: bytes) -> str: """ Decodes from base-16 to a utf-8 string. >>> base16_decode(b'48656C6C6F20576F726C6421') 'Hello World!' >>> base16_decode(b'48454C4C4F20574F524C4421') 'HELLO WORLD!' >>> base16_decode(b'') '' """ # b16decode the input into bytes and decode that into a human readable string return base64.b16decode(b16encoded).decode("utf-8") if __name__ == "__main__": import doctest doctest.testmod()
import base64 def base16_encode(inp: str) -> bytes: """ Encodes a given utf-8 string into base-16. >>> base16_encode('Hello World!') b'48656C6C6F20576F726C6421' >>> base16_encode('HELLO WORLD!') b'48454C4C4F20574F524C4421' >>> base16_encode('') b'' """ # encode the input into a bytes-like object and then encode b16encode that return base64.b16encode(inp.encode("utf-8")) def base16_decode(b16encoded: bytes) -> str: """ Decodes from base-16 to a utf-8 string. >>> base16_decode(b'48656C6C6F20576F726C6421') 'Hello World!' >>> base16_decode(b'48454C4C4F20574F524C4421') 'HELLO WORLD!' >>> base16_decode(b'') '' """ # b16decode the input into bytes and decode that into a human readable string return base64.b16decode(b16encoded).decode("utf-8") if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 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
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Counting Summations Problem 76: https://projecteuler.net/problem=76 It is possible to write five as a sum in exactly six different ways: 4 + 1 3 + 2 3 + 1 + 1 2 + 2 + 1 2 + 1 + 1 + 1 1 + 1 + 1 + 1 + 1 How many different ways can one hundred be written as a sum of at least two positive integers? """ def solution(m: int = 100) -> int: """ Returns the number of different ways the number m can be written as a sum of at least two positive integers. >>> solution(100) 190569291 >>> solution(50) 204225 >>> solution(30) 5603 >>> solution(10) 41 >>> solution(5) 6 >>> solution(3) 2 >>> solution(2) 1 >>> solution(1) 0 """ memo = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 for n in range(m + 1): for k in range(1, m): memo[n][k] += memo[n][k - 1] if n > k: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] - 1 if __name__ == "__main__": print(solution(int(input("Enter a number: ").strip())))
""" Counting Summations Problem 76: https://projecteuler.net/problem=76 It is possible to write five as a sum in exactly six different ways: 4 + 1 3 + 2 3 + 1 + 1 2 + 2 + 1 2 + 1 + 1 + 1 1 + 1 + 1 + 1 + 1 How many different ways can one hundred be written as a sum of at least two positive integers? """ def solution(m: int = 100) -> int: """ Returns the number of different ways the number m can be written as a sum of at least two positive integers. >>> solution(100) 190569291 >>> solution(50) 204225 >>> solution(30) 5603 >>> solution(10) 41 >>> solution(5) 6 >>> solution(3) 2 >>> solution(2) 1 >>> solution(1) 0 """ memo = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 for n in range(m + 1): for k in range(1, m): memo[n][k] += memo[n][k - 1] if n > k: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] - 1 if __name__ == "__main__": print(solution(int(input("Enter a number: ").strip())))
-1
TheAlgorithms/Python
7,235
Add Flake8 comprehensions to pre-commit
### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-15T14:17:49Z"
"2022-10-15T17:29:42Z"
98a4c2487814cdfe0822526e05c4e63ff6aef7d0
a652905b605ddcc43626072366d1130315801dc9
Add Flake8 comprehensions to pre-commit. ### Describe your change: Implements (#7233) * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from .stack import Stack def balanced_parentheses(parentheses: str) -> bool: """Use a stack to check if a string of parentheses is balanced. >>> balanced_parentheses("([]{})") True >>> balanced_parentheses("[()]{}{[()()]()}") True >>> balanced_parentheses("[(])") False >>> balanced_parentheses("1+2*3-4") True >>> balanced_parentheses("") True """ stack: Stack[str] = Stack() bracket_pairs = {"(": ")", "[": "]", "{": "}"} for bracket in parentheses: if bracket in bracket_pairs: stack.push(bracket) elif bracket in (")", "]", "}"): if stack.is_empty() or bracket_pairs[stack.pop()] != bracket: return False return stack.is_empty() if __name__ == "__main__": from doctest import testmod testmod() examples = ["((()))", "((())", "(()))"] print("Balanced parentheses demonstration:\n") for example in examples: not_str = "" if balanced_parentheses(example) else "not " print(f"{example} is {not_str}balanced")
from .stack import Stack def balanced_parentheses(parentheses: str) -> bool: """Use a stack to check if a string of parentheses is balanced. >>> balanced_parentheses("([]{})") True >>> balanced_parentheses("[()]{}{[()()]()}") True >>> balanced_parentheses("[(])") False >>> balanced_parentheses("1+2*3-4") True >>> balanced_parentheses("") True """ stack: Stack[str] = Stack() bracket_pairs = {"(": ")", "[": "]", "{": "}"} for bracket in parentheses: if bracket in bracket_pairs: stack.push(bracket) elif bracket in (")", "]", "}"): if stack.is_empty() or bracket_pairs[stack.pop()] != bracket: return False return stack.is_empty() if __name__ == "__main__": from doctest import testmod testmod() examples = ["((()))", "((())", "(()))"] print("Balanced parentheses demonstration:\n") for example in examples: not_str = "" if balanced_parentheses(example) else "not " print(f"{example} is {not_str}balanced")
-1