repo_name
stringclasses
1 value
pr_number
int64
4.12k
11.2k
pr_title
stringlengths
9
107
pr_description
stringlengths
107
5.48k
author
stringlengths
4
18
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
118
5.52k
before_content
stringlengths
0
7.93M
after_content
stringlengths
0
7.93M
label
int64
-1
1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 dfs(u): global graph, reversed_graph, scc, component, visit, stack if visit[u]: return visit[u] = True for v in graph[u]: dfs(v) stack.append(u) def dfs2(u): global graph, reversed_graph, scc, component, visit, stack if visit[u]: return visit[u] = True component.append(u) for v in reversed_graph[u]: dfs2(v) def kosaraju(): global graph, reversed_graph, scc, component, visit, stack for i in range(n): dfs(i) visit = [False] * n for i in stack[::-1]: if visit[i]: continue component = [] dfs2(i) scc.append(component) return scc if __name__ == "__main__": # n - no of nodes, m - no of edges n, m = list(map(int, input().strip().split())) graph: list[list[int]] = [[] for _ in range(n)] # graph reversed_graph: list[list[int]] = [[] for i in range(n)] # reversed graph # input graph data (edges) for _ in range(m): u, v = list(map(int, input().strip().split())) graph[u].append(v) reversed_graph[v].append(u) stack: list[int] = [] visit: list[bool] = [False] * n scc: list[int] = [] component: list[int] = [] print(kosaraju())
from __future__ import annotations def dfs(u): global graph, reversed_graph, scc, component, visit, stack if visit[u]: return visit[u] = True for v in graph[u]: dfs(v) stack.append(u) def dfs2(u): global graph, reversed_graph, scc, component, visit, stack if visit[u]: return visit[u] = True component.append(u) for v in reversed_graph[u]: dfs2(v) def kosaraju(): global graph, reversed_graph, scc, component, visit, stack for i in range(n): dfs(i) visit = [False] * n for i in stack[::-1]: if visit[i]: continue component = [] dfs2(i) scc.append(component) return scc if __name__ == "__main__": # n - no of nodes, m - no of edges n, m = list(map(int, input().strip().split())) graph: list[list[int]] = [[] for _ in range(n)] # graph reversed_graph: list[list[int]] = [[] for i in range(n)] # reversed graph # input graph data (edges) for _ in range(m): u, v = list(map(int, input().strip().split())) graph[u].append(v) reversed_graph[v].append(u) stack: list[int] = [] visit: list[bool] = [False] * n scc: list[int] = [] component: list[int] = [] print(kosaraju())
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 203: https://projecteuler.net/problem=203 The binomial coefficients (n k) can be arranged in triangular form, Pascal's triangle, like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 ......... It can be seen that the first eight rows of Pascal's triangle contain twelve distinct numbers: 1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 21 and 35. A positive integer n is called squarefree if no square of a prime divides n. Of the twelve distinct numbers in the first eight rows of Pascal's triangle, all except 4 and 20 are squarefree. The sum of the distinct squarefree numbers in the first eight rows is 105. Find the sum of the distinct squarefree numbers in the first 51 rows of Pascal's triangle. References: - https://en.wikipedia.org/wiki/Pascal%27s_triangle """ from __future__ import annotations def get_pascal_triangle_unique_coefficients(depth: int) -> set[int]: """ Returns the unique coefficients of a Pascal's triangle of depth "depth". The coefficients of this triangle are symmetric. A further improvement to this method could be to calculate the coefficients once per level. Nonetheless, the current implementation is fast enough for the original problem. >>> get_pascal_triangle_unique_coefficients(1) {1} >>> get_pascal_triangle_unique_coefficients(2) {1} >>> get_pascal_triangle_unique_coefficients(3) {1, 2} >>> get_pascal_triangle_unique_coefficients(8) {1, 2, 3, 4, 5, 6, 7, 35, 10, 15, 20, 21} """ coefficients = {1} previous_coefficients = [1] for _ in range(2, depth + 1): coefficients_begins_one = previous_coefficients + [0] coefficients_ends_one = [0] + previous_coefficients previous_coefficients = [] for x, y in zip(coefficients_begins_one, coefficients_ends_one): coefficients.add(x + y) previous_coefficients.append(x + y) return coefficients def get_squarefrees(unique_coefficients: set[int]) -> set[int]: """ Calculates the squarefree numbers inside unique_coefficients. Based on the definition of a non-squarefree number, then any non-squarefree n can be decomposed as n = p*p*r, where p is positive prime number and r is a positive integer. Under the previous formula, any coefficient that is lower than p*p is squarefree as r cannot be negative. On the contrary, if any r exists such that n = p*p*r, then the number is non-squarefree. >>> get_squarefrees({1}) {1} >>> get_squarefrees({1, 2}) {1, 2} >>> get_squarefrees({1, 2, 3, 4, 5, 6, 7, 35, 10, 15, 20, 21}) {1, 2, 3, 5, 6, 7, 35, 10, 15, 21} """ non_squarefrees = set() for number in unique_coefficients: divisor = 2 copy_number = number while divisor**2 <= copy_number: multiplicity = 0 while copy_number % divisor == 0: copy_number //= divisor multiplicity += 1 if multiplicity >= 2: non_squarefrees.add(number) break divisor += 1 return unique_coefficients.difference(non_squarefrees) def solution(n: int = 51) -> int: """ Returns the sum of squarefrees for a given Pascal's Triangle of depth n. >>> solution(1) 1 >>> solution(8) 105 >>> solution(9) 175 """ unique_coefficients = get_pascal_triangle_unique_coefficients(n) squarefrees = get_squarefrees(unique_coefficients) return sum(squarefrees) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 203: https://projecteuler.net/problem=203 The binomial coefficients (n k) can be arranged in triangular form, Pascal's triangle, like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 ......... It can be seen that the first eight rows of Pascal's triangle contain twelve distinct numbers: 1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 21 and 35. A positive integer n is called squarefree if no square of a prime divides n. Of the twelve distinct numbers in the first eight rows of Pascal's triangle, all except 4 and 20 are squarefree. The sum of the distinct squarefree numbers in the first eight rows is 105. Find the sum of the distinct squarefree numbers in the first 51 rows of Pascal's triangle. References: - https://en.wikipedia.org/wiki/Pascal%27s_triangle """ from __future__ import annotations def get_pascal_triangle_unique_coefficients(depth: int) -> set[int]: """ Returns the unique coefficients of a Pascal's triangle of depth "depth". The coefficients of this triangle are symmetric. A further improvement to this method could be to calculate the coefficients once per level. Nonetheless, the current implementation is fast enough for the original problem. >>> get_pascal_triangle_unique_coefficients(1) {1} >>> get_pascal_triangle_unique_coefficients(2) {1} >>> get_pascal_triangle_unique_coefficients(3) {1, 2} >>> get_pascal_triangle_unique_coefficients(8) {1, 2, 3, 4, 5, 6, 7, 35, 10, 15, 20, 21} """ coefficients = {1} previous_coefficients = [1] for _ in range(2, depth + 1): coefficients_begins_one = previous_coefficients + [0] coefficients_ends_one = [0] + previous_coefficients previous_coefficients = [] for x, y in zip(coefficients_begins_one, coefficients_ends_one): coefficients.add(x + y) previous_coefficients.append(x + y) return coefficients def get_squarefrees(unique_coefficients: set[int]) -> set[int]: """ Calculates the squarefree numbers inside unique_coefficients. Based on the definition of a non-squarefree number, then any non-squarefree n can be decomposed as n = p*p*r, where p is positive prime number and r is a positive integer. Under the previous formula, any coefficient that is lower than p*p is squarefree as r cannot be negative. On the contrary, if any r exists such that n = p*p*r, then the number is non-squarefree. >>> get_squarefrees({1}) {1} >>> get_squarefrees({1, 2}) {1, 2} >>> get_squarefrees({1, 2, 3, 4, 5, 6, 7, 35, 10, 15, 20, 21}) {1, 2, 3, 5, 6, 7, 35, 10, 15, 21} """ non_squarefrees = set() for number in unique_coefficients: divisor = 2 copy_number = number while divisor**2 <= copy_number: multiplicity = 0 while copy_number % divisor == 0: copy_number //= divisor multiplicity += 1 if multiplicity >= 2: non_squarefrees.add(number) break divisor += 1 return unique_coefficients.difference(non_squarefrees) def solution(n: int = 51) -> int: """ Returns the sum of squarefrees for a given Pascal's Triangle of depth n. >>> solution(1) 1 >>> solution(8) 105 >>> solution(9) 175 """ unique_coefficients = get_pascal_triangle_unique_coefficients(n) squarefrees = get_squarefrees(unique_coefficients) return sum(squarefrees) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 perfect_cube(n: int) -> bool: """ Check if a number is a perfect cube or not. >>> perfect_cube(27) True >>> perfect_cube(4) False """ val = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
def perfect_cube(n: int) -> bool: """ Check if a number is a perfect cube or not. >>> perfect_cube(27) True >>> perfect_cube(4) False """ val = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 3: https://projecteuler.net/problem=3 Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? References: - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization """ def solution(n: int = 600851475143) -> int: """ Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") prime = 1 i = 2 while i * i <= n: while n % i == 0: prime = i n //= i i += 1 if n > 1: prime = n return int(prime) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 3: https://projecteuler.net/problem=3 Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? References: - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization """ def solution(n: int = 600851475143) -> int: """ Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") prime = 1 i = 2 while i * i <= n: while n % i == 0: prime = i n //= i i += 1 if n > 1: prime = n return int(prime) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 from __future__ import annotations from collections.abc import Iterable, Iterator from typing import Any, Generic, TypeVar T = TypeVar("T", bound=bool) class SkewNode(Generic[T]): """ One node of the skew heap. Contains the value and references to two children. """ def __init__(self, value: T) -> None: self._value: T = value self.left: SkewNode[T] | None = None self.right: SkewNode[T] | None = None @property def value(self) -> T: """Return the value of the node.""" return self._value @staticmethod def merge( root1: SkewNode[T] | None, root2: SkewNode[T] | None ) -> SkewNode[T] | None: """Merge 2 nodes together.""" if not root1: return root2 if not root2: return root1 if root1.value > root2.value: root1, root2 = root2, root1 result = root1 temp = root1.right result.right = root1.left result.left = SkewNode.merge(temp, root2) return result class SkewHeap(Generic[T]): """ A data structure that allows inserting a new value and to pop the smallest values. Both operations take O(logN) time where N is the size of the structure. Wiki: https://en.wikipedia.org/wiki/Skew_heap Visualization: https://www.cs.usfca.edu/~galles/visualization/SkewHeap.html >>> list(SkewHeap([2, 3, 1, 5, 1, 7])) [1, 1, 2, 3, 5, 7] >>> sh = SkewHeap() >>> sh.pop() Traceback (most recent call last): ... IndexError: Can't get top element for the empty heap. >>> sh.insert(1) >>> sh.insert(-1) >>> sh.insert(0) >>> list(sh) [-1, 0, 1] """ def __init__(self, data: Iterable[T] | None = ()) -> None: """ >>> sh = SkewHeap([3, 1, 3, 7]) >>> list(sh) [1, 3, 3, 7] """ self._root: SkewNode[T] | None = None if data: for item in data: self.insert(item) def __bool__(self) -> bool: """ Check if the heap is not empty. >>> sh = SkewHeap() >>> bool(sh) False >>> sh.insert(1) >>> bool(sh) True >>> sh.clear() >>> bool(sh) False """ return self._root is not None def __iter__(self) -> Iterator[T]: """ Returns sorted list containing all the values in the heap. >>> sh = SkewHeap([3, 1, 3, 7]) >>> list(sh) [1, 3, 3, 7] """ result: list[Any] = [] while self: result.append(self.pop()) # Pushing items back to the heap not to clear it. for item in result: self.insert(item) return iter(result) def insert(self, value: T) -> None: """ Insert the value into the heap. >>> sh = SkewHeap() >>> sh.insert(3) >>> sh.insert(1) >>> sh.insert(3) >>> sh.insert(7) >>> list(sh) [1, 3, 3, 7] """ self._root = SkewNode.merge(self._root, SkewNode(value)) def pop(self) -> T | None: """ Pop the smallest value from the heap and return it. >>> sh = SkewHeap([3, 1, 3, 7]) >>> sh.pop() 1 >>> sh.pop() 3 >>> sh.pop() 3 >>> sh.pop() 7 >>> sh.pop() Traceback (most recent call last): ... IndexError: Can't get top element for the empty heap. """ result = self.top() self._root = ( SkewNode.merge(self._root.left, self._root.right) if self._root else None ) return result def top(self) -> T: """ Return the smallest value from the heap. >>> sh = SkewHeap() >>> sh.insert(3) >>> sh.top() 3 >>> sh.insert(1) >>> sh.top() 1 >>> sh.insert(3) >>> sh.top() 1 >>> sh.insert(7) >>> sh.top() 1 """ if not self._root: raise IndexError("Can't get top element for the empty heap.") return self._root.value def clear(self) -> None: """ Clear the heap. >>> sh = SkewHeap([3, 1, 3, 7]) >>> sh.clear() >>> sh.pop() Traceback (most recent call last): ... IndexError: Can't get top element for the empty heap. """ self._root = None if __name__ == "__main__": import doctest doctest.testmod()
#!/usr/bin/env python3 from __future__ import annotations from collections.abc import Iterable, Iterator from typing import Any, Generic, TypeVar T = TypeVar("T", bound=bool) class SkewNode(Generic[T]): """ One node of the skew heap. Contains the value and references to two children. """ def __init__(self, value: T) -> None: self._value: T = value self.left: SkewNode[T] | None = None self.right: SkewNode[T] | None = None @property def value(self) -> T: """Return the value of the node.""" return self._value @staticmethod def merge( root1: SkewNode[T] | None, root2: SkewNode[T] | None ) -> SkewNode[T] | None: """Merge 2 nodes together.""" if not root1: return root2 if not root2: return root1 if root1.value > root2.value: root1, root2 = root2, root1 result = root1 temp = root1.right result.right = root1.left result.left = SkewNode.merge(temp, root2) return result class SkewHeap(Generic[T]): """ A data structure that allows inserting a new value and to pop the smallest values. Both operations take O(logN) time where N is the size of the structure. Wiki: https://en.wikipedia.org/wiki/Skew_heap Visualization: https://www.cs.usfca.edu/~galles/visualization/SkewHeap.html >>> list(SkewHeap([2, 3, 1, 5, 1, 7])) [1, 1, 2, 3, 5, 7] >>> sh = SkewHeap() >>> sh.pop() Traceback (most recent call last): ... IndexError: Can't get top element for the empty heap. >>> sh.insert(1) >>> sh.insert(-1) >>> sh.insert(0) >>> list(sh) [-1, 0, 1] """ def __init__(self, data: Iterable[T] | None = ()) -> None: """ >>> sh = SkewHeap([3, 1, 3, 7]) >>> list(sh) [1, 3, 3, 7] """ self._root: SkewNode[T] | None = None if data: for item in data: self.insert(item) def __bool__(self) -> bool: """ Check if the heap is not empty. >>> sh = SkewHeap() >>> bool(sh) False >>> sh.insert(1) >>> bool(sh) True >>> sh.clear() >>> bool(sh) False """ return self._root is not None def __iter__(self) -> Iterator[T]: """ Returns sorted list containing all the values in the heap. >>> sh = SkewHeap([3, 1, 3, 7]) >>> list(sh) [1, 3, 3, 7] """ result: list[Any] = [] while self: result.append(self.pop()) # Pushing items back to the heap not to clear it. for item in result: self.insert(item) return iter(result) def insert(self, value: T) -> None: """ Insert the value into the heap. >>> sh = SkewHeap() >>> sh.insert(3) >>> sh.insert(1) >>> sh.insert(3) >>> sh.insert(7) >>> list(sh) [1, 3, 3, 7] """ self._root = SkewNode.merge(self._root, SkewNode(value)) def pop(self) -> T | None: """ Pop the smallest value from the heap and return it. >>> sh = SkewHeap([3, 1, 3, 7]) >>> sh.pop() 1 >>> sh.pop() 3 >>> sh.pop() 3 >>> sh.pop() 7 >>> sh.pop() Traceback (most recent call last): ... IndexError: Can't get top element for the empty heap. """ result = self.top() self._root = ( SkewNode.merge(self._root.left, self._root.right) if self._root else None ) return result def top(self) -> T: """ Return the smallest value from the heap. >>> sh = SkewHeap() >>> sh.insert(3) >>> sh.top() 3 >>> sh.insert(1) >>> sh.top() 1 >>> sh.insert(3) >>> sh.top() 1 >>> sh.insert(7) >>> sh.top() 1 """ if not self._root: raise IndexError("Can't get top element for the empty heap.") return self._root.value def clear(self) -> None: """ Clear the heap. >>> sh = SkewHeap([3, 1, 3, 7]) >>> sh.clear() >>> sh.pop() Traceback (most recent call last): ... IndexError: Can't get top element for the empty heap. """ self._root = None if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# To get an insight into Greedy Algorithm through the Knapsack problem """ A shopkeeper has bags of wheat that each have different weights and different profits. eg. profit 5 8 7 1 12 3 4 weight 2 7 1 6 4 2 5 max_weight 100 Constraints: max_weight > 0 profit[i] >= 0 weight[i] >= 0 Calculate the maximum profit that the shopkeeper can make given maxmum weight that can be carried. """ def calc_profit(profit: list, weight: list, max_weight: int) -> int: """ Function description is as follows- :param profit: Take a list of profits :param weight: Take a list of weight if bags corresponding to the profits :param max_weight: Maximum weight that could be carried :return: Maximum expected gain >>> calc_profit([1, 2, 3], [3, 4, 5], 15) 6 >>> calc_profit([10, 9 , 8], [3 ,4 , 5], 25) 27 """ if len(profit) != len(weight): raise ValueError("The length of profit and weight must be same.") if max_weight <= 0: raise ValueError("max_weight must greater than zero.") if any(p < 0 for p in profit): raise ValueError("Profit can not be negative.") if any(w < 0 for w in weight): raise ValueError("Weight can not be negative.") # List created to store profit gained for the 1kg in case of each weight # respectively. Calculate and append profit/weight for each element. profit_by_weight = [p / w for p, w in zip(profit, weight)] # Creating a copy of the list and sorting profit/weight in ascending order sorted_profit_by_weight = sorted(profit_by_weight) # declaring useful variables length = len(sorted_profit_by_weight) limit = 0 gain = 0 i = 0 # loop till the total weight do not reach max limit e.g. 15 kg and till i<length while limit <= max_weight and i < length: # flag value for encountered greatest element in sorted_profit_by_weight biggest_profit_by_weight = sorted_profit_by_weight[length - i - 1] """ Calculate the index of the biggest_profit_by_weight in profit_by_weight list. This will give the index of the first encountered element which is same as of biggest_profit_by_weight. There may be one or more values same as that of biggest_profit_by_weight but index always encounter the very first element only. To curb this alter the values in profit_by_weight once they are used here it is done to -1 because neither profit nor weight can be in negative. """ index = profit_by_weight.index(biggest_profit_by_weight) profit_by_weight[index] = -1 # check if the weight encountered is less than the total weight # encountered before. if max_weight - limit >= weight[index]: limit += weight[index] # Adding profit gained for the given weight 1 === # weight[index]/weight[index] gain += 1 * profit[index] else: # Since the weight encountered is greater than limit, therefore take the # required number of remaining kgs and calculate profit for it. # weight remaining / weight[index] gain += (max_weight - limit) / weight[index] * profit[index] break i += 1 return gain if __name__ == "__main__": print( "Input profits, weights, and then max_weight (all positive ints) separated by " "spaces." ) profit = [int(x) for x in input("Input profits separated by spaces: ").split()] weight = [int(x) for x in input("Input weights separated by spaces: ").split()] max_weight = int(input("Max weight allowed: ")) # Function Call calc_profit(profit, weight, max_weight)
# To get an insight into Greedy Algorithm through the Knapsack problem """ A shopkeeper has bags of wheat that each have different weights and different profits. eg. profit 5 8 7 1 12 3 4 weight 2 7 1 6 4 2 5 max_weight 100 Constraints: max_weight > 0 profit[i] >= 0 weight[i] >= 0 Calculate the maximum profit that the shopkeeper can make given maxmum weight that can be carried. """ def calc_profit(profit: list, weight: list, max_weight: int) -> int: """ Function description is as follows- :param profit: Take a list of profits :param weight: Take a list of weight if bags corresponding to the profits :param max_weight: Maximum weight that could be carried :return: Maximum expected gain >>> calc_profit([1, 2, 3], [3, 4, 5], 15) 6 >>> calc_profit([10, 9 , 8], [3 ,4 , 5], 25) 27 """ if len(profit) != len(weight): raise ValueError("The length of profit and weight must be same.") if max_weight <= 0: raise ValueError("max_weight must greater than zero.") if any(p < 0 for p in profit): raise ValueError("Profit can not be negative.") if any(w < 0 for w in weight): raise ValueError("Weight can not be negative.") # List created to store profit gained for the 1kg in case of each weight # respectively. Calculate and append profit/weight for each element. profit_by_weight = [p / w for p, w in zip(profit, weight)] # Creating a copy of the list and sorting profit/weight in ascending order sorted_profit_by_weight = sorted(profit_by_weight) # declaring useful variables length = len(sorted_profit_by_weight) limit = 0 gain = 0 i = 0 # loop till the total weight do not reach max limit e.g. 15 kg and till i<length while limit <= max_weight and i < length: # flag value for encountered greatest element in sorted_profit_by_weight biggest_profit_by_weight = sorted_profit_by_weight[length - i - 1] """ Calculate the index of the biggest_profit_by_weight in profit_by_weight list. This will give the index of the first encountered element which is same as of biggest_profit_by_weight. There may be one or more values same as that of biggest_profit_by_weight but index always encounter the very first element only. To curb this alter the values in profit_by_weight once they are used here it is done to -1 because neither profit nor weight can be in negative. """ index = profit_by_weight.index(biggest_profit_by_weight) profit_by_weight[index] = -1 # check if the weight encountered is less than the total weight # encountered before. if max_weight - limit >= weight[index]: limit += weight[index] # Adding profit gained for the given weight 1 === # weight[index]/weight[index] gain += 1 * profit[index] else: # Since the weight encountered is greater than limit, therefore take the # required number of remaining kgs and calculate profit for it. # weight remaining / weight[index] gain += (max_weight - limit) / weight[index] * profit[index] break i += 1 return gain if __name__ == "__main__": print( "Input profits, weights, and then max_weight (all positive ints) separated by " "spaces." ) profit = [int(x) for x in input("Input profits separated by spaces: ").split()] weight = [int(x) for x in input("Input weights separated by spaces: ").split()] max_weight = int(input("Max weight allowed: ")) # Function Call calc_profit(profit, weight, max_weight)
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 .hash_table import HashTable class QuadraticProbing(HashTable): """ Basic Hash Table example with open addressing using Quadratic Probing """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _collision_resolution(self, key, data=None): i = 1 new_key = self.hash_function(key + i * i) while self.values[new_key] is not None and self.values[new_key] != key: i += 1 new_key = ( self.hash_function(key + i * i) if not self.balanced_factor() >= self.lim_charge else None ) if new_key is None: break return new_key
#!/usr/bin/env python3 from .hash_table import HashTable class QuadraticProbing(HashTable): """ Basic Hash Table example with open addressing using Quadratic Probing """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _collision_resolution(self, key, data=None): i = 1 new_key = self.hash_function(key + i * i) while self.values[new_key] is not None and self.values[new_key] != key: i += 1 new_key = ( self.hash_function(key + i * i) if not self.balanced_factor() >= self.lim_charge else None ) if new_key is None: break return new_key
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Prime permutations Problem 49 The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. What 12-digit number do you form by concatenating the three terms in this sequence? Solution: First, we need to generate all 4 digits prime numbers. Then greedy all of them and use permutation to form new numbers. Use binary search to check if the permutated numbers is in our prime list and include them in a candidate list. After that, bruteforce all passed candidates sequences using 3 nested loops since we know the answer will be 12 digits. The bruteforce of this solution will be about 1 sec. """ import math from itertools import permutations def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def search(target: int, prime_list: list) -> bool: """ function to search a number in a list using Binary Search. >>> search(3, [1, 2, 3]) True >>> search(4, [1, 2, 3]) False >>> search(101, list(range(-100, 100))) False """ left, right = 0, len(prime_list) - 1 while left <= right: middle = (left + right) // 2 if prime_list[middle] == target: return True elif prime_list[middle] < target: left = middle + 1 else: right = middle - 1 return False def solution(): """ Return the solution of the problem. >>> solution() 296962999629 """ prime_list = [n for n in range(1001, 10000, 2) if is_prime(n)] candidates = [] for number in prime_list: tmp_numbers = [] for prime_member in permutations(list(str(number))): prime = int("".join(prime_member)) if prime % 2 == 0: continue if search(prime, prime_list): tmp_numbers.append(prime) tmp_numbers.sort() if len(tmp_numbers) >= 3: candidates.append(tmp_numbers) passed = [] for candidate in candidates: length = len(candidate) found = False for i in range(length): for j in range(i + 1, length): for k in range(j + 1, length): if ( abs(candidate[i] - candidate[j]) == abs(candidate[j] - candidate[k]) and len({candidate[i], candidate[j], candidate[k]}) == 3 ): passed.append( sorted([candidate[i], candidate[j], candidate[k]]) ) found = True if found: break if found: break if found: break answer = set() for seq in passed: answer.add("".join([str(i) for i in seq])) return max(int(x) for x in answer) if __name__ == "__main__": print(solution())
""" Prime permutations Problem 49 The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. What 12-digit number do you form by concatenating the three terms in this sequence? Solution: First, we need to generate all 4 digits prime numbers. Then greedy all of them and use permutation to form new numbers. Use binary search to check if the permutated numbers is in our prime list and include them in a candidate list. After that, bruteforce all passed candidates sequences using 3 nested loops since we know the answer will be 12 digits. The bruteforce of this solution will be about 1 sec. """ import math from itertools import permutations def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def search(target: int, prime_list: list) -> bool: """ function to search a number in a list using Binary Search. >>> search(3, [1, 2, 3]) True >>> search(4, [1, 2, 3]) False >>> search(101, list(range(-100, 100))) False """ left, right = 0, len(prime_list) - 1 while left <= right: middle = (left + right) // 2 if prime_list[middle] == target: return True elif prime_list[middle] < target: left = middle + 1 else: right = middle - 1 return False def solution(): """ Return the solution of the problem. >>> solution() 296962999629 """ prime_list = [n for n in range(1001, 10000, 2) if is_prime(n)] candidates = [] for number in prime_list: tmp_numbers = [] for prime_member in permutations(list(str(number))): prime = int("".join(prime_member)) if prime % 2 == 0: continue if search(prime, prime_list): tmp_numbers.append(prime) tmp_numbers.sort() if len(tmp_numbers) >= 3: candidates.append(tmp_numbers) passed = [] for candidate in candidates: length = len(candidate) found = False for i in range(length): for j in range(i + 1, length): for k in range(j + 1, length): if ( abs(candidate[i] - candidate[j]) == abs(candidate[j] - candidate[k]) and len({candidate[i], candidate[j], candidate[k]}) == 3 ): passed.append( sorted([candidate[i], candidate[j], candidate[k]]) ) found = True if found: break if found: break if found: break answer = set() for seq in passed: answer.add("".join([str(i) for i in seq])) return max(int(x) for x in answer) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 20: https://projecteuler.net/problem=20 n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ def factorial(num: int) -> int: """Find the factorial of a given number n""" fact = 1 for i in range(1, num + 1): fact *= i return fact def split_and_add(number: int) -> int: """Split number digits and add them.""" sum_of_digits = 0 while number > 0: last_digit = number % 10 sum_of_digits += last_digit number = number // 10 # Removing the last_digit from the given number return sum_of_digits def solution(num: int = 100) -> int: """Returns the sum of the digits in the factorial of num >>> solution(100) 648 >>> solution(50) 216 >>> solution(10) 27 >>> solution(5) 3 >>> solution(3) 6 >>> solution(2) 2 >>> solution(1) 1 """ nfact = factorial(num) result = split_and_add(nfact) return result if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
""" Problem 20: https://projecteuler.net/problem=20 n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ def factorial(num: int) -> int: """Find the factorial of a given number n""" fact = 1 for i in range(1, num + 1): fact *= i return fact def split_and_add(number: int) -> int: """Split number digits and add them.""" sum_of_digits = 0 while number > 0: last_digit = number % 10 sum_of_digits += last_digit number = number // 10 # Removing the last_digit from the given number return sum_of_digits def solution(num: int = 100) -> int: """Returns the sum of the digits in the factorial of num >>> solution(100) 648 >>> solution(50) 216 >>> solution(10) 27 >>> solution(5) 3 >>> solution(3) 6 >>> solution(2) 2 >>> solution(1) 1 """ nfact = factorial(num) result = split_and_add(nfact) return result if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Print all the Catalan numbers from 0 to n, n being the user input. * The Catalan numbers are a sequence of positive integers that * appear in many counting problems in combinatorics [1]. Such * problems include counting [2]: * - The number of Dyck words of length 2n * - The number well-formed expressions with n pairs of parentheses * (e.g., `()()` is valid but `())(` is not) * - The number of different ways n + 1 factors can be completely * parenthesized (e.g., for n = 2, C(n) = 2 and (ab)c and a(bc) * are the two valid ways to parenthesize. * - The number of full binary trees with n + 1 leaves * A Catalan number satisfies the following recurrence relation * which we will use in this algorithm [1]. * C(0) = C(1) = 1 * C(n) = sum(C(i).C(n-i-1)), from i = 0 to n-1 * In addition, the n-th Catalan number can be calculated using * the closed form formula below [1]: * C(n) = (1 / (n + 1)) * (2n choose n) * Sources: * [1] https://brilliant.org/wiki/catalan-numbers/ * [2] https://en.wikipedia.org/wiki/Catalan_number """ def catalan_numbers(upper_limit: int) -> "list[int]": """ Return a list of the Catalan number sequence from 0 through `upper_limit`. >>> catalan_numbers(5) [1, 1, 2, 5, 14, 42] >>> catalan_numbers(2) [1, 1, 2] >>> catalan_numbers(-1) Traceback (most recent call last): ValueError: Limit for the Catalan sequence must be ≥ 0 """ if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0") catalan_list = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 catalan_list[0] = 1 if upper_limit > 0: catalan_list[1] = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2, upper_limit + 1): for j in range(i): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("\n********* Catalan Numbers Using Dynamic Programming ************\n") print("\n*** Enter -1 at any time to quit ***") print("\nEnter the upper limit (≥ 0) for the Catalan number sequence: ", end="") try: while True: N = int(input().strip()) if N < 0: print("\n********* Goodbye!! ************") break else: print(f"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print("Try another upper limit for the sequence: ", end="") except (NameError, ValueError): print("\n********* Invalid input, goodbye! ************\n") import doctest doctest.testmod()
""" Print all the Catalan numbers from 0 to n, n being the user input. * The Catalan numbers are a sequence of positive integers that * appear in many counting problems in combinatorics [1]. Such * problems include counting [2]: * - The number of Dyck words of length 2n * - The number well-formed expressions with n pairs of parentheses * (e.g., `()()` is valid but `())(` is not) * - The number of different ways n + 1 factors can be completely * parenthesized (e.g., for n = 2, C(n) = 2 and (ab)c and a(bc) * are the two valid ways to parenthesize. * - The number of full binary trees with n + 1 leaves * A Catalan number satisfies the following recurrence relation * which we will use in this algorithm [1]. * C(0) = C(1) = 1 * C(n) = sum(C(i).C(n-i-1)), from i = 0 to n-1 * In addition, the n-th Catalan number can be calculated using * the closed form formula below [1]: * C(n) = (1 / (n + 1)) * (2n choose n) * Sources: * [1] https://brilliant.org/wiki/catalan-numbers/ * [2] https://en.wikipedia.org/wiki/Catalan_number """ def catalan_numbers(upper_limit: int) -> "list[int]": """ Return a list of the Catalan number sequence from 0 through `upper_limit`. >>> catalan_numbers(5) [1, 1, 2, 5, 14, 42] >>> catalan_numbers(2) [1, 1, 2] >>> catalan_numbers(-1) Traceback (most recent call last): ValueError: Limit for the Catalan sequence must be ≥ 0 """ if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0") catalan_list = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 catalan_list[0] = 1 if upper_limit > 0: catalan_list[1] = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2, upper_limit + 1): for j in range(i): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("\n********* Catalan Numbers Using Dynamic Programming ************\n") print("\n*** Enter -1 at any time to quit ***") print("\nEnter the upper limit (≥ 0) for the Catalan number sequence: ", end="") try: while True: N = int(input().strip()) if N < 0: print("\n********* Goodbye!! ************") break else: print(f"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print("Try another upper limit for the sequence: ", end="") except (NameError, ValueError): print("\n********* Invalid input, goodbye! ************\n") import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Recursive Prorgam to create a Linked List from a sequence and # print a string representation of it. class Node: def __init__(self, data=None): self.data = data self.next = None def __repr__(self): """Returns a visual representation of the node and all its following nodes.""" string_rep = "" temp = self while temp: string_rep += f"<{temp.data}> ---> " temp = temp.next string_rep += "<END>" return string_rep def make_linked_list(elements_list): """Creates a Linked List from the elements of the given sequence (list/tuple) and returns the head of the Linked List.""" # if elements_list is empty if not elements_list: raise Exception("The Elements List is empty") # Set first element as Head head = Node(elements_list[0]) current = head # Loop through elements from position 1 for data in elements_list[1:]: current.next = Node(data) current = current.next return head list_data = [1, 3, 5, 32, 44, 12, 43] print(f"List: {list_data}") print("Creating Linked List from List.") linked_list = make_linked_list(list_data) print("Linked List:") print(linked_list)
# Recursive Prorgam to create a Linked List from a sequence and # print a string representation of it. class Node: def __init__(self, data=None): self.data = data self.next = None def __repr__(self): """Returns a visual representation of the node and all its following nodes.""" string_rep = "" temp = self while temp: string_rep += f"<{temp.data}> ---> " temp = temp.next string_rep += "<END>" return string_rep def make_linked_list(elements_list): """Creates a Linked List from the elements of the given sequence (list/tuple) and returns the head of the Linked List.""" # if elements_list is empty if not elements_list: raise Exception("The Elements List is empty") # Set first element as Head head = Node(elements_list[0]) current = head # Loop through elements from position 1 for data in elements_list[1:]: current.next = Node(data) current = current.next return head list_data = [1, 3, 5, 32, 44, 12, 43] print(f"List: {list_data}") print("Creating Linked List from List.") linked_list = make_linked_list(list_data) print("Linked List:") print(linked_list)
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import os from itertools import chain from random import randrange, shuffle import pytest from .sol1 import PokerHand SORTED_HANDS = ( "4S 3H 2C 7S 5H", "9D 8H 2C 6S 7H", "2D 6D 9D TH 7D", "TC 8C 2S JH 6C", "JH 8S TH AH QH", "TS KS 5S 9S AC", "KD 6S 9D TH AD", "KS 8D 4D 9S 4S", # pair "8C 4S KH JS 4D", # pair "QH 8H KD JH 8S", # pair "KC 4H KS 2H 8D", # pair "KD 4S KC 3H 8S", # pair "AH 8S AS KC JH", # pair "3H 4C 4H 3S 2H", # 2 pairs "5S 5D 2C KH KH", # 2 pairs "3C KH 5D 5S KH", # 2 pairs "AS 3C KH AD KH", # 2 pairs "7C 7S 3S 7H 5S", # 3 of a kind "7C 7S KH 2H 7H", # 3 of a kind "AC KH QH AH AS", # 3 of a kind "2H 4D 3C AS 5S", # straight (low ace) "3C 5C 4C 2C 6H", # straight "6S 8S 7S 5H 9H", # straight "JS QS 9H TS KH", # straight "QC KH TS JS AH", # straight (high ace) "8C 9C 5C 3C TC", # flush "3S 8S 9S 5S KS", # flush "4C 5C 9C 8C KC", # flush "JH 8H AH KH QH", # flush "3D 2H 3H 2C 2D", # full house "2H 2C 3S 3H 3D", # full house "KH KC 3S 3H 3D", # full house "JC 6H JS JD JH", # 4 of a kind "JC 7H JS JD JH", # 4 of a kind "JC KH JS JD JH", # 4 of a kind "2S AS 4S 5S 3S", # straight flush (low ace) "2D 6D 3D 4D 5D", # straight flush "5C 6C 3C 7C 4C", # straight flush "JH 9H TH KH QH", # straight flush "JH AH TH KH QH", # royal flush (high ace straight flush) ) TEST_COMPARE = ( ("2H 3H 4H 5H 6H", "KS AS TS QS JS", "Loss"), ("2H 3H 4H 5H 6H", "AS AD AC AH JD", "Win"), ("AS AH 2H AD AC", "JS JD JC JH 3D", "Win"), ("2S AH 2H AS AC", "JS JD JC JH AD", "Loss"), ("2S AH 2H AS AC", "2H 3H 5H 6H 7H", "Win"), ("AS 3S 4S 8S 2S", "2H 3H 5H 6H 7H", "Win"), ("2H 3H 5H 6H 7H", "2S 3H 4H 5S 6C", "Win"), ("2S 3H 4H 5S 6C", "3D 4C 5H 6H 2S", "Tie"), ("2S 3H 4H 5S 6C", "AH AC 5H 6H AS", "Win"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H AS", "Loss"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H 7S", "Win"), ("6S AD 7H 4S AS", "AH AC 5H 6H 7S", "Loss"), ("2S AH 4H 5S KC", "AH AC 5H 6H 7S", "Loss"), ("2S 3H 6H 7S 9C", "7H 3C TH 6H 9S", "Loss"), ("4S 5H 6H TS AC", "3S 5H 6H TS AC", "Win"), ("2S AH 4H 5S 6C", "AD 4C 5H 6H 2C", "Tie"), ("AS AH 3H AD AC", "AS AH 2H AD AC", "Win"), ("AH AC 5H 5C QS", "AH AC 5H 5C KS", "Loss"), ("AH AC 5H 5C QS", "KH KC 5H 5C QS", "Win"), ("7C 7S KH 2H 7H", "3C 3S AH 2H 3H", "Win"), ("3C 3S AH 2H 3H", "7C 7S KH 2H 7H", "Loss"), ("6H 5H 4H 3H 2H", "5H 4H 3H 2H AH", "Win"), ("5H 4H 3H 2H AH", "5H 4H 3H 2H AH", "Tie"), ("5H 4H 3H 2H AH", "6H 5H 4H 3H 2H", "Loss"), ("AH AD KS KC AC", "AH KD KH AC KC", "Win"), ("2H 4D 3C AS 5S", "2H 4D 3C 6S 5S", "Loss"), ("2H 3S 3C 3H 2S", "3S 3C 2S 2H 2D", "Win"), ("4D 6D 5D 2D JH", "3S 8S 3H TC KH", "Loss"), ("4S 6C 8S 3S 7S", "AD KS 2D 7D 7C", "Loss"), ("6S 4C 7H 8C 3H", "5H JC AH 9D 9C", "Loss"), ("9D 9H JH TC QH", "3C 2S JS 5C 7H", "Win"), ("2H TC 8S AD 9S", "4H TS 7H 2C 5C", "Win"), ("9D 3S 2C 7S 7C", "JC TD 3C TC 9H", "Loss"), ) TEST_FLUSH = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", True), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", False), ("AS 3S 4S 8S 2S", True), ) TEST_STRAIGHT = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", False), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", True), ) TEST_FIVE_HIGH_STRAIGHT = ( ("2H 4D 3C AS 5S", True, [5, 4, 3, 2, 14]), ("2H 5D 3C AS 5S", False, [14, 5, 5, 3, 2]), ("JH QD KC AS TS", False, [14, 13, 12, 11, 10]), ("9D 3S 2C 7S 7C", False, [9, 7, 7, 3, 2]), ) TEST_KIND = ( ("JH AH TH KH QH", 0), ("JH 9H TH KH QH", 0), ("JC KH JS JD JH", 7), ("KH KC 3S 3H 3D", 6), ("8C 9C 5C 3C TC", 0), ("JS QS 9H TS KH", 0), ("7C 7S KH 2H 7H", 3), ("3C KH 5D 5S KH", 2), ("QH 8H KD JH 8S", 1), ("2D 6D 9D TH 7D", 0), ) TEST_TYPES = ( ("JH AH TH KH QH", 23), ("JH 9H TH KH QH", 22), ("JC KH JS JD JH", 21), ("KH KC 3S 3H 3D", 20), ("8C 9C 5C 3C TC", 19), ("JS QS 9H TS KH", 18), ("7C 7S KH 2H 7H", 17), ("3C KH 5D 5S KH", 16), ("QH 8H KD JH 8S", 15), ("2D 6D 9D TH 7D", 14), ) def generate_random_hand(): play, oppo = randrange(len(SORTED_HANDS)), randrange(len(SORTED_HANDS)) expected = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] hand, other = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def generate_random_hands(number_of_hands: int = 100): return (generate_random_hand() for _ in range(number_of_hands)) @pytest.mark.parametrize("hand, expected", TEST_FLUSH) def test_hand_is_flush(hand, expected): assert PokerHand(hand)._is_flush() == expected @pytest.mark.parametrize("hand, expected", TEST_STRAIGHT) def test_hand_is_straight(hand, expected): assert PokerHand(hand)._is_straight() == expected @pytest.mark.parametrize("hand, expected, card_values", TEST_FIVE_HIGH_STRAIGHT) def test_hand_is_five_high_straight(hand, expected, card_values): player = PokerHand(hand) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("hand, expected", TEST_KIND) def test_hand_is_same_kind(hand, expected): assert PokerHand(hand)._is_same_kind() == expected @pytest.mark.parametrize("hand, expected", TEST_TYPES) def test_hand_values(hand, expected): assert PokerHand(hand)._hand_type == expected @pytest.mark.parametrize("hand, other, expected", TEST_COMPARE) def test_compare_simple(hand, other, expected): assert PokerHand(hand).compare_with(PokerHand(other)) == expected @pytest.mark.parametrize("hand, other, expected", generate_random_hands()) def test_compare_random(hand, other, expected): assert PokerHand(hand).compare_with(PokerHand(other)) == expected def test_hand_sorted(): POKER_HANDS = [PokerHand(hand) for hand in SORTED_HANDS] # noqa: N806 list_copy = POKER_HANDS.copy() shuffle(list_copy) user_sorted = chain(sorted(list_copy)) for index, hand in enumerate(user_sorted): assert hand == POKER_HANDS[index] def test_custom_sort_five_high_straight(): # Test that five high straights are compared correctly. pokerhands = [PokerHand("2D AC 3H 4H 5S"), PokerHand("2S 3H 4H 5S 6C")] pokerhands.sort(reverse=True) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def test_multiple_calls_five_high_straight(): # Multiple calls to five_high_straight function should still return True # and shouldn't mutate the list in every call other than the first. pokerhand = PokerHand("2C 4S AS 3D 5C") expected = True expected_card_values = [5, 4, 3, 2, 14] for _ in range(10): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def test_euler_project(): # Problem number 54 from Project Euler # Testing from poker_hands.txt file answer = 0 script_dir = os.path.abspath(os.path.dirname(__file__)) poker_hands = os.path.join(script_dir, "poker_hands.txt") with open(poker_hands) as file_hand: for line in file_hand: player_hand = line[:14].strip() opponent_hand = line[15:].strip() player, opponent = PokerHand(player_hand), PokerHand(opponent_hand) output = player.compare_with(opponent) if output == "Win": answer += 1 assert answer == 376
import os from itertools import chain from random import randrange, shuffle import pytest from .sol1 import PokerHand SORTED_HANDS = ( "4S 3H 2C 7S 5H", "9D 8H 2C 6S 7H", "2D 6D 9D TH 7D", "TC 8C 2S JH 6C", "JH 8S TH AH QH", "TS KS 5S 9S AC", "KD 6S 9D TH AD", "KS 8D 4D 9S 4S", # pair "8C 4S KH JS 4D", # pair "QH 8H KD JH 8S", # pair "KC 4H KS 2H 8D", # pair "KD 4S KC 3H 8S", # pair "AH 8S AS KC JH", # pair "3H 4C 4H 3S 2H", # 2 pairs "5S 5D 2C KH KH", # 2 pairs "3C KH 5D 5S KH", # 2 pairs "AS 3C KH AD KH", # 2 pairs "7C 7S 3S 7H 5S", # 3 of a kind "7C 7S KH 2H 7H", # 3 of a kind "AC KH QH AH AS", # 3 of a kind "2H 4D 3C AS 5S", # straight (low ace) "3C 5C 4C 2C 6H", # straight "6S 8S 7S 5H 9H", # straight "JS QS 9H TS KH", # straight "QC KH TS JS AH", # straight (high ace) "8C 9C 5C 3C TC", # flush "3S 8S 9S 5S KS", # flush "4C 5C 9C 8C KC", # flush "JH 8H AH KH QH", # flush "3D 2H 3H 2C 2D", # full house "2H 2C 3S 3H 3D", # full house "KH KC 3S 3H 3D", # full house "JC 6H JS JD JH", # 4 of a kind "JC 7H JS JD JH", # 4 of a kind "JC KH JS JD JH", # 4 of a kind "2S AS 4S 5S 3S", # straight flush (low ace) "2D 6D 3D 4D 5D", # straight flush "5C 6C 3C 7C 4C", # straight flush "JH 9H TH KH QH", # straight flush "JH AH TH KH QH", # royal flush (high ace straight flush) ) TEST_COMPARE = ( ("2H 3H 4H 5H 6H", "KS AS TS QS JS", "Loss"), ("2H 3H 4H 5H 6H", "AS AD AC AH JD", "Win"), ("AS AH 2H AD AC", "JS JD JC JH 3D", "Win"), ("2S AH 2H AS AC", "JS JD JC JH AD", "Loss"), ("2S AH 2H AS AC", "2H 3H 5H 6H 7H", "Win"), ("AS 3S 4S 8S 2S", "2H 3H 5H 6H 7H", "Win"), ("2H 3H 5H 6H 7H", "2S 3H 4H 5S 6C", "Win"), ("2S 3H 4H 5S 6C", "3D 4C 5H 6H 2S", "Tie"), ("2S 3H 4H 5S 6C", "AH AC 5H 6H AS", "Win"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H AS", "Loss"), ("2S 2H 4H 5S 4C", "AH AC 5H 6H 7S", "Win"), ("6S AD 7H 4S AS", "AH AC 5H 6H 7S", "Loss"), ("2S AH 4H 5S KC", "AH AC 5H 6H 7S", "Loss"), ("2S 3H 6H 7S 9C", "7H 3C TH 6H 9S", "Loss"), ("4S 5H 6H TS AC", "3S 5H 6H TS AC", "Win"), ("2S AH 4H 5S 6C", "AD 4C 5H 6H 2C", "Tie"), ("AS AH 3H AD AC", "AS AH 2H AD AC", "Win"), ("AH AC 5H 5C QS", "AH AC 5H 5C KS", "Loss"), ("AH AC 5H 5C QS", "KH KC 5H 5C QS", "Win"), ("7C 7S KH 2H 7H", "3C 3S AH 2H 3H", "Win"), ("3C 3S AH 2H 3H", "7C 7S KH 2H 7H", "Loss"), ("6H 5H 4H 3H 2H", "5H 4H 3H 2H AH", "Win"), ("5H 4H 3H 2H AH", "5H 4H 3H 2H AH", "Tie"), ("5H 4H 3H 2H AH", "6H 5H 4H 3H 2H", "Loss"), ("AH AD KS KC AC", "AH KD KH AC KC", "Win"), ("2H 4D 3C AS 5S", "2H 4D 3C 6S 5S", "Loss"), ("2H 3S 3C 3H 2S", "3S 3C 2S 2H 2D", "Win"), ("4D 6D 5D 2D JH", "3S 8S 3H TC KH", "Loss"), ("4S 6C 8S 3S 7S", "AD KS 2D 7D 7C", "Loss"), ("6S 4C 7H 8C 3H", "5H JC AH 9D 9C", "Loss"), ("9D 9H JH TC QH", "3C 2S JS 5C 7H", "Win"), ("2H TC 8S AD 9S", "4H TS 7H 2C 5C", "Win"), ("9D 3S 2C 7S 7C", "JC TD 3C TC 9H", "Loss"), ) TEST_FLUSH = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", True), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", False), ("AS 3S 4S 8S 2S", True), ) TEST_STRAIGHT = ( ("2H 3H 4H 5H 6H", True), ("AS AH 2H AD AC", False), ("2H 3H 5H 6H 7H", False), ("KS AS TS QS JS", True), ("8H 9H QS JS TH", True), ) TEST_FIVE_HIGH_STRAIGHT = ( ("2H 4D 3C AS 5S", True, [5, 4, 3, 2, 14]), ("2H 5D 3C AS 5S", False, [14, 5, 5, 3, 2]), ("JH QD KC AS TS", False, [14, 13, 12, 11, 10]), ("9D 3S 2C 7S 7C", False, [9, 7, 7, 3, 2]), ) TEST_KIND = ( ("JH AH TH KH QH", 0), ("JH 9H TH KH QH", 0), ("JC KH JS JD JH", 7), ("KH KC 3S 3H 3D", 6), ("8C 9C 5C 3C TC", 0), ("JS QS 9H TS KH", 0), ("7C 7S KH 2H 7H", 3), ("3C KH 5D 5S KH", 2), ("QH 8H KD JH 8S", 1), ("2D 6D 9D TH 7D", 0), ) TEST_TYPES = ( ("JH AH TH KH QH", 23), ("JH 9H TH KH QH", 22), ("JC KH JS JD JH", 21), ("KH KC 3S 3H 3D", 20), ("8C 9C 5C 3C TC", 19), ("JS QS 9H TS KH", 18), ("7C 7S KH 2H 7H", 17), ("3C KH 5D 5S KH", 16), ("QH 8H KD JH 8S", 15), ("2D 6D 9D TH 7D", 14), ) def generate_random_hand(): play, oppo = randrange(len(SORTED_HANDS)), randrange(len(SORTED_HANDS)) expected = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] hand, other = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def generate_random_hands(number_of_hands: int = 100): return (generate_random_hand() for _ in range(number_of_hands)) @pytest.mark.parametrize("hand, expected", TEST_FLUSH) def test_hand_is_flush(hand, expected): assert PokerHand(hand)._is_flush() == expected @pytest.mark.parametrize("hand, expected", TEST_STRAIGHT) def test_hand_is_straight(hand, expected): assert PokerHand(hand)._is_straight() == expected @pytest.mark.parametrize("hand, expected, card_values", TEST_FIVE_HIGH_STRAIGHT) def test_hand_is_five_high_straight(hand, expected, card_values): player = PokerHand(hand) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("hand, expected", TEST_KIND) def test_hand_is_same_kind(hand, expected): assert PokerHand(hand)._is_same_kind() == expected @pytest.mark.parametrize("hand, expected", TEST_TYPES) def test_hand_values(hand, expected): assert PokerHand(hand)._hand_type == expected @pytest.mark.parametrize("hand, other, expected", TEST_COMPARE) def test_compare_simple(hand, other, expected): assert PokerHand(hand).compare_with(PokerHand(other)) == expected @pytest.mark.parametrize("hand, other, expected", generate_random_hands()) def test_compare_random(hand, other, expected): assert PokerHand(hand).compare_with(PokerHand(other)) == expected def test_hand_sorted(): POKER_HANDS = [PokerHand(hand) for hand in SORTED_HANDS] # noqa: N806 list_copy = POKER_HANDS.copy() shuffle(list_copy) user_sorted = chain(sorted(list_copy)) for index, hand in enumerate(user_sorted): assert hand == POKER_HANDS[index] def test_custom_sort_five_high_straight(): # Test that five high straights are compared correctly. pokerhands = [PokerHand("2D AC 3H 4H 5S"), PokerHand("2S 3H 4H 5S 6C")] pokerhands.sort(reverse=True) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def test_multiple_calls_five_high_straight(): # Multiple calls to five_high_straight function should still return True # and shouldn't mutate the list in every call other than the first. pokerhand = PokerHand("2C 4S AS 3D 5C") expected = True expected_card_values = [5, 4, 3, 2, 14] for _ in range(10): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def test_euler_project(): # Problem number 54 from Project Euler # Testing from poker_hands.txt file answer = 0 script_dir = os.path.abspath(os.path.dirname(__file__)) poker_hands = os.path.join(script_dir, "poker_hands.txt") with open(poker_hands) as file_hand: for line in file_hand: player_hand = line[:14].strip() opponent_hand = line[15:].strip() player, opponent = PokerHand(player_hand), PokerHand(opponent_hand) output = player.compare_with(opponent) if output == "Win": answer += 1 assert answer == 376
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 palindromic_string(input_string: str) -> str: """ >>> palindromic_string('abbbaba') 'abbba' >>> palindromic_string('ababa') 'ababa' Manacher’s algorithm which finds Longest palindromic Substring in linear time. 1. first this convert input_string("xyx") into new_string("x|y|x") where odd positions are actual input characters. 2. for each character in new_string it find corresponding length and store the length and l,r to store previously calculated info.(please look the explanation for details) 3. return corresponding output_string by removing all "|" """ max_length = 0 # if input_string is "aba" than new_input_string become "a|b|a" new_input_string = "" output_string = "" # append each character + "|" in new_string for range(0, length-1) for i in input_string[: len(input_string) - 1]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring l, r = 0, 0 # length[i] shows the length of palindromic substring with center i length = [1 for i in range(len(new_input_string))] # for each character in new_string find corresponding palindromic string start = 0 for j in range(len(new_input_string)): k = 1 if j > r else min(length[l + r - j] // 2, r - j + 1) while ( j - k >= 0 and j + k < len(new_input_string) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 length[j] = 2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: l = j - k + 1 # noqa: E741 r = j + k - 1 # update max_length and start position if max_length < length[j]: max_length = length[j] start = j # create that string s = new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string if __name__ == "__main__": import doctest doctest.testmod() """ ...a0...a1...a2.....a3......a4...a5...a6.... consider the string for which we are calculating the longest palindromic substring is shown above where ... are some characters in between and right now we are calculating the length of palindromic substring with center at a5 with following conditions : i) we have stored the length of palindromic substring which has center at a3 (starts at l ends at r) and it is the furthest ending till now, and it has ending after a6 ii) a2 and a4 are equally distant from a3 so char(a2) == char(a4) iii) a0 and a6 are equally distant from a3 so char(a0) == char(a6) iv) a1 is corresponding equal character of a5 in palindrome with center a3 (remember that in below derivation of a4==a6) now for a5 we will calculate the length of palindromic substring with center as a5 but can we use previously calculated information in some way? Yes, look the above string we know that a5 is inside the palindrome with center a3 and previously we have calculated that a0==a2 (palindrome of center a1) a2==a4 (palindrome of center a3) a0==a6 (palindrome of center a3) so a4==a6 so we can say that palindrome at center a5 is at least as long as palindrome at center a1 but this only holds if a0 and a6 are inside the limits of palindrome centered at a3 so finally .. len_of_palindrome__at(a5) = min(len_of_palindrome_at(a1), r-a5) where a3 lies from l to r and we have to keep updating that and if the a5 lies outside of l,r boundary we calculate length of palindrome with bruteforce and update l,r. it gives the linear time complexity just like z-function """
def palindromic_string(input_string: str) -> str: """ >>> palindromic_string('abbbaba') 'abbba' >>> palindromic_string('ababa') 'ababa' Manacher’s algorithm which finds Longest palindromic Substring in linear time. 1. first this convert input_string("xyx") into new_string("x|y|x") where odd positions are actual input characters. 2. for each character in new_string it find corresponding length and store the length and l,r to store previously calculated info.(please look the explanation for details) 3. return corresponding output_string by removing all "|" """ max_length = 0 # if input_string is "aba" than new_input_string become "a|b|a" new_input_string = "" output_string = "" # append each character + "|" in new_string for range(0, length-1) for i in input_string[: len(input_string) - 1]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring l, r = 0, 0 # length[i] shows the length of palindromic substring with center i length = [1 for i in range(len(new_input_string))] # for each character in new_string find corresponding palindromic string start = 0 for j in range(len(new_input_string)): k = 1 if j > r else min(length[l + r - j] // 2, r - j + 1) while ( j - k >= 0 and j + k < len(new_input_string) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 length[j] = 2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: l = j - k + 1 # noqa: E741 r = j + k - 1 # update max_length and start position if max_length < length[j]: max_length = length[j] start = j # create that string s = new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string if __name__ == "__main__": import doctest doctest.testmod() """ ...a0...a1...a2.....a3......a4...a5...a6.... consider the string for which we are calculating the longest palindromic substring is shown above where ... are some characters in between and right now we are calculating the length of palindromic substring with center at a5 with following conditions : i) we have stored the length of palindromic substring which has center at a3 (starts at l ends at r) and it is the furthest ending till now, and it has ending after a6 ii) a2 and a4 are equally distant from a3 so char(a2) == char(a4) iii) a0 and a6 are equally distant from a3 so char(a0) == char(a6) iv) a1 is corresponding equal character of a5 in palindrome with center a3 (remember that in below derivation of a4==a6) now for a5 we will calculate the length of palindromic substring with center as a5 but can we use previously calculated information in some way? Yes, look the above string we know that a5 is inside the palindrome with center a3 and previously we have calculated that a0==a2 (palindrome of center a1) a2==a4 (palindrome of center a3) a0==a6 (palindrome of center a3) so a4==a6 so we can say that palindrome at center a5 is at least as long as palindrome at center a1 but this only holds if a0 and a6 are inside the limits of palindrome centered at a3 so finally .. len_of_palindrome__at(a5) = min(len_of_palindrome_at(a1), r-a5) where a3 lies from l to r and we have to keep updating that and if the a5 lies outside of l,r boundary we calculate length of palindrome with bruteforce and update l,r. it gives the linear time complexity just like z-function """
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
59 73 41 52 40 09 26 53 06 34 10 51 87 86 81 61 95 66 57 25 68 90 81 80 38 92 67 73 30 28 51 76 81 18 75 44 84 14 95 87 62 81 17 78 58 21 46 71 58 02 79 62 39 31 09 56 34 35 53 78 31 81 18 90 93 15 78 53 04 21 84 93 32 13 97 11 37 51 45 03 81 79 05 18 78 86 13 30 63 99 95 39 87 96 28 03 38 42 17 82 87 58 07 22 57 06 17 51 17 07 93 09 07 75 97 95 78 87 08 53 67 66 59 60 88 99 94 65 55 77 55 34 27 53 78 28 76 40 41 04 87 16 09 42 75 69 23 97 30 60 10 79 87 12 10 44 26 21 36 32 84 98 60 13 12 36 16 63 31 91 35 70 39 06 05 55 27 38 48 28 22 34 35 62 62 15 14 94 89 86 66 56 68 84 96 21 34 34 34 81 62 40 65 54 62 05 98 03 02 60 38 89 46 37 99 54 34 53 36 14 70 26 02 90 45 13 31 61 83 73 47 36 10 63 96 60 49 41 05 37 42 14 58 84 93 96 17 09 43 05 43 06 59 66 57 87 57 61 28 37 51 84 73 79 15 39 95 88 87 43 39 11 86 77 74 18 54 42 05 79 30 49 99 73 46 37 50 02 45 09 54 52 27 95 27 65 19 45 26 45 71 39 17 78 76 29 52 90 18 99 78 19 35 62 71 19 23 65 93 85 49 33 75 09 02 33 24 47 61 60 55 32 88 57 55 91 54 46 57 07 77 98 52 80 99 24 25 46 78 79 05 92 09 13 55 10 67 26 78 76 82 63 49 51 31 24 68 05 57 07 54 69 21 67 43 17 63 12 24 59 06 08 98 74 66 26 61 60 13 03 09 09 24 30 71 08 88 70 72 70 29 90 11 82 41 34 66 82 67 04 36 60 92 77 91 85 62 49 59 61 30 90 29 94 26 41 89 04 53 22 83 41 09 74 90 48 28 26 37 28 52 77 26 51 32 18 98 79 36 62 13 17 08 19 54 89 29 73 68 42 14 08 16 70 37 37 60 69 70 72 71 09 59 13 60 38 13 57 36 09 30 43 89 30 39 15 02 44 73 05 73 26 63 56 86 12 55 55 85 50 62 99 84 77 28 85 03 21 27 22 19 26 82 69 54 04 13 07 85 14 01 15 70 59 89 95 10 19 04 09 31 92 91 38 92 86 98 75 21 05 64 42 62 84 36 20 73 42 21 23 22 51 51 79 25 45 85 53 03 43 22 75 63 02 49 14 12 89 14 60 78 92 16 44 82 38 30 72 11 46 52 90 27 08 65 78 03 85 41 57 79 39 52 33 48 78 27 56 56 39 13 19 43 86 72 58 95 39 07 04 34 21 98 39 15 39 84 89 69 84 46 37 57 59 35 59 50 26 15 93 42 89 36 27 78 91 24 11 17 41 05 94 07 69 51 96 03 96 47 90 90 45 91 20 50 56 10 32 36 49 04 53 85 92 25 65 52 09 61 30 61 97 66 21 96 92 98 90 06 34 96 60 32 69 68 33 75 84 18 31 71 50 84 63 03 03 19 11 28 42 75 45 45 61 31 61 68 96 34 49 39 05 71 76 59 62 67 06 47 96 99 34 21 32 47 52 07 71 60 42 72 94 56 82 83 84 40 94 87 82 46 01 20 60 14 17 38 26 78 66 81 45 95 18 51 98 81 48 16 53 88 37 52 69 95 72 93 22 34 98 20 54 27 73 61 56 63 60 34 63 93 42 94 83 47 61 27 51 79 79 45 01 44 73 31 70 83 42 88 25 53 51 30 15 65 94 80 44 61 84 12 77 02 62 02 65 94 42 14 94 32 73 09 67 68 29 74 98 10 19 85 48 38 31 85 67 53 93 93 77 47 67 39 72 94 53 18 43 77 40 78 32 29 59 24 06 02 83 50 60 66 32 01 44 30 16 51 15 81 98 15 10 62 86 79 50 62 45 60 70 38 31 85 65 61 64 06 69 84 14 22 56 43 09 48 66 69 83 91 60 40 36 61 92 48 22 99 15 95 64 43 01 16 94 02 99 19 17 69 11 58 97 56 89 31 77 45 67 96 12 73 08 20 36 47 81 44 50 64 68 85 40 81 85 52 09 91 35 92 45 32 84 62 15 19 64 21 66 06 01 52 80 62 59 12 25 88 28 91 50 40 16 22 99 92 79 87 51 21 77 74 77 07 42 38 42 74 83 02 05 46 19 77 66 24 18 05 32 02 84 31 99 92 58 96 72 91 36 62 99 55 29 53 42 12 37 26 58 89 50 66 19 82 75 12 48 24 87 91 85 02 07 03 76 86 99 98 84 93 07 17 33 61 92 20 66 60 24 66 40 30 67 05 37 29 24 96 03 27 70 62 13 04 45 47 59 88 43 20 66 15 46 92 30 04 71 66 78 70 53 99 67 60 38 06 88 04 17 72 10 99 71 07 42 25 54 05 26 64 91 50 45 71 06 30 67 48 69 82 08 56 80 67 18 46 66 63 01 20 08 80 47 07 91 16 03 79 87 18 54 78 49 80 48 77 40 68 23 60 88 58 80 33 57 11 69 55 53 64 02 94 49 60 92 16 35 81 21 82 96 25 24 96 18 02 05 49 03 50 77 06 32 84 27 18 38 68 01 50 04 03 21 42 94 53 24 89 05 92 26 52 36 68 11 85 01 04 42 02 45 15 06 50 04 53 73 25 74 81 88 98 21 67 84 79 97 99 20 95 04 40 46 02 58 87 94 10 02 78 88 52 21 03 88 60 06 53 49 71 20 91 12 65 07 49 21 22 11 41 58 99 36 16 09 48 17 24 52 36 23 15 72 16 84 56 02 99 43 76 81 71 29 39 49 17 64 39 59 84 86 16 17 66 03 09 43 06 64 18 63 29 68 06 23 07 87 14 26 35 17 12 98 41 53 64 78 18 98 27 28 84 80 67 75 62 10 11 76 90 54 10 05 54 41 39 66 43 83 18 37 32 31 52 29 95 47 08 76 35 11 04 53 35 43 34 10 52 57 12 36 20 39 40 55 78 44 07 31 38 26 08 15 56 88 86 01 52 62 10 24 32 05 60 65 53 28 57 99 03 50 03 52 07 73 49 92 66 80 01 46 08 67 25 36 73 93 07 42 25 53 13 96 76 83 87 90 54 89 78 22 78 91 73 51 69 09 79 94 83 53 09 40 69 62 10 79 49 47 03 81 30 71 54 73 33 51 76 59 54 79 37 56 45 84 17 62 21 98 69 41 95 65 24 39 37 62 03 24 48 54 64 46 82 71 78 33 67 09 16 96 68 52 74 79 68 32 21 13 78 96 60 09 69 20 36 73 26 21 44 46 38 17 83 65 98 07 23 52 46 61 97 33 13 60 31 70 15 36 77 31 58 56 93 75 68 21 36 69 53 90 75 25 82 39 50 65 94 29 30 11 33 11 13 96 02 56 47 07 49 02 76 46 73 30 10 20 60 70 14 56 34 26 37 39 48 24 55 76 84 91 39 86 95 61 50 14 53 93 64 67 37 31 10 84 42 70 48 20 10 72 60 61 84 79 69 65 99 73 89 25 85 48 92 56 97 16 03 14 80 27 22 30 44 27 67 75 79 32 51 54 81 29 65 14 19 04 13 82 04 91 43 40 12 52 29 99 07 76 60 25 01 07 61 71 37 92 40 47 99 66 57 01 43 44 22 40 53 53 09 69 26 81 07 49 80 56 90 93 87 47 13 75 28 87 23 72 79 32 18 27 20 28 10 37 59 21 18 70 04 79 96 03 31 45 71 81 06 14 18 17 05 31 50 92 79 23 47 09 39 47 91 43 54 69 47 42 95 62 46 32 85 37 18 62 85 87 28 64 05 77 51 47 26 30 65 05 70 65 75 59 80 42 52 25 20 44 10 92 17 71 95 52 14 77 13 24 55 11 65 26 91 01 30 63 15 49 48 41 17 67 47 03 68 20 90 98 32 04 40 68 90 51 58 60 06 55 23 68 05 19 76 94 82 36 96 43 38 90 87 28 33 83 05 17 70 83 96 93 06 04 78 47 80 06 23 84 75 23 87 72 99 14 50 98 92 38 90 64 61 58 76 94 36 66 87 80 51 35 61 38 57 95 64 06 53 36 82 51 40 33 47 14 07 98 78 65 39 58 53 06 50 53 04 69 40 68 36 69 75 78 75 60 03 32 39 24 74 47 26 90 13 40 44 71 90 76 51 24 36 50 25 45 70 80 61 80 61 43 90 64 11 18 29 86 56 68 42 79 10 42 44 30 12 96 18 23 18 52 59 02 99 67 46 60 86 43 38 55 17 44 93 42 21 55 14 47 34 55 16 49 24 23 29 96 51 55 10 46 53 27 92 27 46 63 57 30 65 43 27 21 20 24 83 81 72 93 19 69 52 48 01 13 83 92 69 20 48 69 59 20 62 05 42 28 89 90 99 32 72 84 17 08 87 36 03 60 31 36 36 81 26 97 36 48 54 56 56 27 16 91 08 23 11 87 99 33 47 02 14 44 73 70 99 43 35 33 90 56 61 86 56 12 70 59 63 32 01 15 81 47 71 76 95 32 65 80 54 70 34 51 40 45 33 04 64 55 78 68 88 47 31 47 68 87 03 84 23 44 89 72 35 08 31 76 63 26 90 85 96 67 65 91 19 14 17 86 04 71 32 95 37 13 04 22 64 37 37 28 56 62 86 33 07 37 10 44 52 82 52 06 19 52 57 75 90 26 91 24 06 21 14 67 76 30 46 14 35 89 89 41 03 64 56 97 87 63 22 34 03 79 17 45 11 53 25 56 96 61 23 18 63 31 37 37 47 77 23 26 70 72 76 77 04 28 64 71 69 14 85 96 54 95 48 06 62 99 83 86 77 97 75 71 66 30 19 57 90 33 01 60 61 14 12 90 99 32 77 56 41 18 14 87 49 10 14 90 64 18 50 21 74 14 16 88 05 45 73 82 47 74 44 22 97 41 13 34 31 54 61 56 94 03 24 59 27 98 77 04 09 37 40 12 26 87 09 71 70 07 18 64 57 80 21 12 71 83 94 60 39 73 79 73 19 97 32 64 29 41 07 48 84 85 67 12 74 95 20 24 52 41 67 56 61 29 93 35 72 69 72 23 63 66 01 11 07 30 52 56 95 16 65 26 83 90 50 74 60 18 16 48 43 77 37 11 99 98 30 94 91 26 62 73 45 12 87 73 47 27 01 88 66 99 21 41 95 80 02 53 23 32 61 48 32 43 43 83 14 66 95 91 19 81 80 67 25 88 08 62 32 18 92 14 83 71 37 96 11 83 39 99 05 16 23 27 10 67 02 25 44 11 55 31 46 64 41 56 44 74 26 81 51 31 45 85 87 09 81 95 22 28 76 69 46 48 64 87 67 76 27 89 31 11 74 16 62 03 60 94 42 47 09 34 94 93 72 56 18 90 18 42 17 42 32 14 86 06 53 33 95 99 35 29 15 44 20 49 59 25 54 34 59 84 21 23 54 35 90 78 16 93 13 37 88 54 19 86 67 68 55 66 84 65 42 98 37 87 56 33 28 58 38 28 38 66 27 52 21 81 15 08 22 97 32 85 27 91 53 40 28 13 34 91 25 01 63 50 37 22 49 71 58 32 28 30 18 68 94 23 83 63 62 94 76 80 41 90 22 82 52 29 12 18 56 10 08 35 14 37 57 23 65 67 40 72 39 93 39 70 89 40 34 07 46 94 22 20 05 53 64 56 30 05 56 61 88 27 23 95 11 12 37 69 68 24 66 10 87 70 43 50 75 07 62 41 83 58 95 93 89 79 45 39 02 22 05 22 95 43 62 11 68 29 17 40 26 44 25 71 87 16 70 85 19 25 59 94 90 41 41 80 61 70 55 60 84 33 95 76 42 63 15 09 03 40 38 12 03 32 09 84 56 80 61 55 85 97 16 94 82 94 98 57 84 30 84 48 93 90 71 05 95 90 73 17 30 98 40 64 65 89 07 79 09 19 56 36 42 30 23 69 73 72 07 05 27 61 24 31 43 48 71 84 21 28 26 65 65 59 65 74 77 20 10 81 61 84 95 08 52 23 70 47 81 28 09 98 51 67 64 35 51 59 36 92 82 77 65 80 24 72 53 22 07 27 10 21 28 30 22 48 82 80 48 56 20 14 43 18 25 50 95 90 31 77 08 09 48 44 80 90 22 93 45 82 17 13 96 25 26 08 73 34 99 06 49 24 06 83 51 40 14 15 10 25 01 54 25 10 81 30 64 24 74 75 80 36 75 82 60 22 69 72 91 45 67 03 62 79 54 89 74 44 83 64 96 66 73 44 30 74 50 37 05 09 97 70 01 60 46 37 91 39 75 75 18 58 52 72 78 51 81 86 52 08 97 01 46 43 66 98 62 81 18 70 93 73 08 32 46 34 96 80 82 07 59 71 92 53 19 20 88 66 03 26 26 10 24 27 50 82 94 73 63 08 51 33 22 45 19 13 58 33 90 15 22 50 36 13 55 06 35 47 82 52 33 61 36 27 28 46 98 14 73 20 73 32 16 26 80 53 47 66 76 38 94 45 02 01 22 52 47 96 64 58 52 39 88 46 23 39 74 63 81 64 20 90 33 33 76 55 58 26 10 46 42 26 74 74 12 83 32 43 09 02 73 55 86 54 85 34 28 23 29 79 91 62 47 41 82 87 99 22 48 90 20 05 96 75 95 04 43 28 81 39 81 01 28 42 78 25 39 77 90 57 58 98 17 36 73 22 63 74 51 29 39 74 94 95 78 64 24 38 86 63 87 93 06 70 92 22 16 80 64 29 52 20 27 23 50 14 13 87 15 72 96 81 22 08 49 72 30 70 24 79 31 16 64 59 21 89 34 96 91 48 76 43 53 88 01 57 80 23 81 90 79 58 01 80 87 17 99 86 90 72 63 32 69 14 28 88 69 37 17 71 95 56 93 71 35 43 45 04 98 92 94 84 96 11 30 31 27 31 60 92 03 48 05 98 91 86 94 35 90 90 08 48 19 33 28 68 37 59 26 65 96 50 68 22 07 09 49 34 31 77 49 43 06 75 17 81 87 61 79 52 26 27 72 29 50 07 98 86 01 17 10 46 64 24 18 56 51 30 25 94 88 85 79 91 40 33 63 84 49 67 98 92 15 26 75 19 82 05 18 78 65 93 61 48 91 43 59 41 70 51 22 15 92 81 67 91 46 98 11 11 65 31 66 10 98 65 83 21 05 56 05 98 73 67 46 74 69 34 08 30 05 52 07 98 32 95 30 94 65 50 24 63 28 81 99 57 19 23 61 36 09 89 71 98 65 17 30 29 89 26 79 74 94 11 44 48 97 54 81 55 39 66 69 45 28 47 13 86 15 76 74 70 84 32 36 33 79 20 78 14 41 47 89 28 81 05 99 66 81 86 38 26 06 25 13 60 54 55 23 53 27 05 89 25 23 11 13 54 59 54 56 34 16 24 53 44 06 13 40 57 72 21 15 60 08 04 19 11 98 34 45 09 97 86 71 03 15 56 19 15 44 97 31 90 04 87 87 76 08 12 30 24 62 84 28 12 85 82 53 99 52 13 94 06 65 97 86 09 50 94 68 69 74 30 67 87 94 63 07 78 27 80 36 69 41 06 92 32 78 37 82 30 05 18 87 99 72 19 99 44 20 55 77 69 91 27 31 28 81 80 27 02 07 97 23 95 98 12 25 75 29 47 71 07 47 78 39 41 59 27 76 13 15 66 61 68 35 69 86 16 53 67 63 99 85 41 56 08 28 33 40 94 76 90 85 31 70 24 65 84 65 99 82 19 25 54 37 21 46 33 02 52 99 51 33 26 04 87 02 08 18 96 54 42 61 45 91 06 64 79 80 82 32 16 83 63 42 49 19 78 65 97 40 42 14 61 49 34 04 18 25 98 59 30 82 72 26 88 54 36 21 75 03 88 99 53 46 51 55 78 22 94 34 40 68 87 84 25 30 76 25 08 92 84 42 61 40 38 09 99 40 23 29 39 46 55 10 90 35 84 56 70 63 23 91 39 52 92 03 71 89 07 09 37 68 66 58 20 44 92 51 56 13 71 79 99 26 37 02 06 16 67 36 52 58 16 79 73 56 60 59 27 44 77 94 82 20 50 98 33 09 87 94 37 40 83 64 83 58 85 17 76 53 02 83 52 22 27 39 20 48 92 45 21 09 42 24 23 12 37 52 28 50 78 79 20 86 62 73 20 59 54 96 80 15 91 90 99 70 10 09 58 90 93 50 81 99 54 38 36 10 30 11 35 84 16 45 82 18 11 97 36 43 96 79 97 65 40 48 23 19 17 31 64 52 65 65 37 32 65 76 99 79 34 65 79 27 55 33 03 01 33 27 61 28 66 08 04 70 49 46 48 83 01 45 19 96 13 81 14 21 31 79 93 85 50 05 92 92 48 84 59 98 31 53 23 27 15 22 79 95 24 76 05 79 16 93 97 89 38 89 42 83 02 88 94 95 82 21 01 97 48 39 31 78 09 65 50 56 97 61 01 07 65 27 21 23 14 15 80 97 44 78 49 35 33 45 81 74 34 05 31 57 09 38 94 07 69 54 69 32 65 68 46 68 78 90 24 28 49 51 45 86 35 41 63 89 76 87 31 86 09 46 14 87 82 22 29 47 16 13 10 70 72 82 95 48 64 58 43 13 75 42 69 21 12 67 13 64 85 58 23 98 09 37 76 05 22 31 12 66 50 29 99 86 72 45 25 10 28 19 06 90 43 29 31 67 79 46 25 74 14 97 35 76 37 65 46 23 82 06 22 30 76 93 66 94 17 96 13 20 72 63 40 78 08 52 09 90 41 70 28 36 14 46 44 85 96 24 52 58 15 87 37 05 98 99 39 13 61 76 38 44 99 83 74 90 22 53 80 56 98 30 51 63 39 44 30 91 91 04 22 27 73 17 35 53 18 35 45 54 56 27 78 48 13 69 36 44 38 71 25 30 56 15 22 73 43 32 69 59 25 93 83 45 11 34 94 44 39 92 12 36 56 88 13 96 16 12 55 54 11 47 19 78 17 17 68 81 77 51 42 55 99 85 66 27 81 79 93 42 65 61 69 74 14 01 18 56 12 01 58 37 91 22 42 66 83 25 19 04 96 41 25 45 18 69 96 88 36 93 10 12 98 32 44 83 83 04 72 91 04 27 73 07 34 37 71 60 59 31 01 54 54 44 96 93 83 36 04 45 30 18 22 20 42 96 65 79 17 41 55 69 94 81 29 80 91 31 85 25 47 26 43 49 02 99 34 67 99 76 16 14 15 93 08 32 99 44 61 77 67 50 43 55 87 55 53 72 17 46 62 25 50 99 73 05 93 48 17 31 70 80 59 09 44 59 45 13 74 66 58 94 87 73 16 14 85 38 74 99 64 23 79 28 71 42 20 37 82 31 23 51 96 39 65 46 71 56 13 29 68 53 86 45 33 51 49 12 91 21 21 76 85 02 17 98 15 46 12 60 21 88 30 92 83 44 59 42 50 27 88 46 86 94 73 45 54 23 24 14 10 94 21 20 34 23 51 04 83 99 75 90 63 60 16 22 33 83 70 11 32 10 50 29 30 83 46 11 05 31 17 86 42 49 01 44 63 28 60 07 78 95 40 44 61 89 59 04 49 51 27 69 71 46 76 44 04 09 34 56 39 15 06 94 91 75 90 65 27 56 23 74 06 23 33 36 69 14 39 05 34 35 57 33 22 76 46 56 10 61 65 98 09 16 69 04 62 65 18 99 76 49 18 72 66 73 83 82 40 76 31 89 91 27 88 17 35 41 35 32 51 32 67 52 68 74 85 80 57 07 11 62 66 47 22 67 65 37 19 97 26 17 16 24 24 17 50 37 64 82 24 36 32 11 68 34 69 31 32 89 79 93 96 68 49 90 14 23 04 04 67 99 81 74 70 74 36 96 68 09 64 39 88 35 54 89 96 58 66 27 88 97 32 14 06 35 78 20 71 06 85 66 57 02 58 91 72 05 29 56 73 48 86 52 09 93 22 57 79 42 12 01 31 68 17 59 63 76 07 77 73 81 14 13 17 20 11 09 01 83 08 85 91 70 84 63 62 77 37 07 47 01 59 95 39 69 39 21 99 09 87 02 97 16 92 36 74 71 90 66 33 73 73 75 52 91 11 12 26 53 05 26 26 48 61 50 90 65 01 87 42 47 74 35 22 73 24 26 56 70 52 05 48 41 31 18 83 27 21 39 80 85 26 08 44 02 71 07 63 22 05 52 19 08 20 17 25 21 11 72 93 33 49 64 23 53 82 03 13 91 65 85 02 40 05 42 31 77 42 05 36 06 54 04 58 07 76 87 83 25 57 66 12 74 33 85 37 74 32 20 69 03 97 91 68 82 44 19 14 89 28 85 85 80 53 34 87 58 98 88 78 48 65 98 40 11 57 10 67 70 81 60 79 74 72 97 59 79 47 30 20 54 80 89 91 14 05 33 36 79 39 60 85 59 39 60 07 57 76 77 92 06 35 15 72 23 41 45 52 95 18 64 79 86 53 56 31 69 11 91 31 84 50 44 82 22 81 41 40 30 42 30 91 48 94 74 76 64 58 74 25 96 57 14 19 03 99 28 83 15 75 99 01 89 85 79 50 03 95 32 67 44 08 07 41 62 64 29 20 14 76 26 55 48 71 69 66 19 72 44 25 14 01 48 74 12 98 07 64 66 84 24 18 16 27 48 20 14 47 69 30 86 48 40 23 16 61 21 51 50 26 47 35 33 91 28 78 64 43 68 04 79 51 08 19 60 52 95 06 68 46 86 35 97 27 58 04 65 30 58 99 12 12 75 91 39 50 31 42 64 70 04 46 07 98 73 98 93 37 89 77 91 64 71 64 65 66 21 78 62 81 74 42 20 83 70 73 95 78 45 92 27 34 53 71 15 30 11 85 31 34 71 13 48 05 14 44 03 19 67 23 73 19 57 06 90 94 72 57 69 81 62 59 68 88 57 55 69 49 13 07 87 97 80 89 05 71 05 05 26 38 40 16 62 45 99 18 38 98 24 21 26 62 74 69 04 85 57 77 35 58 67 91 79 79 57 86 28 66 34 72 51 76 78 36 95 63 90 08 78 47 63 45 31 22 70 52 48 79 94 15 77 61 67 68 23 33 44 81 80 92 93 75 94 88 23 61 39 76 22 03 28 94 32 06 49 65 41 34 18 23 08 47 62 60 03 63 33 13 80 52 31 54 73 43 70 26 16 69 57 87 83 31 03 93 70 81 47 95 77 44 29 68 39 51 56 59 63 07 25 70 07 77 43 53 64 03 94 42 95 39 18 01 66 21 16 97 20 50 90 16 70 10 95 69 29 06 25 61 41 26 15 59 63 35
59 73 41 52 40 09 26 53 06 34 10 51 87 86 81 61 95 66 57 25 68 90 81 80 38 92 67 73 30 28 51 76 81 18 75 44 84 14 95 87 62 81 17 78 58 21 46 71 58 02 79 62 39 31 09 56 34 35 53 78 31 81 18 90 93 15 78 53 04 21 84 93 32 13 97 11 37 51 45 03 81 79 05 18 78 86 13 30 63 99 95 39 87 96 28 03 38 42 17 82 87 58 07 22 57 06 17 51 17 07 93 09 07 75 97 95 78 87 08 53 67 66 59 60 88 99 94 65 55 77 55 34 27 53 78 28 76 40 41 04 87 16 09 42 75 69 23 97 30 60 10 79 87 12 10 44 26 21 36 32 84 98 60 13 12 36 16 63 31 91 35 70 39 06 05 55 27 38 48 28 22 34 35 62 62 15 14 94 89 86 66 56 68 84 96 21 34 34 34 81 62 40 65 54 62 05 98 03 02 60 38 89 46 37 99 54 34 53 36 14 70 26 02 90 45 13 31 61 83 73 47 36 10 63 96 60 49 41 05 37 42 14 58 84 93 96 17 09 43 05 43 06 59 66 57 87 57 61 28 37 51 84 73 79 15 39 95 88 87 43 39 11 86 77 74 18 54 42 05 79 30 49 99 73 46 37 50 02 45 09 54 52 27 95 27 65 19 45 26 45 71 39 17 78 76 29 52 90 18 99 78 19 35 62 71 19 23 65 93 85 49 33 75 09 02 33 24 47 61 60 55 32 88 57 55 91 54 46 57 07 77 98 52 80 99 24 25 46 78 79 05 92 09 13 55 10 67 26 78 76 82 63 49 51 31 24 68 05 57 07 54 69 21 67 43 17 63 12 24 59 06 08 98 74 66 26 61 60 13 03 09 09 24 30 71 08 88 70 72 70 29 90 11 82 41 34 66 82 67 04 36 60 92 77 91 85 62 49 59 61 30 90 29 94 26 41 89 04 53 22 83 41 09 74 90 48 28 26 37 28 52 77 26 51 32 18 98 79 36 62 13 17 08 19 54 89 29 73 68 42 14 08 16 70 37 37 60 69 70 72 71 09 59 13 60 38 13 57 36 09 30 43 89 30 39 15 02 44 73 05 73 26 63 56 86 12 55 55 85 50 62 99 84 77 28 85 03 21 27 22 19 26 82 69 54 04 13 07 85 14 01 15 70 59 89 95 10 19 04 09 31 92 91 38 92 86 98 75 21 05 64 42 62 84 36 20 73 42 21 23 22 51 51 79 25 45 85 53 03 43 22 75 63 02 49 14 12 89 14 60 78 92 16 44 82 38 30 72 11 46 52 90 27 08 65 78 03 85 41 57 79 39 52 33 48 78 27 56 56 39 13 19 43 86 72 58 95 39 07 04 34 21 98 39 15 39 84 89 69 84 46 37 57 59 35 59 50 26 15 93 42 89 36 27 78 91 24 11 17 41 05 94 07 69 51 96 03 96 47 90 90 45 91 20 50 56 10 32 36 49 04 53 85 92 25 65 52 09 61 30 61 97 66 21 96 92 98 90 06 34 96 60 32 69 68 33 75 84 18 31 71 50 84 63 03 03 19 11 28 42 75 45 45 61 31 61 68 96 34 49 39 05 71 76 59 62 67 06 47 96 99 34 21 32 47 52 07 71 60 42 72 94 56 82 83 84 40 94 87 82 46 01 20 60 14 17 38 26 78 66 81 45 95 18 51 98 81 48 16 53 88 37 52 69 95 72 93 22 34 98 20 54 27 73 61 56 63 60 34 63 93 42 94 83 47 61 27 51 79 79 45 01 44 73 31 70 83 42 88 25 53 51 30 15 65 94 80 44 61 84 12 77 02 62 02 65 94 42 14 94 32 73 09 67 68 29 74 98 10 19 85 48 38 31 85 67 53 93 93 77 47 67 39 72 94 53 18 43 77 40 78 32 29 59 24 06 02 83 50 60 66 32 01 44 30 16 51 15 81 98 15 10 62 86 79 50 62 45 60 70 38 31 85 65 61 64 06 69 84 14 22 56 43 09 48 66 69 83 91 60 40 36 61 92 48 22 99 15 95 64 43 01 16 94 02 99 19 17 69 11 58 97 56 89 31 77 45 67 96 12 73 08 20 36 47 81 44 50 64 68 85 40 81 85 52 09 91 35 92 45 32 84 62 15 19 64 21 66 06 01 52 80 62 59 12 25 88 28 91 50 40 16 22 99 92 79 87 51 21 77 74 77 07 42 38 42 74 83 02 05 46 19 77 66 24 18 05 32 02 84 31 99 92 58 96 72 91 36 62 99 55 29 53 42 12 37 26 58 89 50 66 19 82 75 12 48 24 87 91 85 02 07 03 76 86 99 98 84 93 07 17 33 61 92 20 66 60 24 66 40 30 67 05 37 29 24 96 03 27 70 62 13 04 45 47 59 88 43 20 66 15 46 92 30 04 71 66 78 70 53 99 67 60 38 06 88 04 17 72 10 99 71 07 42 25 54 05 26 64 91 50 45 71 06 30 67 48 69 82 08 56 80 67 18 46 66 63 01 20 08 80 47 07 91 16 03 79 87 18 54 78 49 80 48 77 40 68 23 60 88 58 80 33 57 11 69 55 53 64 02 94 49 60 92 16 35 81 21 82 96 25 24 96 18 02 05 49 03 50 77 06 32 84 27 18 38 68 01 50 04 03 21 42 94 53 24 89 05 92 26 52 36 68 11 85 01 04 42 02 45 15 06 50 04 53 73 25 74 81 88 98 21 67 84 79 97 99 20 95 04 40 46 02 58 87 94 10 02 78 88 52 21 03 88 60 06 53 49 71 20 91 12 65 07 49 21 22 11 41 58 99 36 16 09 48 17 24 52 36 23 15 72 16 84 56 02 99 43 76 81 71 29 39 49 17 64 39 59 84 86 16 17 66 03 09 43 06 64 18 63 29 68 06 23 07 87 14 26 35 17 12 98 41 53 64 78 18 98 27 28 84 80 67 75 62 10 11 76 90 54 10 05 54 41 39 66 43 83 18 37 32 31 52 29 95 47 08 76 35 11 04 53 35 43 34 10 52 57 12 36 20 39 40 55 78 44 07 31 38 26 08 15 56 88 86 01 52 62 10 24 32 05 60 65 53 28 57 99 03 50 03 52 07 73 49 92 66 80 01 46 08 67 25 36 73 93 07 42 25 53 13 96 76 83 87 90 54 89 78 22 78 91 73 51 69 09 79 94 83 53 09 40 69 62 10 79 49 47 03 81 30 71 54 73 33 51 76 59 54 79 37 56 45 84 17 62 21 98 69 41 95 65 24 39 37 62 03 24 48 54 64 46 82 71 78 33 67 09 16 96 68 52 74 79 68 32 21 13 78 96 60 09 69 20 36 73 26 21 44 46 38 17 83 65 98 07 23 52 46 61 97 33 13 60 31 70 15 36 77 31 58 56 93 75 68 21 36 69 53 90 75 25 82 39 50 65 94 29 30 11 33 11 13 96 02 56 47 07 49 02 76 46 73 30 10 20 60 70 14 56 34 26 37 39 48 24 55 76 84 91 39 86 95 61 50 14 53 93 64 67 37 31 10 84 42 70 48 20 10 72 60 61 84 79 69 65 99 73 89 25 85 48 92 56 97 16 03 14 80 27 22 30 44 27 67 75 79 32 51 54 81 29 65 14 19 04 13 82 04 91 43 40 12 52 29 99 07 76 60 25 01 07 61 71 37 92 40 47 99 66 57 01 43 44 22 40 53 53 09 69 26 81 07 49 80 56 90 93 87 47 13 75 28 87 23 72 79 32 18 27 20 28 10 37 59 21 18 70 04 79 96 03 31 45 71 81 06 14 18 17 05 31 50 92 79 23 47 09 39 47 91 43 54 69 47 42 95 62 46 32 85 37 18 62 85 87 28 64 05 77 51 47 26 30 65 05 70 65 75 59 80 42 52 25 20 44 10 92 17 71 95 52 14 77 13 24 55 11 65 26 91 01 30 63 15 49 48 41 17 67 47 03 68 20 90 98 32 04 40 68 90 51 58 60 06 55 23 68 05 19 76 94 82 36 96 43 38 90 87 28 33 83 05 17 70 83 96 93 06 04 78 47 80 06 23 84 75 23 87 72 99 14 50 98 92 38 90 64 61 58 76 94 36 66 87 80 51 35 61 38 57 95 64 06 53 36 82 51 40 33 47 14 07 98 78 65 39 58 53 06 50 53 04 69 40 68 36 69 75 78 75 60 03 32 39 24 74 47 26 90 13 40 44 71 90 76 51 24 36 50 25 45 70 80 61 80 61 43 90 64 11 18 29 86 56 68 42 79 10 42 44 30 12 96 18 23 18 52 59 02 99 67 46 60 86 43 38 55 17 44 93 42 21 55 14 47 34 55 16 49 24 23 29 96 51 55 10 46 53 27 92 27 46 63 57 30 65 43 27 21 20 24 83 81 72 93 19 69 52 48 01 13 83 92 69 20 48 69 59 20 62 05 42 28 89 90 99 32 72 84 17 08 87 36 03 60 31 36 36 81 26 97 36 48 54 56 56 27 16 91 08 23 11 87 99 33 47 02 14 44 73 70 99 43 35 33 90 56 61 86 56 12 70 59 63 32 01 15 81 47 71 76 95 32 65 80 54 70 34 51 40 45 33 04 64 55 78 68 88 47 31 47 68 87 03 84 23 44 89 72 35 08 31 76 63 26 90 85 96 67 65 91 19 14 17 86 04 71 32 95 37 13 04 22 64 37 37 28 56 62 86 33 07 37 10 44 52 82 52 06 19 52 57 75 90 26 91 24 06 21 14 67 76 30 46 14 35 89 89 41 03 64 56 97 87 63 22 34 03 79 17 45 11 53 25 56 96 61 23 18 63 31 37 37 47 77 23 26 70 72 76 77 04 28 64 71 69 14 85 96 54 95 48 06 62 99 83 86 77 97 75 71 66 30 19 57 90 33 01 60 61 14 12 90 99 32 77 56 41 18 14 87 49 10 14 90 64 18 50 21 74 14 16 88 05 45 73 82 47 74 44 22 97 41 13 34 31 54 61 56 94 03 24 59 27 98 77 04 09 37 40 12 26 87 09 71 70 07 18 64 57 80 21 12 71 83 94 60 39 73 79 73 19 97 32 64 29 41 07 48 84 85 67 12 74 95 20 24 52 41 67 56 61 29 93 35 72 69 72 23 63 66 01 11 07 30 52 56 95 16 65 26 83 90 50 74 60 18 16 48 43 77 37 11 99 98 30 94 91 26 62 73 45 12 87 73 47 27 01 88 66 99 21 41 95 80 02 53 23 32 61 48 32 43 43 83 14 66 95 91 19 81 80 67 25 88 08 62 32 18 92 14 83 71 37 96 11 83 39 99 05 16 23 27 10 67 02 25 44 11 55 31 46 64 41 56 44 74 26 81 51 31 45 85 87 09 81 95 22 28 76 69 46 48 64 87 67 76 27 89 31 11 74 16 62 03 60 94 42 47 09 34 94 93 72 56 18 90 18 42 17 42 32 14 86 06 53 33 95 99 35 29 15 44 20 49 59 25 54 34 59 84 21 23 54 35 90 78 16 93 13 37 88 54 19 86 67 68 55 66 84 65 42 98 37 87 56 33 28 58 38 28 38 66 27 52 21 81 15 08 22 97 32 85 27 91 53 40 28 13 34 91 25 01 63 50 37 22 49 71 58 32 28 30 18 68 94 23 83 63 62 94 76 80 41 90 22 82 52 29 12 18 56 10 08 35 14 37 57 23 65 67 40 72 39 93 39 70 89 40 34 07 46 94 22 20 05 53 64 56 30 05 56 61 88 27 23 95 11 12 37 69 68 24 66 10 87 70 43 50 75 07 62 41 83 58 95 93 89 79 45 39 02 22 05 22 95 43 62 11 68 29 17 40 26 44 25 71 87 16 70 85 19 25 59 94 90 41 41 80 61 70 55 60 84 33 95 76 42 63 15 09 03 40 38 12 03 32 09 84 56 80 61 55 85 97 16 94 82 94 98 57 84 30 84 48 93 90 71 05 95 90 73 17 30 98 40 64 65 89 07 79 09 19 56 36 42 30 23 69 73 72 07 05 27 61 24 31 43 48 71 84 21 28 26 65 65 59 65 74 77 20 10 81 61 84 95 08 52 23 70 47 81 28 09 98 51 67 64 35 51 59 36 92 82 77 65 80 24 72 53 22 07 27 10 21 28 30 22 48 82 80 48 56 20 14 43 18 25 50 95 90 31 77 08 09 48 44 80 90 22 93 45 82 17 13 96 25 26 08 73 34 99 06 49 24 06 83 51 40 14 15 10 25 01 54 25 10 81 30 64 24 74 75 80 36 75 82 60 22 69 72 91 45 67 03 62 79 54 89 74 44 83 64 96 66 73 44 30 74 50 37 05 09 97 70 01 60 46 37 91 39 75 75 18 58 52 72 78 51 81 86 52 08 97 01 46 43 66 98 62 81 18 70 93 73 08 32 46 34 96 80 82 07 59 71 92 53 19 20 88 66 03 26 26 10 24 27 50 82 94 73 63 08 51 33 22 45 19 13 58 33 90 15 22 50 36 13 55 06 35 47 82 52 33 61 36 27 28 46 98 14 73 20 73 32 16 26 80 53 47 66 76 38 94 45 02 01 22 52 47 96 64 58 52 39 88 46 23 39 74 63 81 64 20 90 33 33 76 55 58 26 10 46 42 26 74 74 12 83 32 43 09 02 73 55 86 54 85 34 28 23 29 79 91 62 47 41 82 87 99 22 48 90 20 05 96 75 95 04 43 28 81 39 81 01 28 42 78 25 39 77 90 57 58 98 17 36 73 22 63 74 51 29 39 74 94 95 78 64 24 38 86 63 87 93 06 70 92 22 16 80 64 29 52 20 27 23 50 14 13 87 15 72 96 81 22 08 49 72 30 70 24 79 31 16 64 59 21 89 34 96 91 48 76 43 53 88 01 57 80 23 81 90 79 58 01 80 87 17 99 86 90 72 63 32 69 14 28 88 69 37 17 71 95 56 93 71 35 43 45 04 98 92 94 84 96 11 30 31 27 31 60 92 03 48 05 98 91 86 94 35 90 90 08 48 19 33 28 68 37 59 26 65 96 50 68 22 07 09 49 34 31 77 49 43 06 75 17 81 87 61 79 52 26 27 72 29 50 07 98 86 01 17 10 46 64 24 18 56 51 30 25 94 88 85 79 91 40 33 63 84 49 67 98 92 15 26 75 19 82 05 18 78 65 93 61 48 91 43 59 41 70 51 22 15 92 81 67 91 46 98 11 11 65 31 66 10 98 65 83 21 05 56 05 98 73 67 46 74 69 34 08 30 05 52 07 98 32 95 30 94 65 50 24 63 28 81 99 57 19 23 61 36 09 89 71 98 65 17 30 29 89 26 79 74 94 11 44 48 97 54 81 55 39 66 69 45 28 47 13 86 15 76 74 70 84 32 36 33 79 20 78 14 41 47 89 28 81 05 99 66 81 86 38 26 06 25 13 60 54 55 23 53 27 05 89 25 23 11 13 54 59 54 56 34 16 24 53 44 06 13 40 57 72 21 15 60 08 04 19 11 98 34 45 09 97 86 71 03 15 56 19 15 44 97 31 90 04 87 87 76 08 12 30 24 62 84 28 12 85 82 53 99 52 13 94 06 65 97 86 09 50 94 68 69 74 30 67 87 94 63 07 78 27 80 36 69 41 06 92 32 78 37 82 30 05 18 87 99 72 19 99 44 20 55 77 69 91 27 31 28 81 80 27 02 07 97 23 95 98 12 25 75 29 47 71 07 47 78 39 41 59 27 76 13 15 66 61 68 35 69 86 16 53 67 63 99 85 41 56 08 28 33 40 94 76 90 85 31 70 24 65 84 65 99 82 19 25 54 37 21 46 33 02 52 99 51 33 26 04 87 02 08 18 96 54 42 61 45 91 06 64 79 80 82 32 16 83 63 42 49 19 78 65 97 40 42 14 61 49 34 04 18 25 98 59 30 82 72 26 88 54 36 21 75 03 88 99 53 46 51 55 78 22 94 34 40 68 87 84 25 30 76 25 08 92 84 42 61 40 38 09 99 40 23 29 39 46 55 10 90 35 84 56 70 63 23 91 39 52 92 03 71 89 07 09 37 68 66 58 20 44 92 51 56 13 71 79 99 26 37 02 06 16 67 36 52 58 16 79 73 56 60 59 27 44 77 94 82 20 50 98 33 09 87 94 37 40 83 64 83 58 85 17 76 53 02 83 52 22 27 39 20 48 92 45 21 09 42 24 23 12 37 52 28 50 78 79 20 86 62 73 20 59 54 96 80 15 91 90 99 70 10 09 58 90 93 50 81 99 54 38 36 10 30 11 35 84 16 45 82 18 11 97 36 43 96 79 97 65 40 48 23 19 17 31 64 52 65 65 37 32 65 76 99 79 34 65 79 27 55 33 03 01 33 27 61 28 66 08 04 70 49 46 48 83 01 45 19 96 13 81 14 21 31 79 93 85 50 05 92 92 48 84 59 98 31 53 23 27 15 22 79 95 24 76 05 79 16 93 97 89 38 89 42 83 02 88 94 95 82 21 01 97 48 39 31 78 09 65 50 56 97 61 01 07 65 27 21 23 14 15 80 97 44 78 49 35 33 45 81 74 34 05 31 57 09 38 94 07 69 54 69 32 65 68 46 68 78 90 24 28 49 51 45 86 35 41 63 89 76 87 31 86 09 46 14 87 82 22 29 47 16 13 10 70 72 82 95 48 64 58 43 13 75 42 69 21 12 67 13 64 85 58 23 98 09 37 76 05 22 31 12 66 50 29 99 86 72 45 25 10 28 19 06 90 43 29 31 67 79 46 25 74 14 97 35 76 37 65 46 23 82 06 22 30 76 93 66 94 17 96 13 20 72 63 40 78 08 52 09 90 41 70 28 36 14 46 44 85 96 24 52 58 15 87 37 05 98 99 39 13 61 76 38 44 99 83 74 90 22 53 80 56 98 30 51 63 39 44 30 91 91 04 22 27 73 17 35 53 18 35 45 54 56 27 78 48 13 69 36 44 38 71 25 30 56 15 22 73 43 32 69 59 25 93 83 45 11 34 94 44 39 92 12 36 56 88 13 96 16 12 55 54 11 47 19 78 17 17 68 81 77 51 42 55 99 85 66 27 81 79 93 42 65 61 69 74 14 01 18 56 12 01 58 37 91 22 42 66 83 25 19 04 96 41 25 45 18 69 96 88 36 93 10 12 98 32 44 83 83 04 72 91 04 27 73 07 34 37 71 60 59 31 01 54 54 44 96 93 83 36 04 45 30 18 22 20 42 96 65 79 17 41 55 69 94 81 29 80 91 31 85 25 47 26 43 49 02 99 34 67 99 76 16 14 15 93 08 32 99 44 61 77 67 50 43 55 87 55 53 72 17 46 62 25 50 99 73 05 93 48 17 31 70 80 59 09 44 59 45 13 74 66 58 94 87 73 16 14 85 38 74 99 64 23 79 28 71 42 20 37 82 31 23 51 96 39 65 46 71 56 13 29 68 53 86 45 33 51 49 12 91 21 21 76 85 02 17 98 15 46 12 60 21 88 30 92 83 44 59 42 50 27 88 46 86 94 73 45 54 23 24 14 10 94 21 20 34 23 51 04 83 99 75 90 63 60 16 22 33 83 70 11 32 10 50 29 30 83 46 11 05 31 17 86 42 49 01 44 63 28 60 07 78 95 40 44 61 89 59 04 49 51 27 69 71 46 76 44 04 09 34 56 39 15 06 94 91 75 90 65 27 56 23 74 06 23 33 36 69 14 39 05 34 35 57 33 22 76 46 56 10 61 65 98 09 16 69 04 62 65 18 99 76 49 18 72 66 73 83 82 40 76 31 89 91 27 88 17 35 41 35 32 51 32 67 52 68 74 85 80 57 07 11 62 66 47 22 67 65 37 19 97 26 17 16 24 24 17 50 37 64 82 24 36 32 11 68 34 69 31 32 89 79 93 96 68 49 90 14 23 04 04 67 99 81 74 70 74 36 96 68 09 64 39 88 35 54 89 96 58 66 27 88 97 32 14 06 35 78 20 71 06 85 66 57 02 58 91 72 05 29 56 73 48 86 52 09 93 22 57 79 42 12 01 31 68 17 59 63 76 07 77 73 81 14 13 17 20 11 09 01 83 08 85 91 70 84 63 62 77 37 07 47 01 59 95 39 69 39 21 99 09 87 02 97 16 92 36 74 71 90 66 33 73 73 75 52 91 11 12 26 53 05 26 26 48 61 50 90 65 01 87 42 47 74 35 22 73 24 26 56 70 52 05 48 41 31 18 83 27 21 39 80 85 26 08 44 02 71 07 63 22 05 52 19 08 20 17 25 21 11 72 93 33 49 64 23 53 82 03 13 91 65 85 02 40 05 42 31 77 42 05 36 06 54 04 58 07 76 87 83 25 57 66 12 74 33 85 37 74 32 20 69 03 97 91 68 82 44 19 14 89 28 85 85 80 53 34 87 58 98 88 78 48 65 98 40 11 57 10 67 70 81 60 79 74 72 97 59 79 47 30 20 54 80 89 91 14 05 33 36 79 39 60 85 59 39 60 07 57 76 77 92 06 35 15 72 23 41 45 52 95 18 64 79 86 53 56 31 69 11 91 31 84 50 44 82 22 81 41 40 30 42 30 91 48 94 74 76 64 58 74 25 96 57 14 19 03 99 28 83 15 75 99 01 89 85 79 50 03 95 32 67 44 08 07 41 62 64 29 20 14 76 26 55 48 71 69 66 19 72 44 25 14 01 48 74 12 98 07 64 66 84 24 18 16 27 48 20 14 47 69 30 86 48 40 23 16 61 21 51 50 26 47 35 33 91 28 78 64 43 68 04 79 51 08 19 60 52 95 06 68 46 86 35 97 27 58 04 65 30 58 99 12 12 75 91 39 50 31 42 64 70 04 46 07 98 73 98 93 37 89 77 91 64 71 64 65 66 21 78 62 81 74 42 20 83 70 73 95 78 45 92 27 34 53 71 15 30 11 85 31 34 71 13 48 05 14 44 03 19 67 23 73 19 57 06 90 94 72 57 69 81 62 59 68 88 57 55 69 49 13 07 87 97 80 89 05 71 05 05 26 38 40 16 62 45 99 18 38 98 24 21 26 62 74 69 04 85 57 77 35 58 67 91 79 79 57 86 28 66 34 72 51 76 78 36 95 63 90 08 78 47 63 45 31 22 70 52 48 79 94 15 77 61 67 68 23 33 44 81 80 92 93 75 94 88 23 61 39 76 22 03 28 94 32 06 49 65 41 34 18 23 08 47 62 60 03 63 33 13 80 52 31 54 73 43 70 26 16 69 57 87 83 31 03 93 70 81 47 95 77 44 29 68 39 51 56 59 63 07 25 70 07 77 43 53 64 03 94 42 95 39 18 01 66 21 16 97 20 50 90 16 70 10 95 69 29 06 25 61 41 26 15 59 63 35
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" You have m types of coins available in infinite quantities where the value of each coins is given in the array S=[S0,... Sm-1] Can you determine number of ways of making change for n units using the given types of coins? https://www.hackerrank.com/challenges/coin-change/problem """ def dp_count(s, n): """ >>> dp_count([1, 2, 3], 4) 4 >>> dp_count([1, 2, 3], 7) 8 >>> dp_count([2, 5, 3, 6], 10) 5 >>> dp_count([10], 99) 0 >>> dp_count([4, 5, 6], 0) 1 >>> dp_count([1, 2, 3], -5) 0 """ if n < 0: return 0 # table[i] represents the number of ways to get to amount i table = [0] * (n + 1) # There is exactly 1 way to get to zero(You pick no coins). table[0] = 1 # Pick all coins one by one and update table[] values # after the index greater than or equal to the value of the # picked coin for coin_val in s: for j in range(coin_val, n + 1): table[j] += table[j - coin_val] return table[n] if __name__ == "__main__": import doctest doctest.testmod()
""" You have m types of coins available in infinite quantities where the value of each coins is given in the array S=[S0,... Sm-1] Can you determine number of ways of making change for n units using the given types of coins? https://www.hackerrank.com/challenges/coin-change/problem """ def dp_count(s, n): """ >>> dp_count([1, 2, 3], 4) 4 >>> dp_count([1, 2, 3], 7) 8 >>> dp_count([2, 5, 3, 6], 10) 5 >>> dp_count([10], 99) 0 >>> dp_count([4, 5, 6], 0) 1 >>> dp_count([1, 2, 3], -5) 0 """ if n < 0: return 0 # table[i] represents the number of ways to get to amount i table = [0] * (n + 1) # There is exactly 1 way to get to zero(You pick no coins). table[0] = 1 # Pick all coins one by one and update table[] values # after the index greater than or equal to the value of the # picked coin for coin_val in s: for j in range(coin_val, n + 1): table[j] += table[j - coin_val] return table[n] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. # # To enable this hook, rename this file to "pre-commit". if git rev-parse --verify HEAD >/dev/null 2>&1 then against=HEAD else # Initial commit: diff against an empty tree object against=$(git hash-object -t tree /dev/null) fi # If you want to allow non-ASCII filenames set this variable to true. allownonascii=$(git config --bool hooks.allownonascii) # Redirect output to stderr. exec 1>&2 # Cross platform projects tend to avoid non-ASCII filenames; prevent # them from being added to the repository. We exploit the fact that the # printable range starts at the space character and ends with tilde. if [ "$allownonascii" != "true" ] && # Note that the use of brackets around a tr range is ok here, (it's # even required, for portability to Solaris 10's /usr/bin/tr), since # the square bracket bytes happen to fall in the designated range. test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 then cat <<\EOF Error: Attempt to add a non-ASCII file name. This can cause problems if you want to work with people on other platforms. To be portable it is advisable to rename the file. If you know what you are doing you can disable this check using: git config hooks.allownonascii true EOF exit 1 fi # If there are whitespace errors, print the offending file names and fail. exec git diff-index --check --cached $against --
#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. # # To enable this hook, rename this file to "pre-commit". if git rev-parse --verify HEAD >/dev/null 2>&1 then against=HEAD else # Initial commit: diff against an empty tree object against=$(git hash-object -t tree /dev/null) fi # If you want to allow non-ASCII filenames set this variable to true. allownonascii=$(git config --bool hooks.allownonascii) # Redirect output to stderr. exec 1>&2 # Cross platform projects tend to avoid non-ASCII filenames; prevent # them from being added to the repository. We exploit the fact that the # printable range starts at the space character and ends with tilde. if [ "$allownonascii" != "true" ] && # Note that the use of brackets around a tr range is ok here, (it's # even required, for portability to Solaris 10's /usr/bin/tr), since # the square bracket bytes happen to fall in the designated range. test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 then cat <<\EOF Error: Attempt to add a non-ASCII file name. This can cause problems if you want to work with people on other platforms. To be portable it is advisable to rename the file. If you know what you are doing you can disable this check using: git config hooks.allownonascii true EOF exit 1 fi # If there are whitespace errors, print the offending file names and fail. exec git diff-index --check --cached $against --
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Multiply two numbers using Karatsuba algorithm """ def karatsuba(a, b): """ >>> karatsuba(15463, 23489) == 15463 * 23489 True >>> karatsuba(3, 9) == 3 * 9 True """ if len(str(a)) == 1 or len(str(b)) == 1: return a * b else: m1 = max(len(str(a)), len(str(b))) m2 = m1 // 2 a1, a2 = divmod(a, 10**m2) b1, b2 = divmod(b, 10**m2) x = karatsuba(a2, b2) y = karatsuba((a1 + a2), (b1 + b2)) z = karatsuba(a1, b1) return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) def main(): print(karatsuba(15463, 23489)) if __name__ == "__main__": main()
""" Multiply two numbers using Karatsuba algorithm """ def karatsuba(a, b): """ >>> karatsuba(15463, 23489) == 15463 * 23489 True >>> karatsuba(3, 9) == 3 * 9 True """ if len(str(a)) == 1 or len(str(b)) == 1: return a * b else: m1 = max(len(str(a)), len(str(b))) m2 = m1 // 2 a1, a2 = divmod(a, 10**m2) b1, b2 = divmod(b, 10**m2) x = karatsuba(a2, b2) y = karatsuba((a1 + a2), (b1 + b2)) z = karatsuba(a1, b1) return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) def main(): print(karatsuba(15463, 23489)) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 multiplicative_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> multiplicative_persistence(217) 2 >>> multiplicative_persistence(-1) Traceback (most recent call last): ... ValueError: multiplicative_persistence() does not accept negative values >>> multiplicative_persistence("long number") Traceback (most recent call last): ... ValueError: multiplicative_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("multiplicative_persistence() only accepts integral values") if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 1 for i in range(0, len(numbers)): total *= numbers[i] num_string = str(total) steps += 1 return steps def additive_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> additive_persistence(199) 3 >>> additive_persistence(-1) Traceback (most recent call last): ... ValueError: additive_persistence() does not accept negative values >>> additive_persistence("long number") Traceback (most recent call last): ... ValueError: additive_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("additive_persistence() only accepts integral values") if num < 0: raise ValueError("additive_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 0 for i in range(0, len(numbers)): total += numbers[i] num_string = str(total) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
def multiplicative_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> multiplicative_persistence(217) 2 >>> multiplicative_persistence(-1) Traceback (most recent call last): ... ValueError: multiplicative_persistence() does not accept negative values >>> multiplicative_persistence("long number") Traceback (most recent call last): ... ValueError: multiplicative_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("multiplicative_persistence() only accepts integral values") if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 1 for i in range(0, len(numbers)): total *= numbers[i] num_string = str(total) steps += 1 return steps def additive_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> additive_persistence(199) 3 >>> additive_persistence(-1) Traceback (most recent call last): ... ValueError: additive_persistence() does not accept negative values >>> additive_persistence("long number") Traceback (most recent call last): ... ValueError: additive_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("additive_persistence() only accepts integral values") if num < 0: raise ValueError("additive_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 0 for i in range(0, len(numbers)): total += numbers[i] num_string = str(total) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. """ from __future__ import annotations def two_sum(nums: list[int], target: int) -> list[int]: """ >>> two_sum([2, 7, 11, 15], 9) [0, 1] >>> two_sum([15, 2, 11, 7], 13) [1, 2] >>> two_sum([2, 7, 11, 15], 17) [0, 3] >>> two_sum([7, 15, 11, 2], 18) [0, 2] >>> two_sum([2, 7, 11, 15], 26) [2, 3] >>> two_sum([2, 7, 11, 15], 8) [] >>> two_sum([3 * i for i in range(10)], 19) [] """ chk_map: dict[int, int] = {} for index, val in enumerate(nums): compl = target - val if compl in chk_map: return [chk_map[compl], index] chk_map[val] = index return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"{two_sum([2, 7, 11, 15], 9) = }")
""" Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. """ from __future__ import annotations def two_sum(nums: list[int], target: int) -> list[int]: """ >>> two_sum([2, 7, 11, 15], 9) [0, 1] >>> two_sum([15, 2, 11, 7], 13) [1, 2] >>> two_sum([2, 7, 11, 15], 17) [0, 3] >>> two_sum([7, 15, 11, 2], 18) [0, 2] >>> two_sum([2, 7, 11, 15], 26) [2, 3] >>> two_sum([2, 7, 11, 15], 8) [] >>> two_sum([3 * i for i in range(10)], 19) [] """ chk_map: dict[int, int] = {} for index, val in enumerate(nums): compl = target - val if compl in chk_map: return [chk_map[compl], index] chk_map[val] = index return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"{two_sum([2, 7, 11, 15], 9) = }")
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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/Burrows%E2%80%93Wheeler_transform The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data except the position of the first original character. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. """ from __future__ import annotations from typing import TypedDict class BWTTransformDict(TypedDict): bwt_string: str idx_original_string: int def all_rotations(s: str) -> list[str]: """ :param s: The string that will be rotated len(s) times. :return: A list with the rotations. :raises TypeError: If s is not an instance of str. Examples: >>> all_rotations("^BANANA|") # doctest: +NORMALIZE_WHITESPACE ['^BANANA|', 'BANANA|^', 'ANANA|^B', 'NANA|^BA', 'ANA|^BAN', 'NA|^BANA', 'A|^BANAN', '|^BANANA'] >>> all_rotations("a_asa_da_casa") # doctest: +NORMALIZE_WHITESPACE ['a_asa_da_casa', '_asa_da_casaa', 'asa_da_casaa_', 'sa_da_casaa_a', 'a_da_casaa_as', '_da_casaa_asa', 'da_casaa_asa_', 'a_casaa_asa_d', '_casaa_asa_da', 'casaa_asa_da_', 'asaa_asa_da_c', 'saa_asa_da_ca', 'aa_asa_da_cas'] >>> all_rotations("panamabanana") # doctest: +NORMALIZE_WHITESPACE ['panamabanana', 'anamabananap', 'namabananapa', 'amabananapan', 'mabananapana', 'abananapanam', 'bananapanama', 'ananapanamab', 'nanapanamaba', 'anapanamaban', 'napanamabana', 'apanamabanan'] >>> all_rotations(5) Traceback (most recent call last): ... TypeError: The parameter s type must be str. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") return [s[i:] + s[:i] for i in range(len(s))] def bwt_transform(s: str) -> BWTTransformDict: """ :param s: The string that will be used at bwt algorithm :return: the string composed of the last char of each row of the ordered rotations and the index of the original string at ordered rotations list :raises TypeError: If the s parameter type is not str :raises ValueError: If the s parameter is empty Examples: >>> bwt_transform("^BANANA") {'bwt_string': 'BNN^AAA', 'idx_original_string': 6} >>> bwt_transform("a_asa_da_casa") {'bwt_string': 'aaaadss_c__aa', 'idx_original_string': 3} >>> bwt_transform("panamabanana") {'bwt_string': 'mnpbnnaaaaaa', 'idx_original_string': 11} >>> bwt_transform(4) Traceback (most recent call last): ... TypeError: The parameter s type must be str. >>> bwt_transform('') Traceback (most recent call last): ... ValueError: The parameter s must not be empty. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") if not s: raise ValueError("The parameter s must not be empty.") rotations = all_rotations(s) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation response: BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations]), "idx_original_string": rotations.index(s), } return response def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: """ :param bwt_string: The string returned from bwt algorithm execution :param idx_original_string: A 0-based index of the string that was used to generate bwt_string at ordered rotations list :return: The string used to generate bwt_string when bwt was executed :raises TypeError: If the bwt_string parameter type is not str :raises ValueError: If the bwt_string parameter is empty :raises TypeError: If the idx_original_string type is not int or if not possible to cast it to int :raises ValueError: If the idx_original_string value is lower than 0 or greater than len(bwt_string) - 1 >>> reverse_bwt("BNN^AAA", 6) '^BANANA' >>> reverse_bwt("aaaadss_c__aa", 3) 'a_asa_da_casa' >>> reverse_bwt("mnpbnnaaaaaa", 11) 'panamabanana' >>> reverse_bwt(4, 11) Traceback (most recent call last): ... TypeError: The parameter bwt_string type must be str. >>> reverse_bwt("", 11) Traceback (most recent call last): ... ValueError: The parameter bwt_string must not be empty. >>> reverse_bwt("mnpbnnaaaaaa", "asd") # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: The parameter idx_original_string type must be int or passive of cast to int. >>> reverse_bwt("mnpbnnaaaaaa", -1) Traceback (most recent call last): ... ValueError: The parameter idx_original_string must not be lower than 0. >>> reverse_bwt("mnpbnnaaaaaa", 12) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: The parameter idx_original_string must be lower than len(bwt_string). >>> reverse_bwt("mnpbnnaaaaaa", 11.0) 'panamabanana' >>> reverse_bwt("mnpbnnaaaaaa", 11.4) 'panamabanana' """ if not isinstance(bwt_string, str): raise TypeError("The parameter bwt_string type must be str.") if not bwt_string: raise ValueError("The parameter bwt_string must not be empty.") try: idx_original_string = int(idx_original_string) except ValueError: raise TypeError( "The parameter idx_original_string type must be int or passive" " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0.") if idx_original_string >= len(bwt_string): raise ValueError( "The parameter idx_original_string must be lower than" " len(bwt_string)." ) ordered_rotations = [""] * len(bwt_string) for _ in range(len(bwt_string)): for i in range(len(bwt_string)): ordered_rotations[i] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": entry_msg = "Provide a string that I will generate its BWT transform: " s = input(entry_msg).strip() result = bwt_transform(s) print( f"Burrows Wheeler transform for string '{s}' results " f"in '{result['bwt_string']}'" ) original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"]) print( f"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " f"we get original string '{original_string}'" )
""" https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data except the position of the first original character. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. """ from __future__ import annotations from typing import TypedDict class BWTTransformDict(TypedDict): bwt_string: str idx_original_string: int def all_rotations(s: str) -> list[str]: """ :param s: The string that will be rotated len(s) times. :return: A list with the rotations. :raises TypeError: If s is not an instance of str. Examples: >>> all_rotations("^BANANA|") # doctest: +NORMALIZE_WHITESPACE ['^BANANA|', 'BANANA|^', 'ANANA|^B', 'NANA|^BA', 'ANA|^BAN', 'NA|^BANA', 'A|^BANAN', '|^BANANA'] >>> all_rotations("a_asa_da_casa") # doctest: +NORMALIZE_WHITESPACE ['a_asa_da_casa', '_asa_da_casaa', 'asa_da_casaa_', 'sa_da_casaa_a', 'a_da_casaa_as', '_da_casaa_asa', 'da_casaa_asa_', 'a_casaa_asa_d', '_casaa_asa_da', 'casaa_asa_da_', 'asaa_asa_da_c', 'saa_asa_da_ca', 'aa_asa_da_cas'] >>> all_rotations("panamabanana") # doctest: +NORMALIZE_WHITESPACE ['panamabanana', 'anamabananap', 'namabananapa', 'amabananapan', 'mabananapana', 'abananapanam', 'bananapanama', 'ananapanamab', 'nanapanamaba', 'anapanamaban', 'napanamabana', 'apanamabanan'] >>> all_rotations(5) Traceback (most recent call last): ... TypeError: The parameter s type must be str. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") return [s[i:] + s[:i] for i in range(len(s))] def bwt_transform(s: str) -> BWTTransformDict: """ :param s: The string that will be used at bwt algorithm :return: the string composed of the last char of each row of the ordered rotations and the index of the original string at ordered rotations list :raises TypeError: If the s parameter type is not str :raises ValueError: If the s parameter is empty Examples: >>> bwt_transform("^BANANA") {'bwt_string': 'BNN^AAA', 'idx_original_string': 6} >>> bwt_transform("a_asa_da_casa") {'bwt_string': 'aaaadss_c__aa', 'idx_original_string': 3} >>> bwt_transform("panamabanana") {'bwt_string': 'mnpbnnaaaaaa', 'idx_original_string': 11} >>> bwt_transform(4) Traceback (most recent call last): ... TypeError: The parameter s type must be str. >>> bwt_transform('') Traceback (most recent call last): ... ValueError: The parameter s must not be empty. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") if not s: raise ValueError("The parameter s must not be empty.") rotations = all_rotations(s) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation response: BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations]), "idx_original_string": rotations.index(s), } return response def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: """ :param bwt_string: The string returned from bwt algorithm execution :param idx_original_string: A 0-based index of the string that was used to generate bwt_string at ordered rotations list :return: The string used to generate bwt_string when bwt was executed :raises TypeError: If the bwt_string parameter type is not str :raises ValueError: If the bwt_string parameter is empty :raises TypeError: If the idx_original_string type is not int or if not possible to cast it to int :raises ValueError: If the idx_original_string value is lower than 0 or greater than len(bwt_string) - 1 >>> reverse_bwt("BNN^AAA", 6) '^BANANA' >>> reverse_bwt("aaaadss_c__aa", 3) 'a_asa_da_casa' >>> reverse_bwt("mnpbnnaaaaaa", 11) 'panamabanana' >>> reverse_bwt(4, 11) Traceback (most recent call last): ... TypeError: The parameter bwt_string type must be str. >>> reverse_bwt("", 11) Traceback (most recent call last): ... ValueError: The parameter bwt_string must not be empty. >>> reverse_bwt("mnpbnnaaaaaa", "asd") # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: The parameter idx_original_string type must be int or passive of cast to int. >>> reverse_bwt("mnpbnnaaaaaa", -1) Traceback (most recent call last): ... ValueError: The parameter idx_original_string must not be lower than 0. >>> reverse_bwt("mnpbnnaaaaaa", 12) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: The parameter idx_original_string must be lower than len(bwt_string). >>> reverse_bwt("mnpbnnaaaaaa", 11.0) 'panamabanana' >>> reverse_bwt("mnpbnnaaaaaa", 11.4) 'panamabanana' """ if not isinstance(bwt_string, str): raise TypeError("The parameter bwt_string type must be str.") if not bwt_string: raise ValueError("The parameter bwt_string must not be empty.") try: idx_original_string = int(idx_original_string) except ValueError: raise TypeError( "The parameter idx_original_string type must be int or passive" " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0.") if idx_original_string >= len(bwt_string): raise ValueError( "The parameter idx_original_string must be lower than" " len(bwt_string)." ) ordered_rotations = [""] * len(bwt_string) for _ in range(len(bwt_string)): for i in range(len(bwt_string)): ordered_rotations[i] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": entry_msg = "Provide a string that I will generate its BWT transform: " s = input(entry_msg).strip() result = bwt_transform(s) print( f"Burrows Wheeler transform for string '{s}' results " f"in '{result['bwt_string']}'" ) original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"]) print( f"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " f"we get original string '{original_string}'" )
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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_1s_count(number: int) -> int: """ Count the number of set bits in a 32 bit integer using Brian Kernighan's way. Ref - http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan >>> get_1s_count(25) 3 >>> get_1s_count(37) 3 >>> get_1s_count(21) 3 >>> get_1s_count(58) 4 >>> get_1s_count(0) 0 >>> get_1s_count(256) 1 >>> get_1s_count(-1) Traceback (most recent call last): ... ValueError: the value of input must be positive >>> get_1s_count(0.8) Traceback (most recent call last): ... TypeError: Input value must be an 'int' type """ if number < 0: raise ValueError("the value of input must be positive") elif isinstance(number, float): raise TypeError("Input value must be an 'int' type") count = 0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
def get_1s_count(number: int) -> int: """ Count the number of set bits in a 32 bit integer using Brian Kernighan's way. Ref - http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan >>> get_1s_count(25) 3 >>> get_1s_count(37) 3 >>> get_1s_count(21) 3 >>> get_1s_count(58) 4 >>> get_1s_count(0) 0 >>> get_1s_count(256) 1 >>> get_1s_count(-1) Traceback (most recent call last): ... ValueError: the value of input must be positive >>> get_1s_count(0.8) Traceback (most recent call last): ... TypeError: Input value must be an 'int' type """ if number < 0: raise ValueError("the value of input must be positive") elif isinstance(number, float): raise TypeError("Input value must be an 'int' type") count = 0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tasks: - init: pip3 install -r ./requirements.txt
tasks: - init: pip3 install -r ./requirements.txt
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Numbers of alphabet which we call base alphabet_size = 256 # Modulus to hash a string modulus = 1000003 def rabin_karp(pattern: str, text: str) -> bool: """ The Rabin-Karp Algorithm for finding a pattern within a piece of text with complexity O(nm), most efficient when it is used with multiple patterns as it is able to check if any of a set of patterns match a section of text in o(1) given the precomputed hashes. This will be the simple version which only assumes one pattern is being searched for but it's not hard to modify 1) Calculate pattern hash 2) Step through the text one character at a time passing a window with the same length as the pattern calculating the hash of the text within the window compare it with the hash of the pattern. Only testing equality if the hashes match """ p_len = len(pattern) t_len = len(text) if p_len > t_len: return False p_hash = 0 text_hash = 0 modulus_power = 1 # Calculating the hash of pattern and substring of text for i in range(p_len): p_hash = (ord(pattern[i]) + p_hash * alphabet_size) % modulus text_hash = (ord(text[i]) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue modulus_power = (modulus_power * alphabet_size) % modulus for i in range(0, t_len - p_len + 1): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash text_hash = ( (text_hash - ord(text[i]) * modulus_power) * alphabet_size + ord(text[i + p_len]) ) % modulus return False def test_rabin_karp() -> None: """ >>> test_rabin_karp() Success. """ # Test 1) pattern = "abc1abc12" text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc" text2 = "alskfjaldsk23adsfabcabc" assert rabin_karp(pattern, text1) and not rabin_karp(pattern, text2) # Test 2) pattern = "ABABX" text = "ABABZABABYABABX" assert rabin_karp(pattern, text) # Test 3) pattern = "AAAB" text = "ABAAAAAB" assert rabin_karp(pattern, text) # Test 4) pattern = "abcdabcy" text = "abcxabcdabxabcdabcdabcy" assert rabin_karp(pattern, text) # Test 5) pattern = "Lü" text = "Lüsai" assert rabin_karp(pattern, text) pattern = "Lue" assert not rabin_karp(pattern, text) print("Success.") if __name__ == "__main__": test_rabin_karp()
# Numbers of alphabet which we call base alphabet_size = 256 # Modulus to hash a string modulus = 1000003 def rabin_karp(pattern: str, text: str) -> bool: """ The Rabin-Karp Algorithm for finding a pattern within a piece of text with complexity O(nm), most efficient when it is used with multiple patterns as it is able to check if any of a set of patterns match a section of text in o(1) given the precomputed hashes. This will be the simple version which only assumes one pattern is being searched for but it's not hard to modify 1) Calculate pattern hash 2) Step through the text one character at a time passing a window with the same length as the pattern calculating the hash of the text within the window compare it with the hash of the pattern. Only testing equality if the hashes match """ p_len = len(pattern) t_len = len(text) if p_len > t_len: return False p_hash = 0 text_hash = 0 modulus_power = 1 # Calculating the hash of pattern and substring of text for i in range(p_len): p_hash = (ord(pattern[i]) + p_hash * alphabet_size) % modulus text_hash = (ord(text[i]) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue modulus_power = (modulus_power * alphabet_size) % modulus for i in range(0, t_len - p_len + 1): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash text_hash = ( (text_hash - ord(text[i]) * modulus_power) * alphabet_size + ord(text[i + p_len]) ) % modulus return False def test_rabin_karp() -> None: """ >>> test_rabin_karp() Success. """ # Test 1) pattern = "abc1abc12" text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc" text2 = "alskfjaldsk23adsfabcabc" assert rabin_karp(pattern, text1) and not rabin_karp(pattern, text2) # Test 2) pattern = "ABABX" text = "ABABZABABYABABX" assert rabin_karp(pattern, text) # Test 3) pattern = "AAAB" text = "ABAAAAAB" assert rabin_karp(pattern, text) # Test 4) pattern = "abcdabcy" text = "abcxabcdabxabcdabcdabcy" assert rabin_karp(pattern, text) # Test 5) pattern = "Lü" text = "Lüsai" assert rabin_karp(pattern, text) pattern = "Lue" assert not rabin_karp(pattern, text) print("Success.") if __name__ == "__main__": test_rabin_karp()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Uses Pythagoras theorem to calculate the distance between two points in space.""" import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) def test_distance() -> None: """ >>> point1 = Point(2, -1, 7) >>> point2 = Point(1, -3, 5) >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 """ pass if __name__ == "__main__": import doctest doctest.testmod()
"""Uses Pythagoras theorem to calculate the distance between two points in space.""" import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) def test_distance() -> None: """ >>> point1 = Point(2, -1, 7) >>> point2 = Point(1, -3, 5) >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 """ pass if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 80: https://projecteuler.net/problem=80 Author: Sandeep Gupta Problem statement: For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots. Time: 5 October 2020, 18:30 """ import decimal def solution() -> int: """ To evaluate the sum, Used decimal python module to calculate the decimal places up to 100, the most important thing would be take calculate a few extra places for decimal otherwise there will be rounding error. >>> solution() 40886 """ answer = 0 decimal_context = decimal.Context(prec=105) for i in range(2, 100): number = decimal.Decimal(i) sqrt_number = number.sqrt(decimal_context) if len(str(sqrt_number)) > 1: answer += int(str(sqrt_number)[0]) sqrt_number_str = str(sqrt_number)[2:101] answer += sum(int(x) for x in sqrt_number_str) return answer if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
""" Project Euler Problem 80: https://projecteuler.net/problem=80 Author: Sandeep Gupta Problem statement: For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots. Time: 5 October 2020, 18:30 """ import decimal def solution() -> int: """ To evaluate the sum, Used decimal python module to calculate the decimal places up to 100, the most important thing would be take calculate a few extra places for decimal otherwise there will be rounding error. >>> solution() 40886 """ answer = 0 decimal_context = decimal.Context(prec=105) for i in range(2, 100): number = decimal.Decimal(i) sqrt_number = number.sqrt(decimal_context) if len(str(sqrt_number)) > 1: answer += int(str(sqrt_number)[0]) sqrt_number_str = str(sqrt_number)[2:101] answer += sum(int(x) for x in sqrt_number_str) return answer if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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/Strongly_connected_component Finding strongly connected components in directed graph """ test_graph_1 = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} test_graph_2 = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def topology_sort( graph: dict[int, list[int]], vert: int, visited: list[bool] ) -> list[int]: """ Use depth first search to sort graph At this time graph is the same as input >>> topology_sort(test_graph_1, 0, 5 * [False]) [1, 2, 4, 3, 0] >>> topology_sort(test_graph_2, 0, 6 * [False]) [2, 1, 5, 4, 3, 0] """ visited[vert] = True order = [] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(graph, neighbour, visited) order.append(vert) return order def find_components( reversed_graph: dict[int, list[int]], vert: int, visited: list[bool] ) -> list[int]: """ Use depth first search to find strongliy connected vertices. Now graph is reversed >>> find_components({0: [1], 1: [2], 2: [0]}, 0, 5 * [False]) [0, 1, 2] >>> find_components({0: [2], 1: [0], 2: [0, 1]}, 0, 6 * [False]) [0, 2, 1] """ visited[vert] = True component = [vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(reversed_graph, neighbour, visited) return component def strongly_connected_components(graph: dict[int, list[int]]) -> list[list[int]]: """ This function takes graph as a parameter and then returns the list of strongly connected components >>> strongly_connected_components(test_graph_1) [[0, 1, 2], [3], [4]] >>> strongly_connected_components(test_graph_2) [[0, 2, 1], [3, 5, 4]] """ visited = len(graph) * [False] reversed_graph: dict[int, list[int]] = {vert: [] for vert in range(len(graph))} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(vert) order = [] for i, was_visited in enumerate(visited): if not was_visited: order += topology_sort(graph, i, visited) components_list = [] visited = len(graph) * [False] for i in range(len(graph)): vert = order[len(graph) - i - 1] if not visited[vert]: component = find_components(reversed_graph, vert, visited) components_list.append(component) return components_list
""" https://en.wikipedia.org/wiki/Strongly_connected_component Finding strongly connected components in directed graph """ test_graph_1 = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} test_graph_2 = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def topology_sort( graph: dict[int, list[int]], vert: int, visited: list[bool] ) -> list[int]: """ Use depth first search to sort graph At this time graph is the same as input >>> topology_sort(test_graph_1, 0, 5 * [False]) [1, 2, 4, 3, 0] >>> topology_sort(test_graph_2, 0, 6 * [False]) [2, 1, 5, 4, 3, 0] """ visited[vert] = True order = [] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(graph, neighbour, visited) order.append(vert) return order def find_components( reversed_graph: dict[int, list[int]], vert: int, visited: list[bool] ) -> list[int]: """ Use depth first search to find strongliy connected vertices. Now graph is reversed >>> find_components({0: [1], 1: [2], 2: [0]}, 0, 5 * [False]) [0, 1, 2] >>> find_components({0: [2], 1: [0], 2: [0, 1]}, 0, 6 * [False]) [0, 2, 1] """ visited[vert] = True component = [vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(reversed_graph, neighbour, visited) return component def strongly_connected_components(graph: dict[int, list[int]]) -> list[list[int]]: """ This function takes graph as a parameter and then returns the list of strongly connected components >>> strongly_connected_components(test_graph_1) [[0, 1, 2], [3], [4]] >>> strongly_connected_components(test_graph_2) [[0, 2, 1], [3, 5, 4]] """ visited = len(graph) * [False] reversed_graph: dict[int, list[int]] = {vert: [] for vert in range(len(graph))} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(vert) order = [] for i, was_visited in enumerate(visited): if not was_visited: order += topology_sort(graph, i, visited) components_list = [] visited = len(graph) * [False] for i in range(len(graph)): vert = order[len(graph) - i - 1] if not visited[vert]: component = find_components(reversed_graph, vert, visited) components_list.append(component) return components_list
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Shortest job remaining first Please note arrival time and burst Please use spaces to separate times entered. """ from __future__ import annotations import pandas as pd def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: """ Calculate the waiting time of each processes Return: List of waiting times. >>> calculate_waitingtime([1,2,3,4],[3,3,5,1],4) [0, 3, 5, 0] >>> calculate_waitingtime([1,2,3],[2,5,1],3) [0, 2, 0] >>> calculate_waitingtime([2,3],[5,1],2) [1, 0] """ remaining_time = [0] * no_of_processes waiting_time = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(no_of_processes): remaining_time[i] = burst_time[i] complete = 0 increment_time = 0 minm = 999999999 short = 0 check = False # Process until all processes are completed while complete != no_of_processes: for j in range(no_of_processes): if arrival_time[j] <= increment_time: if remaining_time[j] > 0: if remaining_time[j] < minm: minm = remaining_time[j] short = j check = True if not check: increment_time += 1 continue remaining_time[short] -= 1 minm = remaining_time[short] if minm == 0: minm = 999999999 if remaining_time[short] == 0: complete += 1 check = False # Find finish time of current process finish_time = increment_time + 1 # Calculate waiting time finar = finish_time - arrival_time[short] waiting_time[short] = finar - burst_time[short] if waiting_time[short] < 0: waiting_time[short] = 0 # Increment time increment_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: """ Calculate the turn around time of each Processes Return: list of turn around times. >>> calculate_turnaroundtime([3,3,5,1], 4, [0,3,5,0]) [3, 6, 10, 1] >>> calculate_turnaroundtime([3,3], 2, [0,3]) [3, 6] >>> calculate_turnaroundtime([8,10,1], 3, [1,0,3]) [9, 10, 4] """ turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time def calculate_average_times( waiting_time: list[int], turn_around_time: list[int], no_of_processes: int ) -> None: """ This function calculates the average of the waiting & turnaround times Prints: Average Waiting time & Average Turn Around Time >>> calculate_average_times([0,3,5,0],[3,6,10,1],4) Average waiting time = 2.00000 Average turn around time = 5.0 >>> calculate_average_times([2,3],[3,6],2) Average waiting time = 2.50000 Average turn around time = 4.5 >>> calculate_average_times([10,4,3],[2,7,6],3) Average waiting time = 5.66667 Average turn around time = 5.0 """ total_waiting_time = 0 total_turn_around_time = 0 for i in range(no_of_processes): total_waiting_time = total_waiting_time + waiting_time[i] total_turn_around_time = total_turn_around_time + turn_around_time[i] print(f"Average waiting time = {total_waiting_time / no_of_processes:.5f}") print("Average turn around time =", total_turn_around_time / no_of_processes) if __name__ == "__main__": print("Enter how many process you want to analyze") no_of_processes = int(input()) burst_time = [0] * no_of_processes arrival_time = [0] * no_of_processes processes = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print("Enter the arrival time and burst time for process:--" + str(i + 1)) arrival_time[i], burst_time[i] = map(int, input().split()) waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) bt = burst_time n = no_of_processes wt = waiting_time turn_around_time = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) fcfs = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ "Process", "BurstTime", "ArrivalTime", "WaitingTime", "TurnAroundTime", ], ) # Printing the dataFrame pd.set_option("display.max_rows", fcfs.shape[0] + 1) print(fcfs)
""" Shortest job remaining first Please note arrival time and burst Please use spaces to separate times entered. """ from __future__ import annotations import pandas as pd def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: """ Calculate the waiting time of each processes Return: List of waiting times. >>> calculate_waitingtime([1,2,3,4],[3,3,5,1],4) [0, 3, 5, 0] >>> calculate_waitingtime([1,2,3],[2,5,1],3) [0, 2, 0] >>> calculate_waitingtime([2,3],[5,1],2) [1, 0] """ remaining_time = [0] * no_of_processes waiting_time = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(no_of_processes): remaining_time[i] = burst_time[i] complete = 0 increment_time = 0 minm = 999999999 short = 0 check = False # Process until all processes are completed while complete != no_of_processes: for j in range(no_of_processes): if arrival_time[j] <= increment_time: if remaining_time[j] > 0: if remaining_time[j] < minm: minm = remaining_time[j] short = j check = True if not check: increment_time += 1 continue remaining_time[short] -= 1 minm = remaining_time[short] if minm == 0: minm = 999999999 if remaining_time[short] == 0: complete += 1 check = False # Find finish time of current process finish_time = increment_time + 1 # Calculate waiting time finar = finish_time - arrival_time[short] waiting_time[short] = finar - burst_time[short] if waiting_time[short] < 0: waiting_time[short] = 0 # Increment time increment_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: """ Calculate the turn around time of each Processes Return: list of turn around times. >>> calculate_turnaroundtime([3,3,5,1], 4, [0,3,5,0]) [3, 6, 10, 1] >>> calculate_turnaroundtime([3,3], 2, [0,3]) [3, 6] >>> calculate_turnaroundtime([8,10,1], 3, [1,0,3]) [9, 10, 4] """ turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time def calculate_average_times( waiting_time: list[int], turn_around_time: list[int], no_of_processes: int ) -> None: """ This function calculates the average of the waiting & turnaround times Prints: Average Waiting time & Average Turn Around Time >>> calculate_average_times([0,3,5,0],[3,6,10,1],4) Average waiting time = 2.00000 Average turn around time = 5.0 >>> calculate_average_times([2,3],[3,6],2) Average waiting time = 2.50000 Average turn around time = 4.5 >>> calculate_average_times([10,4,3],[2,7,6],3) Average waiting time = 5.66667 Average turn around time = 5.0 """ total_waiting_time = 0 total_turn_around_time = 0 for i in range(no_of_processes): total_waiting_time = total_waiting_time + waiting_time[i] total_turn_around_time = total_turn_around_time + turn_around_time[i] print(f"Average waiting time = {total_waiting_time / no_of_processes:.5f}") print("Average turn around time =", total_turn_around_time / no_of_processes) if __name__ == "__main__": print("Enter how many process you want to analyze") no_of_processes = int(input()) burst_time = [0] * no_of_processes arrival_time = [0] * no_of_processes processes = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print("Enter the arrival time and burst time for process:--" + str(i + 1)) arrival_time[i], burst_time[i] = map(int, input().split()) waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) bt = burst_time n = no_of_processes wt = waiting_time turn_around_time = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) fcfs = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ "Process", "BurstTime", "ArrivalTime", "WaitingTime", "TurnAroundTime", ], ) # Printing the dataFrame pd.set_option("display.max_rows", fcfs.shape[0] + 1) print(fcfs)
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from collections.abc import Callable import numpy as np def explicit_euler( ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float ) -> np.ndarray: """Calculate numeric solution at each step to an ODE using Euler's Method For reference to Euler's method refer to https://en.wikipedia.org/wiki/Euler_method. Args: ode_func (Callable): The ordinary differential equation as a function of x and y. y0 (float): The initial value for y. x0 (float): The initial value for x. step_size (float): The increment value for x. x_end (float): The final value of x to be calculated. Returns: np.ndarray: Solution of y for every step in x. >>> # the exact solution is math.exp(x) >>> def f(x, y): ... return y >>> y0 = 1 >>> y = explicit_euler(f, y0, 0.0, 0.01, 5) >>> y[-1] 144.77277243257308 """ n = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((n + 1,)) y[0] = y0 x = x0 for k in range(n): y[k + 1] = y[k] + step_size * ode_func(x, y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
from collections.abc import Callable import numpy as np def explicit_euler( ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float ) -> np.ndarray: """Calculate numeric solution at each step to an ODE using Euler's Method For reference to Euler's method refer to https://en.wikipedia.org/wiki/Euler_method. Args: ode_func (Callable): The ordinary differential equation as a function of x and y. y0 (float): The initial value for y. x0 (float): The initial value for x. step_size (float): The increment value for x. x_end (float): The final value of x to be calculated. Returns: np.ndarray: Solution of y for every step in x. >>> # the exact solution is math.exp(x) >>> def f(x, y): ... return y >>> y0 = 1 >>> y = explicit_euler(f, y0, 0.0, 0.01, 5) >>> y[-1] 144.77277243257308 """ n = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((n + 1,)) y[0] = y0 x = x0 for k in range(n): y[k + 1] = y[k] + step_size * ode_func(x, y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import math def fx(x: float, a: float) -> float: return math.pow(x, 2) - a def fx_derivative(x: float) -> float: return 2 * x def get_initial_point(a: float) -> float: start = 2.0 while start <= a: start = math.pow(start, 2) return start def square_root_iterative( a: float, max_iter: int = 9999, tolerance: float = 0.00000000000001 ) -> float: """ Square root is aproximated using Newtons method. https://en.wikipedia.org/wiki/Newton%27s_method >>> all(abs(square_root_iterative(i)-math.sqrt(i)) <= .00000000000001 ... for i in range(500)) True >>> square_root_iterative(-1) Traceback (most recent call last): ... ValueError: math domain error >>> square_root_iterative(4) 2.0 >>> square_root_iterative(3.2) 1.788854381999832 >>> square_root_iterative(140) 11.832159566199232 """ if a < 0: raise ValueError("math domain error") value = get_initial_point(a) for _ in range(max_iter): prev_value = value value = value - fx(value, a) / fx_derivative(value) if abs(prev_value - value) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
import math def fx(x: float, a: float) -> float: return math.pow(x, 2) - a def fx_derivative(x: float) -> float: return 2 * x def get_initial_point(a: float) -> float: start = 2.0 while start <= a: start = math.pow(start, 2) return start def square_root_iterative( a: float, max_iter: int = 9999, tolerance: float = 0.00000000000001 ) -> float: """ Square root is aproximated using Newtons method. https://en.wikipedia.org/wiki/Newton%27s_method >>> all(abs(square_root_iterative(i)-math.sqrt(i)) <= .00000000000001 ... for i in range(500)) True >>> square_root_iterative(-1) Traceback (most recent call last): ... ValueError: math domain error >>> square_root_iterative(4) 2.0 >>> square_root_iterative(3.2) 1.788854381999832 >>> square_root_iterative(140) 11.832159566199232 """ if a < 0: raise ValueError("math domain error") value = get_initial_point(a) for _ in range(max_iter): prev_value = value value = value - fx(value, a) / fx_derivative(value) if abs(prev_value - value) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a Python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .DS_Store .idea .try .vscode/ .vs/
# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a Python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .DS_Store .idea .try .vscode/ .vs/
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 used to convert the currency using the Amdoren Currency API https://www.amdoren.com """ import os import requests URL_BASE = "https://www.amdoren.com/api/currency.php" TESTING = os.getenv("CI", False) API_KEY = os.getenv("AMDOREN_API_KEY", "") if not API_KEY and not TESTING: raise KeyError( "API key must be provided in the 'AMDOREN_API_KEY' environment variable." ) # Currency and their description list_of_currencies = """ AED United Arab Emirates Dirham AFN Afghan Afghani ALL Albanian Lek AMD Armenian Dram ANG Netherlands Antillean Guilder AOA Angolan Kwanza ARS Argentine Peso AUD Australian Dollar AWG Aruban Florin AZN Azerbaijani Manat BAM Bosnia & Herzegovina Convertible Mark BBD Barbadian Dollar BDT Bangladeshi Taka BGN Bulgarian Lev BHD Bahraini Dinar BIF Burundian Franc BMD Bermudian Dollar BND Brunei Dollar BOB Bolivian Boliviano BRL Brazilian Real BSD Bahamian Dollar BTN Bhutanese Ngultrum BWP Botswana Pula BYN Belarus Ruble BZD Belize Dollar CAD Canadian Dollar CDF Congolese Franc CHF Swiss Franc CLP Chilean Peso CNY Chinese Yuan COP Colombian Peso CRC Costa Rican Colon CUC Cuban Convertible Peso CVE Cape Verdean Escudo CZK Czech Republic Koruna DJF Djiboutian Franc DKK Danish Krone DOP Dominican Peso DZD Algerian Dinar EGP Egyptian Pound ERN Eritrean Nakfa ETB Ethiopian Birr EUR Euro FJD Fiji Dollar GBP British Pound Sterling GEL Georgian Lari GHS Ghanaian Cedi GIP Gibraltar Pound GMD Gambian Dalasi GNF Guinea Franc GTQ Guatemalan Quetzal GYD Guyanaese Dollar HKD Hong Kong Dollar HNL Honduran Lempira HRK Croatian Kuna HTG Haiti Gourde HUF Hungarian Forint IDR Indonesian Rupiah ILS Israeli Shekel INR Indian Rupee IQD Iraqi Dinar IRR Iranian Rial ISK Icelandic Krona JMD Jamaican Dollar JOD Jordanian Dinar JPY Japanese Yen KES Kenyan Shilling KGS Kyrgystani Som KHR Cambodian Riel KMF Comorian Franc KPW North Korean Won KRW South Korean Won KWD Kuwaiti Dinar KYD Cayman Islands Dollar KZT Kazakhstan Tenge LAK Laotian Kip LBP Lebanese Pound LKR Sri Lankan Rupee LRD Liberian Dollar LSL Lesotho Loti LYD Libyan Dinar MAD Moroccan Dirham MDL Moldovan Leu MGA Malagasy Ariary MKD Macedonian Denar MMK Myanma Kyat MNT Mongolian Tugrik MOP Macau Pataca MRO Mauritanian Ouguiya MUR Mauritian Rupee MVR Maldivian Rufiyaa MWK Malawi Kwacha MXN Mexican Peso MYR Malaysian Ringgit MZN Mozambican Metical NAD Namibian Dollar NGN Nigerian Naira NIO Nicaragua Cordoba NOK Norwegian Krone NPR Nepalese Rupee NZD New Zealand Dollar OMR Omani Rial PAB Panamanian Balboa PEN Peruvian Nuevo Sol PGK Papua New Guinean Kina PHP Philippine Peso PKR Pakistani Rupee PLN Polish Zloty PYG Paraguayan Guarani QAR Qatari Riyal RON Romanian Leu RSD Serbian Dinar RUB Russian Ruble RWF Rwanda Franc SAR Saudi Riyal SBD Solomon Islands Dollar SCR Seychellois Rupee SDG Sudanese Pound SEK Swedish Krona SGD Singapore Dollar SHP Saint Helena Pound SLL Sierra Leonean Leone SOS Somali Shilling SRD Surinamese Dollar SSP South Sudanese Pound STD Sao Tome and Principe Dobra SYP Syrian Pound SZL Swazi Lilangeni THB Thai Baht TJS Tajikistan Somoni TMT Turkmenistani Manat TND Tunisian Dinar TOP Tonga Paanga TRY Turkish Lira TTD Trinidad and Tobago Dollar TWD New Taiwan Dollar TZS Tanzanian Shilling UAH Ukrainian Hryvnia UGX Ugandan Shilling USD United States Dollar UYU Uruguayan Peso UZS Uzbekistan Som VEF Venezuelan Bolivar VND Vietnamese Dong VUV Vanuatu Vatu WST Samoan Tala XAF Central African CFA franc XCD East Caribbean Dollar XOF West African CFA franc XPF CFP Franc YER Yemeni Rial ZAR South African Rand ZMW Zambian Kwacha """ def convert_currency( from_: str = "USD", to: str = "INR", amount: float = 1.0, api_key: str = API_KEY ) -> str: """https://www.amdoren.com/currency-api/""" params = locals() params["from"] = params.pop("from_") res = requests.get(URL_BASE, params=params).json() return str(res["amount"]) if res["error"] == 0 else res["error_message"] if __name__ == "__main__": print( convert_currency( input("Enter from currency: ").strip(), input("Enter to currency: ").strip(), float(input("Enter the amount: ").strip()), ) )
""" This is used to convert the currency using the Amdoren Currency API https://www.amdoren.com """ import os import requests URL_BASE = "https://www.amdoren.com/api/currency.php" TESTING = os.getenv("CI", False) API_KEY = os.getenv("AMDOREN_API_KEY", "") if not API_KEY and not TESTING: raise KeyError( "API key must be provided in the 'AMDOREN_API_KEY' environment variable." ) # Currency and their description list_of_currencies = """ AED United Arab Emirates Dirham AFN Afghan Afghani ALL Albanian Lek AMD Armenian Dram ANG Netherlands Antillean Guilder AOA Angolan Kwanza ARS Argentine Peso AUD Australian Dollar AWG Aruban Florin AZN Azerbaijani Manat BAM Bosnia & Herzegovina Convertible Mark BBD Barbadian Dollar BDT Bangladeshi Taka BGN Bulgarian Lev BHD Bahraini Dinar BIF Burundian Franc BMD Bermudian Dollar BND Brunei Dollar BOB Bolivian Boliviano BRL Brazilian Real BSD Bahamian Dollar BTN Bhutanese Ngultrum BWP Botswana Pula BYN Belarus Ruble BZD Belize Dollar CAD Canadian Dollar CDF Congolese Franc CHF Swiss Franc CLP Chilean Peso CNY Chinese Yuan COP Colombian Peso CRC Costa Rican Colon CUC Cuban Convertible Peso CVE Cape Verdean Escudo CZK Czech Republic Koruna DJF Djiboutian Franc DKK Danish Krone DOP Dominican Peso DZD Algerian Dinar EGP Egyptian Pound ERN Eritrean Nakfa ETB Ethiopian Birr EUR Euro FJD Fiji Dollar GBP British Pound Sterling GEL Georgian Lari GHS Ghanaian Cedi GIP Gibraltar Pound GMD Gambian Dalasi GNF Guinea Franc GTQ Guatemalan Quetzal GYD Guyanaese Dollar HKD Hong Kong Dollar HNL Honduran Lempira HRK Croatian Kuna HTG Haiti Gourde HUF Hungarian Forint IDR Indonesian Rupiah ILS Israeli Shekel INR Indian Rupee IQD Iraqi Dinar IRR Iranian Rial ISK Icelandic Krona JMD Jamaican Dollar JOD Jordanian Dinar JPY Japanese Yen KES Kenyan Shilling KGS Kyrgystani Som KHR Cambodian Riel KMF Comorian Franc KPW North Korean Won KRW South Korean Won KWD Kuwaiti Dinar KYD Cayman Islands Dollar KZT Kazakhstan Tenge LAK Laotian Kip LBP Lebanese Pound LKR Sri Lankan Rupee LRD Liberian Dollar LSL Lesotho Loti LYD Libyan Dinar MAD Moroccan Dirham MDL Moldovan Leu MGA Malagasy Ariary MKD Macedonian Denar MMK Myanma Kyat MNT Mongolian Tugrik MOP Macau Pataca MRO Mauritanian Ouguiya MUR Mauritian Rupee MVR Maldivian Rufiyaa MWK Malawi Kwacha MXN Mexican Peso MYR Malaysian Ringgit MZN Mozambican Metical NAD Namibian Dollar NGN Nigerian Naira NIO Nicaragua Cordoba NOK Norwegian Krone NPR Nepalese Rupee NZD New Zealand Dollar OMR Omani Rial PAB Panamanian Balboa PEN Peruvian Nuevo Sol PGK Papua New Guinean Kina PHP Philippine Peso PKR Pakistani Rupee PLN Polish Zloty PYG Paraguayan Guarani QAR Qatari Riyal RON Romanian Leu RSD Serbian Dinar RUB Russian Ruble RWF Rwanda Franc SAR Saudi Riyal SBD Solomon Islands Dollar SCR Seychellois Rupee SDG Sudanese Pound SEK Swedish Krona SGD Singapore Dollar SHP Saint Helena Pound SLL Sierra Leonean Leone SOS Somali Shilling SRD Surinamese Dollar SSP South Sudanese Pound STD Sao Tome and Principe Dobra SYP Syrian Pound SZL Swazi Lilangeni THB Thai Baht TJS Tajikistan Somoni TMT Turkmenistani Manat TND Tunisian Dinar TOP Tonga Paanga TRY Turkish Lira TTD Trinidad and Tobago Dollar TWD New Taiwan Dollar TZS Tanzanian Shilling UAH Ukrainian Hryvnia UGX Ugandan Shilling USD United States Dollar UYU Uruguayan Peso UZS Uzbekistan Som VEF Venezuelan Bolivar VND Vietnamese Dong VUV Vanuatu Vatu WST Samoan Tala XAF Central African CFA franc XCD East Caribbean Dollar XOF West African CFA franc XPF CFP Franc YER Yemeni Rial ZAR South African Rand ZMW Zambian Kwacha """ def convert_currency( from_: str = "USD", to: str = "INR", amount: float = 1.0, api_key: str = API_KEY ) -> str: """https://www.amdoren.com/currency-api/""" params = locals() params["from"] = params.pop("from_") res = requests.get(URL_BASE, params=params).json() return str(res["amount"]) if res["error"] == 0 else res["error_message"] if __name__ == "__main__": print( convert_currency( input("Enter from currency: ").strip(), input("Enter to currency: ").strip(), float(input("Enter the amount: ").strip()), ) )
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 iterative merge sort in Python Author: Aman Gupta For doctests run following command: python3 -m doctest -v iterative_merge_sort.py For manual testing run: python3 iterative_merge_sort.py """ from __future__ import annotations def merge(input_list: list, low: int, mid: int, high: int) -> list: """ sorting left-half and right-half individually then merging them into result """ result = [] left, right = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0)) input_list[low : high + 1] = result + left + right return input_list # iteration over the unsorted list def iter_merge_sort(input_list: list) -> list: """ Return a sorted copy of the input list >>> iter_merge_sort([5, 9, 8, 7, 1, 2, 7]) [1, 2, 5, 7, 7, 8, 9] >>> iter_merge_sort([1]) [1] >>> iter_merge_sort([2, 1]) [1, 2] >>> iter_merge_sort([2, 1, 3]) [1, 2, 3] >>> iter_merge_sort([4, 3, 2, 1]) [1, 2, 3, 4] >>> iter_merge_sort([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> iter_merge_sort(['c', 'b', 'a']) ['a', 'b', 'c'] >>> iter_merge_sort([0.3, 0.2, 0.1]) [0.1, 0.2, 0.3] >>> iter_merge_sort(['dep', 'dang', 'trai']) ['dang', 'dep', 'trai'] >>> iter_merge_sort([6]) [6] >>> iter_merge_sort([]) [] >>> iter_merge_sort([-2, -9, -1, -4]) [-9, -4, -2, -1] >>> iter_merge_sort([1.1, 1, 0.0, -1, -1.1]) [-1.1, -1, 0.0, 1, 1.1] >>> iter_merge_sort(['c', 'b', 'a']) ['a', 'b', 'c'] >>> iter_merge_sort('cba') ['a', 'b', 'c'] """ if len(input_list) <= 1: return input_list input_list = list(input_list) # iteration for two-way merging p = 2 while p <= len(input_list): # getting low, high and middle value for merge-sort of single list for i in range(0, len(input_list), p): low = i high = i + p - 1 mid = (low + high + 1) // 2 input_list = merge(input_list, low, mid, high) # final merge of last two parts if p * 2 >= len(input_list): mid = i input_list = merge(input_list, 0, mid, len(input_list) - 1) break p *= 2 return input_list if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() if user_input == "": unsorted = [] else: unsorted = [int(item.strip()) for item in user_input.split(",")] print(iter_merge_sort(unsorted))
""" Implementation of iterative merge sort in Python Author: Aman Gupta For doctests run following command: python3 -m doctest -v iterative_merge_sort.py For manual testing run: python3 iterative_merge_sort.py """ from __future__ import annotations def merge(input_list: list, low: int, mid: int, high: int) -> list: """ sorting left-half and right-half individually then merging them into result """ result = [] left, right = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0)) input_list[low : high + 1] = result + left + right return input_list # iteration over the unsorted list def iter_merge_sort(input_list: list) -> list: """ Return a sorted copy of the input list >>> iter_merge_sort([5, 9, 8, 7, 1, 2, 7]) [1, 2, 5, 7, 7, 8, 9] >>> iter_merge_sort([1]) [1] >>> iter_merge_sort([2, 1]) [1, 2] >>> iter_merge_sort([2, 1, 3]) [1, 2, 3] >>> iter_merge_sort([4, 3, 2, 1]) [1, 2, 3, 4] >>> iter_merge_sort([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> iter_merge_sort(['c', 'b', 'a']) ['a', 'b', 'c'] >>> iter_merge_sort([0.3, 0.2, 0.1]) [0.1, 0.2, 0.3] >>> iter_merge_sort(['dep', 'dang', 'trai']) ['dang', 'dep', 'trai'] >>> iter_merge_sort([6]) [6] >>> iter_merge_sort([]) [] >>> iter_merge_sort([-2, -9, -1, -4]) [-9, -4, -2, -1] >>> iter_merge_sort([1.1, 1, 0.0, -1, -1.1]) [-1.1, -1, 0.0, 1, 1.1] >>> iter_merge_sort(['c', 'b', 'a']) ['a', 'b', 'c'] >>> iter_merge_sort('cba') ['a', 'b', 'c'] """ if len(input_list) <= 1: return input_list input_list = list(input_list) # iteration for two-way merging p = 2 while p <= len(input_list): # getting low, high and middle value for merge-sort of single list for i in range(0, len(input_list), p): low = i high = i + p - 1 mid = (low + high + 1) // 2 input_list = merge(input_list, low, mid, high) # final merge of last two parts if p * 2 >= len(input_list): mid = i input_list = merge(input_list, 0, mid, len(input_list) - 1) break p *= 2 return input_list if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() if user_input == "": unsorted = [] else: unsorted = [int(item.strip()) for item in user_input.split(",")] print(iter_merge_sort(unsorted))
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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(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)
#!/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
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ def fibonacci(n: int) -> int: """ Computes the Fibonacci number for input n by iterating through n numbers and creating an array of ints using the Fibonacci formula. Returns the nth element of the array. >>> fibonacci(2) 1 >>> fibonacci(3) 2 >>> fibonacci(5) 5 >>> fibonacci(10) 55 >>> fibonacci(12) 144 """ if n == 1 or type(n) is not int: return 0 elif n == 2: return 1 else: sequence = [0, 1] for i in range(2, n + 1): sequence.append(sequence[i - 1] + sequence[i - 2]) return sequence[n] def fibonacci_digits_index(n: int) -> int: """ Computes incrementing Fibonacci numbers starting from 3 until the length of the resulting Fibonacci result is the input value n. Returns the term of the Fibonacci sequence where this occurs. >>> fibonacci_digits_index(1000) 4782 >>> fibonacci_digits_index(100) 476 >>> fibonacci_digits_index(50) 237 >>> fibonacci_digits_index(3) 12 """ digits = 0 index = 2 while digits < n: index += 1 digits = len(str(fibonacci(index))) return index def solution(n: int = 1000) -> int: """ Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ return fibonacci_digits_index(n) if __name__ == "__main__": print(solution(int(str(input()).strip())))
""" The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ def fibonacci(n: int) -> int: """ Computes the Fibonacci number for input n by iterating through n numbers and creating an array of ints using the Fibonacci formula. Returns the nth element of the array. >>> fibonacci(2) 1 >>> fibonacci(3) 2 >>> fibonacci(5) 5 >>> fibonacci(10) 55 >>> fibonacci(12) 144 """ if n == 1 or type(n) is not int: return 0 elif n == 2: return 1 else: sequence = [0, 1] for i in range(2, n + 1): sequence.append(sequence[i - 1] + sequence[i - 2]) return sequence[n] def fibonacci_digits_index(n: int) -> int: """ Computes incrementing Fibonacci numbers starting from 3 until the length of the resulting Fibonacci result is the input value n. Returns the term of the Fibonacci sequence where this occurs. >>> fibonacci_digits_index(1000) 4782 >>> fibonacci_digits_index(100) 476 >>> fibonacci_digits_index(50) 237 >>> fibonacci_digits_index(3) 12 """ digits = 0 index = 2 while digits < n: index += 1 digits = len(str(fibonacci(index))) return index def solution(n: int = 1000) -> int: """ Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ return fibonacci_digits_index(n) if __name__ == "__main__": print(solution(int(str(input()).strip())))
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Compression Data compression is everywhere, you need it to store data without taking too much space. Either the compression lose some data (then we talk about lossy compression, such as .jpg) or it does not (and then it is lossless compression, such as .png) Lossless compression is mainly used for archive purpose as it allow storing data without losing information about the file archived. On the other hand, lossy compression is used for transfer of file where quality isn't necessarily what is required (i.e: images on Twitter). * <https://www.sciencedirect.com/topics/computer-science/compression-algorithm> * <https://en.wikipedia.org/wiki/Data_compression> * <https://en.wikipedia.org/wiki/Pigeonhole_principle>
# Compression Data compression is everywhere, you need it to store data without taking too much space. Either the compression lose some data (then we talk about lossy compression, such as .jpg) or it does not (and then it is lossless compression, such as .png) Lossless compression is mainly used for archive purpose as it allow storing data without losing information about the file archived. On the other hand, lossy compression is used for transfer of file where quality isn't necessarily what is required (i.e: images on Twitter). * <https://www.sciencedirect.com/topics/computer-science/compression-algorithm> * <https://en.wikipedia.org/wiki/Data_compression> * <https://en.wikipedia.org/wiki/Pigeonhole_principle>
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 """ The Bifid Cipher uses a Polybius Square to encipher a message in a way that makes it fairly difficult to decipher without knowing the secret. https://www.braingle.com/brainteasers/codes/bifid.php """ import numpy as np class BifidCipher: def __init__(self) -> None: SQUARE = [ # noqa: N806 ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "k"], ["l", "m", "n", "o", "p"], ["q", "r", "s", "t", "u"], ["v", "w", "x", "y", "z"], ] self.SQUARE = np.array(SQUARE) def letter_to_numbers(self, letter: str) -> np.ndarray: """ Return the pair of numbers that represents the given letter in the polybius square >>> np.array_equal(BifidCipher().letter_to_numbers('a'), [1,1]) True >>> np.array_equal(BifidCipher().letter_to_numbers('u'), [4,5]) True """ index1, index2 = np.where(self.SQUARE == letter) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes def numbers_to_letter(self, index1: int, index2: int) -> str: """ Return the letter corresponding to the position [index1, index2] in the polybius square >>> BifidCipher().numbers_to_letter(4, 5) == "u" True >>> BifidCipher().numbers_to_letter(1, 1) == "a" True """ letter = self.SQUARE[index1 - 1, index2 - 1] return letter def encode(self, message: str) -> str: """ Return the encoded version of message according to the polybius cipher >>> BifidCipher().encode('testmessage') == 'qtltbdxrxlk' True >>> BifidCipher().encode('Test Message') == 'qtltbdxrxlk' True >>> BifidCipher().encode('test j') == BifidCipher().encode('test i') True """ message = message.lower() message = message.replace(" ", "") message = message.replace("j", "i") first_step = np.empty((2, len(message))) for letter_index in range(len(message)): numbers = self.letter_to_numbers(message[letter_index]) first_step[0, letter_index] = numbers[0] first_step[1, letter_index] = numbers[1] second_step = first_step.reshape(2 * len(message)) encoded_message = "" for numbers_index in range(len(message)): index1 = int(second_step[numbers_index * 2]) index2 = int(second_step[(numbers_index * 2) + 1]) letter = self.numbers_to_letter(index1, index2) encoded_message = encoded_message + letter return encoded_message def decode(self, message: str) -> str: """ Return the decoded version of message according to the polybius cipher >>> BifidCipher().decode('qtltbdxrxlk') == 'testmessage' True """ message = message.lower() message.replace(" ", "") first_step = np.empty(2 * len(message)) for letter_index in range(len(message)): numbers = self.letter_to_numbers(message[letter_index]) first_step[letter_index * 2] = numbers[0] first_step[letter_index * 2 + 1] = numbers[1] second_step = first_step.reshape((2, len(message))) decoded_message = "" for numbers_index in range(len(message)): index1 = int(second_step[0, numbers_index]) index2 = int(second_step[1, numbers_index]) letter = self.numbers_to_letter(index1, index2) decoded_message = decoded_message + letter return decoded_message
#!/usr/bin/env python3 """ The Bifid Cipher uses a Polybius Square to encipher a message in a way that makes it fairly difficult to decipher without knowing the secret. https://www.braingle.com/brainteasers/codes/bifid.php """ import numpy as np class BifidCipher: def __init__(self) -> None: SQUARE = [ # noqa: N806 ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "k"], ["l", "m", "n", "o", "p"], ["q", "r", "s", "t", "u"], ["v", "w", "x", "y", "z"], ] self.SQUARE = np.array(SQUARE) def letter_to_numbers(self, letter: str) -> np.ndarray: """ Return the pair of numbers that represents the given letter in the polybius square >>> np.array_equal(BifidCipher().letter_to_numbers('a'), [1,1]) True >>> np.array_equal(BifidCipher().letter_to_numbers('u'), [4,5]) True """ index1, index2 = np.where(self.SQUARE == letter) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes def numbers_to_letter(self, index1: int, index2: int) -> str: """ Return the letter corresponding to the position [index1, index2] in the polybius square >>> BifidCipher().numbers_to_letter(4, 5) == "u" True >>> BifidCipher().numbers_to_letter(1, 1) == "a" True """ letter = self.SQUARE[index1 - 1, index2 - 1] return letter def encode(self, message: str) -> str: """ Return the encoded version of message according to the polybius cipher >>> BifidCipher().encode('testmessage') == 'qtltbdxrxlk' True >>> BifidCipher().encode('Test Message') == 'qtltbdxrxlk' True >>> BifidCipher().encode('test j') == BifidCipher().encode('test i') True """ message = message.lower() message = message.replace(" ", "") message = message.replace("j", "i") first_step = np.empty((2, len(message))) for letter_index in range(len(message)): numbers = self.letter_to_numbers(message[letter_index]) first_step[0, letter_index] = numbers[0] first_step[1, letter_index] = numbers[1] second_step = first_step.reshape(2 * len(message)) encoded_message = "" for numbers_index in range(len(message)): index1 = int(second_step[numbers_index * 2]) index2 = int(second_step[(numbers_index * 2) + 1]) letter = self.numbers_to_letter(index1, index2) encoded_message = encoded_message + letter return encoded_message def decode(self, message: str) -> str: """ Return the decoded version of message according to the polybius cipher >>> BifidCipher().decode('qtltbdxrxlk') == 'testmessage' True """ message = message.lower() message.replace(" ", "") first_step = np.empty(2 * len(message)) for letter_index in range(len(message)): numbers = self.letter_to_numbers(message[letter_index]) first_step[letter_index * 2] = numbers[0] first_step[letter_index * 2 + 1] = numbers[1] second_step = first_step.reshape((2, len(message))) decoded_message = "" for numbers_index in range(len(message)): index1 = int(second_step[0, numbers_index]) index2 = int(second_step[1, numbers_index]) letter = self.numbers_to_letter(index1, index2) decoded_message = decoded_message + letter return decoded_message
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ with open(os.path.dirname(__file__) + "/p022_names.txt") as file: names = str(file.readlines()[0]) names = names.replace('"', "").split(",") names.sort() name_score = 0 total_score = 0 for i, name in enumerate(names): for letter in name: name_score += ord(letter) - 64 total_score += (i + 1) * name_score name_score = 0 return total_score if __name__ == "__main__": print(solution())
""" Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ with open(os.path.dirname(__file__) + "/p022_names.txt") as file: names = str(file.readlines()[0]) names = names.replace('"', "").split(",") names.sort() name_score = 0 total_score = 0 for i, name in enumerate(names): for letter in name: name_score += ord(letter) - 64 total_score += (i + 1) * name_score name_score = 0 return total_score if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implemented an algorithm using opencv to tone an image with sepia technique """ from cv2 import destroyAllWindows, imread, imshow, waitKey def make_sepia(img, factor: int): """ Function create sepia tone. Source: https://en.wikipedia.org/wiki/Sepia_(color) """ pixel_h, pixel_v = img.shape[0], img.shape[1] def to_grayscale(blue, green, red): """ Helper function to create pixel's greyscale representation Src: https://pl.wikipedia.org/wiki/YUV """ return 0.2126 * red + 0.587 * green + 0.114 * blue def normalize(value): """Helper function to normalize R/G/B value -> return 255 if value > 255""" return min(value, 255) for i in range(pixel_h): for j in range(pixel_v): greyscale = int(to_grayscale(*img[i][j])) img[i][j] = [ normalize(greyscale), normalize(greyscale + factor), normalize(greyscale + 2 * factor), ] return img if __name__ == "__main__": # read original image images = { percentage: imread("image_data/lena.jpg", 1) for percentage in (10, 20, 30, 40) } for percentage, img in images.items(): make_sepia(img, percentage) for percentage, img in images.items(): imshow(f"Original image with sepia (factor: {percentage})", img) waitKey(0) destroyAllWindows()
""" Implemented an algorithm using opencv to tone an image with sepia technique """ from cv2 import destroyAllWindows, imread, imshow, waitKey def make_sepia(img, factor: int): """ Function create sepia tone. Source: https://en.wikipedia.org/wiki/Sepia_(color) """ pixel_h, pixel_v = img.shape[0], img.shape[1] def to_grayscale(blue, green, red): """ Helper function to create pixel's greyscale representation Src: https://pl.wikipedia.org/wiki/YUV """ return 0.2126 * red + 0.587 * green + 0.114 * blue def normalize(value): """Helper function to normalize R/G/B value -> return 255 if value > 255""" return min(value, 255) for i in range(pixel_h): for j in range(pixel_v): greyscale = int(to_grayscale(*img[i][j])) img[i][j] = [ normalize(greyscale), normalize(greyscale + factor), normalize(greyscale + 2 * factor), ] return img if __name__ == "__main__": # read original image images = { percentage: imread("image_data/lena.jpg", 1) for percentage in (10, 20, 30, 40) } for percentage, img in images.items(): make_sepia(img, percentage) for percentage, img in images.items(): imshow(f"Original image with sepia (factor: {percentage})", img) waitKey(0) destroyAllWindows()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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/String-searching_algorithm#Na%C3%AFve_string_search this algorithm tries to find the pattern from every position of the mainString if pattern is found from position i it add it to the answer and does the same for position i+1 Complexity : O(n*m) n=length of main string m=length of pattern string """ def naive_pattern_search(s: str, pattern: str) -> list: """ >>> naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC") [4, 10, 18] >>> naive_pattern_search("ABC", "ABAAABCDBBABCDDEBCABC") [] >>> naive_pattern_search("", "ABC") [] >>> naive_pattern_search("TEST", "TEST") [0] >>> naive_pattern_search("ABCDEGFTEST", "TEST") [7] """ pat_len = len(pattern) position = [] for i in range(len(s) - pat_len + 1): match_found = True for j in range(pat_len): if s[i + j] != pattern[j]: match_found = False break if match_found: position.append(i) return position if __name__ == "__main__": assert naive_pattern_search("ABCDEFG", "DE") == [3] print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
""" https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search this algorithm tries to find the pattern from every position of the mainString if pattern is found from position i it add it to the answer and does the same for position i+1 Complexity : O(n*m) n=length of main string m=length of pattern string """ def naive_pattern_search(s: str, pattern: str) -> list: """ >>> naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC") [4, 10, 18] >>> naive_pattern_search("ABC", "ABAAABCDBBABCDDEBCABC") [] >>> naive_pattern_search("", "ABC") [] >>> naive_pattern_search("TEST", "TEST") [0] >>> naive_pattern_search("ABCDEGFTEST", "TEST") [7] """ pat_len = len(pattern) position = [] for i in range(len(s) - pat_len + 1): match_found = True for j in range(pat_len): if s[i + j] != pattern[j]: match_found = False break if match_found: position.append(i) return position if __name__ == "__main__": assert naive_pattern_search("ABCDEFG", "DE") == [3] print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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): """ Create and initialize Node class instance. >>> Node(20) Node(20) >>> Node("Hello, world!") Node(Hello, world!) >>> Node(None) Node(None) >>> Node(True) Node(True) """ self.data = data self.next = None def __repr__(self) -> str: """ Get the string representation of this node. >>> Node(10).__repr__() 'Node(10)' """ return f"Node({self.data})" class LinkedList: def __init__(self): """ Create and initialize LinkedList class instance. >>> linked_list = LinkedList() """ self.head = None def __iter__(self) -> Any: """ This function is intended for iterators to access and iterate through data inside linked list. >>> linked_list = LinkedList() >>> linked_list.insert_tail("tail") >>> linked_list.insert_tail("tail_1") >>> linked_list.insert_tail("tail_2") >>> for node in linked_list: # __iter__ used here. ... node 'tail' 'tail_1' 'tail_2' """ node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ Return length of linked list i.e. number of nodes >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.insert_tail("tail") >>> len(linked_list) 1 >>> linked_list.insert_head("head") >>> len(linked_list) 2 >>> _ = linked_list.delete_tail() >>> len(linked_list) 1 >>> _ = linked_list.delete_head() >>> len(linked_list) 0 """ return len(tuple(iter(self))) def __repr__(self) -> str: """ String representation/visualization of a Linked Lists >>> linked_list = LinkedList() >>> linked_list.insert_tail(1) >>> linked_list.insert_tail(3) >>> linked_list.__repr__() '1->3' """ return "->".join([str(item) for item in self]) def __getitem__(self, index: int) -> Any: """ Indexing Support. Used to get a node at particular position >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> all(str(linked_list[i]) == str(i) for i in range(0, 10)) True >>> linked_list[-10] Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") for i, node in enumerate(self): if i == index: return node # Used to change the data of a particular node def __setitem__(self, index: int, data: Any) -> None: """ >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> linked_list[0] = 666 >>> linked_list[0] 666 >>> linked_list[5] = -666 >>> linked_list[5] -666 >>> linked_list[-10] = 666 Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] = 666 Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") current = self.head for _ in range(index): current = current.next current.data = data def insert_tail(self, data: Any) -> None: """ Insert data to the end of linked list. >>> linked_list = LinkedList() >>> linked_list.insert_tail("tail") >>> linked_list tail >>> linked_list.insert_tail("tail_2") >>> linked_list tail->tail_2 >>> linked_list.insert_tail("tail_3") >>> linked_list tail->tail_2->tail_3 """ self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: """ Insert data to the beginning of linked list. >>> linked_list = LinkedList() >>> linked_list.insert_head("head") >>> linked_list head >>> linked_list.insert_head("head_2") >>> linked_list head_2->head >>> linked_list.insert_head("head_3") >>> linked_list head_3->head_2->head """ self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: """ Insert data at given index. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.insert_nth(1, "fourth") >>> linked_list first->fourth->second->third >>> linked_list.insert_nth(3, "fifth") >>> linked_list first->fourth->second->fifth->third """ if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = new_node elif index == 0: new_node.next = self.head # link new_node to head self.head = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next new_node.next = temp.next temp.next = new_node def print_list(self) -> None: # print every node data """ This method prints every node data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third """ print(self) def delete_head(self) -> Any: """ Delete the first node and return the node's data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.delete_head() 'first' >>> linked_list second->third >>> linked_list.delete_head() 'second' >>> linked_list third >>> linked_list.delete_head() 'third' >>> linked_list.delete_head() Traceback (most recent call last): ... IndexError: List index out of range. """ return self.delete_nth(0) def delete_tail(self) -> Any: # delete from tail """ Delete the tail end node and return the node's data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.delete_tail() 'third' >>> linked_list first->second >>> linked_list.delete_tail() 'second' >>> linked_list first >>> linked_list.delete_tail() 'first' >>> linked_list.delete_tail() Traceback (most recent call last): ... IndexError: List index out of range. """ return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: """ Delete node at given index and return the node's data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.delete_nth(1) # delete middle 'second' >>> linked_list first->third >>> linked_list.delete_nth(5) # this raises error Traceback (most recent call last): ... IndexError: List index out of range. >>> linked_list.delete_nth(-1) # this also raises error Traceback (most recent call last): ... IndexError: List index out of range. """ if not 0 <= index <= len(self) - 1: # test if index is valid raise IndexError("List index out of range.") delete_node = self.head # default first node if index == 0: self.head = self.head.next else: temp = self.head for _ in range(index - 1): temp = temp.next delete_node = temp.next temp.next = temp.next.next return delete_node.data def is_empty(self) -> bool: """ Check if linked list is empty. >>> linked_list = LinkedList() >>> linked_list.is_empty() True >>> linked_list.insert_head("first") >>> linked_list.is_empty() False """ return self.head is None def reverse(self) -> None: """ This reverses the linked list order. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.reverse() >>> linked_list third->second->first """ prev = None current = self.head while current: # Store the current node's next node. next_node = current.next # Make the current node's next point backwards current.next = prev # Make the previous node be the current node prev = current # Make the current node the next node (to progress iteration) current = next_node # Return prev in order to put the head at the end self.head = prev def test_singly_linked_list() -> None: """ >>> test_singly_linked_list() """ linked_list = LinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(linked_list) == i linked_list.insert_nth(i, i + 1) assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(linked_list) == "->".join(str(i) for i in range(0, 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True for i in range(0, 9): linked_list[i] = -i assert all(linked_list[i] == -i for i in range(0, 9)) is True linked_list.reverse() assert str(linked_list) == "->".join(str(i) for i in range(-8, 1)) def test_singly_linked_list_2() -> None: """ This section of the test used varying data types for input. >>> test_singly_linked_list_2() """ test_input = [ -9, 100, Node(77345112), "dlrow olleH", 7, 5555, 0, -192.55555, "Hello, world!", 77.9, Node(10), None, None, 12.20, ] linked_list = LinkedList() for i in test_input: linked_list.insert_tail(i) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(linked_list) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head result = linked_list.delete_head() assert result == -9 assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail result = linked_list.delete_tail() assert result == 12.2 assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list result = linked_list.delete_nth(10) assert result is None assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("Hello again, world!")) assert ( str(linked_list) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(None) assert ( str(linked_list) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(linked_list) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def main(): from doctest import testmod testmod() linked_list = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(linked_list) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") linked_list[1] = input("Enter New Value: ").strip() print("New list:") print(linked_list) print(f"length of linked_list is : {len(linked_list)}") if __name__ == "__main__": main()
from typing import Any class Node: def __init__(self, data: Any): """ Create and initialize Node class instance. >>> Node(20) Node(20) >>> Node("Hello, world!") Node(Hello, world!) >>> Node(None) Node(None) >>> Node(True) Node(True) """ self.data = data self.next = None def __repr__(self) -> str: """ Get the string representation of this node. >>> Node(10).__repr__() 'Node(10)' """ return f"Node({self.data})" class LinkedList: def __init__(self): """ Create and initialize LinkedList class instance. >>> linked_list = LinkedList() """ self.head = None def __iter__(self) -> Any: """ This function is intended for iterators to access and iterate through data inside linked list. >>> linked_list = LinkedList() >>> linked_list.insert_tail("tail") >>> linked_list.insert_tail("tail_1") >>> linked_list.insert_tail("tail_2") >>> for node in linked_list: # __iter__ used here. ... node 'tail' 'tail_1' 'tail_2' """ node = self.head while node: yield node.data node = node.next def __len__(self) -> int: """ Return length of linked list i.e. number of nodes >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.insert_tail("tail") >>> len(linked_list) 1 >>> linked_list.insert_head("head") >>> len(linked_list) 2 >>> _ = linked_list.delete_tail() >>> len(linked_list) 1 >>> _ = linked_list.delete_head() >>> len(linked_list) 0 """ return len(tuple(iter(self))) def __repr__(self) -> str: """ String representation/visualization of a Linked Lists >>> linked_list = LinkedList() >>> linked_list.insert_tail(1) >>> linked_list.insert_tail(3) >>> linked_list.__repr__() '1->3' """ return "->".join([str(item) for item in self]) def __getitem__(self, index: int) -> Any: """ Indexing Support. Used to get a node at particular position >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> all(str(linked_list[i]) == str(i) for i in range(0, 10)) True >>> linked_list[-10] Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") for i, node in enumerate(self): if i == index: return node # Used to change the data of a particular node def __setitem__(self, index: int, data: Any) -> None: """ >>> linked_list = LinkedList() >>> for i in range(0, 10): ... linked_list.insert_nth(i, i) >>> linked_list[0] = 666 >>> linked_list[0] 666 >>> linked_list[5] = -666 >>> linked_list[5] -666 >>> linked_list[-10] = 666 Traceback (most recent call last): ... ValueError: list index out of range. >>> linked_list[len(linked_list)] = 666 Traceback (most recent call last): ... ValueError: list index out of range. """ if not 0 <= index < len(self): raise ValueError("list index out of range.") current = self.head for _ in range(index): current = current.next current.data = data def insert_tail(self, data: Any) -> None: """ Insert data to the end of linked list. >>> linked_list = LinkedList() >>> linked_list.insert_tail("tail") >>> linked_list tail >>> linked_list.insert_tail("tail_2") >>> linked_list tail->tail_2 >>> linked_list.insert_tail("tail_3") >>> linked_list tail->tail_2->tail_3 """ self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: """ Insert data to the beginning of linked list. >>> linked_list = LinkedList() >>> linked_list.insert_head("head") >>> linked_list head >>> linked_list.insert_head("head_2") >>> linked_list head_2->head >>> linked_list.insert_head("head_3") >>> linked_list head_3->head_2->head """ self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: """ Insert data at given index. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.insert_nth(1, "fourth") >>> linked_list first->fourth->second->third >>> linked_list.insert_nth(3, "fifth") >>> linked_list first->fourth->second->fifth->third """ if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = new_node elif index == 0: new_node.next = self.head # link new_node to head self.head = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next new_node.next = temp.next temp.next = new_node def print_list(self) -> None: # print every node data """ This method prints every node data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third """ print(self) def delete_head(self) -> Any: """ Delete the first node and return the node's data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.delete_head() 'first' >>> linked_list second->third >>> linked_list.delete_head() 'second' >>> linked_list third >>> linked_list.delete_head() 'third' >>> linked_list.delete_head() Traceback (most recent call last): ... IndexError: List index out of range. """ return self.delete_nth(0) def delete_tail(self) -> Any: # delete from tail """ Delete the tail end node and return the node's data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.delete_tail() 'third' >>> linked_list first->second >>> linked_list.delete_tail() 'second' >>> linked_list first >>> linked_list.delete_tail() 'first' >>> linked_list.delete_tail() Traceback (most recent call last): ... IndexError: List index out of range. """ return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: """ Delete node at given index and return the node's data. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.delete_nth(1) # delete middle 'second' >>> linked_list first->third >>> linked_list.delete_nth(5) # this raises error Traceback (most recent call last): ... IndexError: List index out of range. >>> linked_list.delete_nth(-1) # this also raises error Traceback (most recent call last): ... IndexError: List index out of range. """ if not 0 <= index <= len(self) - 1: # test if index is valid raise IndexError("List index out of range.") delete_node = self.head # default first node if index == 0: self.head = self.head.next else: temp = self.head for _ in range(index - 1): temp = temp.next delete_node = temp.next temp.next = temp.next.next return delete_node.data def is_empty(self) -> bool: """ Check if linked list is empty. >>> linked_list = LinkedList() >>> linked_list.is_empty() True >>> linked_list.insert_head("first") >>> linked_list.is_empty() False """ return self.head is None def reverse(self) -> None: """ This reverses the linked list order. >>> linked_list = LinkedList() >>> linked_list.insert_tail("first") >>> linked_list.insert_tail("second") >>> linked_list.insert_tail("third") >>> linked_list first->second->third >>> linked_list.reverse() >>> linked_list third->second->first """ prev = None current = self.head while current: # Store the current node's next node. next_node = current.next # Make the current node's next point backwards current.next = prev # Make the previous node be the current node prev = current # Make the current node the next node (to progress iteration) current = next_node # Return prev in order to put the head at the end self.head = prev def test_singly_linked_list() -> None: """ >>> test_singly_linked_list() """ linked_list = LinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(linked_list) == i linked_list.insert_nth(i, i + 1) assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(linked_list) == "->".join(str(i) for i in range(0, 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) assert all(linked_list[i] == i + 1 for i in range(0, 9)) is True for i in range(0, 9): linked_list[i] = -i assert all(linked_list[i] == -i for i in range(0, 9)) is True linked_list.reverse() assert str(linked_list) == "->".join(str(i) for i in range(-8, 1)) def test_singly_linked_list_2() -> None: """ This section of the test used varying data types for input. >>> test_singly_linked_list_2() """ test_input = [ -9, 100, Node(77345112), "dlrow olleH", 7, 5555, 0, -192.55555, "Hello, world!", 77.9, Node(10), None, None, 12.20, ] linked_list = LinkedList() for i in test_input: linked_list.insert_tail(i) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(linked_list) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head result = linked_list.delete_head() assert result == -9 assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail result = linked_list.delete_tail() assert result == 12.2 assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list result = linked_list.delete_nth(10) assert result is None assert ( str(linked_list) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("Hello again, world!")) assert ( str(linked_list) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(None) assert ( str(linked_list) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(linked_list) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def main(): from doctest import testmod testmod() linked_list = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(linked_list) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") linked_list[1] = input("Enter New Value: ").strip() print("New list:") print(linked_list) print(f"length of linked_list is : {len(linked_list)}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Get CO2 emission data from the UK CarbonIntensity API """ from datetime import date import requests BASE_URL = "https://api.carbonintensity.org.uk/intensity" # Emission in the last half hour def fetch_last_half_hour() -> str: last_half_hour = requests.get(BASE_URL).json()["data"][0] return last_half_hour["intensity"]["actual"] # Emissions in a specific date range def fetch_from_to(start, end) -> list: return requests.get(f"{BASE_URL}/{start}/{end}").json()["data"] if __name__ == "__main__": for entry in fetch_from_to(start=date(2020, 10, 1), end=date(2020, 10, 3)): print("from {from} to {to}: {intensity[actual]}".format(**entry)) print(f"{fetch_last_half_hour() = }")
""" Get CO2 emission data from the UK CarbonIntensity API """ from datetime import date import requests BASE_URL = "https://api.carbonintensity.org.uk/intensity" # Emission in the last half hour def fetch_last_half_hour() -> str: last_half_hour = requests.get(BASE_URL).json()["data"][0] return last_half_hour["intensity"]["actual"] # Emissions in a specific date range def fetch_from_to(start, end) -> list: return requests.get(f"{BASE_URL}/{start}/{end}").json()["data"] if __name__ == "__main__": for entry in fetch_from_to(start=date(2020, 10, 1), end=date(2020, 10, 3)): print("from {from} to {to}: {intensity[actual]}".format(**entry)) print(f"{fetch_last_half_hour() = }")
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
[flake8] max-line-length = 88 max-complexity = 25 extend-ignore = A003 # Class attribute is shadowing a python builtin # Formatting style for `black` E203 # Whitespace before ':' W503 # Line break occurred before a binary operator
[flake8] max-line-length = 88 max-complexity = 25 extend-ignore = A003 # Class attribute is shadowing a python builtin # Formatting style for `black` E203 # Whitespace before ':' W503 # Line break occurred before a binary operator
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
JFIFC     9: }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz?;( 8T1kV]Zïk?;nIN:_5xJ k1i&>Dg$`˯W1{4[y>3B/t=$'ǿS)J47Wg ;󠂊>}+پ[n|OޟnmXL*$ozI}ͳpH1s^oNqWឲcR1[17$DžtDt7yY=u>6~0.-1syx➏kfGtܝFQ3y)Ixδ՟5m4ypkV1Mk \^BpjX_{qxJ{N|;7Od{jߍ9ǠCGuG̗tL׈~ߵo<K/K>{ 3¿>'NKN:n|h09n}1ֿoUhU{M"Ե]3J#ZKw~~R4+F:U=7㯃Cy5&Y ,_Z4B)1y|S[Kb;uT1>_SiK=֝QjMi@RNS'3_}/O߉c^^! 3v aյGUyl⹞? VtxGK@v5AmX>65k|}pB][<OҼ>!ğ㽼A<+T qf_3sOЇ?>cҵk{WWᯊ>feOa|lJ^">+(gO¿-,mf=zu$w^ÿO^u.EYAF0zc6 qoJy2rFO8QEQESLjT@$cWIÝ] -f>t)Fxqn+χOV[9- ޘx wtkz9{n_O|Ui5qw\Z89WuJL6> Rf#pG,~q o{ztLE}`G_ڗg=?txA >.M{^+3}s]k֒HXO J=?l?\Z7"lpK>#յ_ nm. ėz9?louOGy uG.8}{zt^um]x^jZnڨ" N9߀#>&xW٥*nFv]n]mF-]+|+1Hbd]NI[_QhW,AϦ+ʩf|C6a!$v?U0]*G{c3~(¾^cZEr?~x6G,1usP> IwZS1Eec8&z\f5xz0e'JK@_f7|_K68_XbL@b?3iG:<mUE\:b8:W^*|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5OtoUcFOY?}_Je\' r*Ȅ?ʿ;o'y]襯Q:o@GWJoO k O$Fq*Q?U_봵OIF{I&`Qſ1ikxA^7g HW)1X^!]'|-z?/]n$Tgׅ____Q"??0 : 1kdSKǘ|U_j}ެ -s?Ԟ]fP.ܪqy^"4'vFk_ Z<[s޿!B5
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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/Jaro%E2%80%93Winkler_distance""" def jaro_winkler(str1: str, str2: str) -> float: """ Jaro–Winkler distance is a string metric measuring an edit distance between two sequences. Output value is between 0.0 and 1.0. >>> jaro_winkler("martha", "marhta") 0.9611111111111111 >>> jaro_winkler("CRATE", "TRACE") 0.7333333333333334 >>> jaro_winkler("test", "dbdbdbdb") 0.0 >>> jaro_winkler("test", "test") 1.0 >>> jaro_winkler("hello world", "HeLLo W0rlD") 0.6363636363636364 >>> jaro_winkler("test", "") 0.0 >>> jaro_winkler("hello", "world") 0.4666666666666666 >>> jaro_winkler("hell**o", "*world") 0.4365079365079365 """ def get_matched_characters(_str1: str, _str2: str) -> str: matched = [] limit = min(len(_str1), len(_str2)) // 2 for i, l in enumerate(_str1): left = int(max(0, i - limit)) right = int(min(i + limit + 1, len(_str2))) if l in _str2[left:right]: matched.append(l) _str2 = f"{_str2[0:_str2.index(l)]} {_str2[_str2.index(l) + 1:]}" return "".join(matched) # matching characters matching_1 = get_matched_characters(str1, str2) matching_2 = get_matched_characters(str2, str1) match_count = len(matching_1) # transposition transpositions = ( len([(c1, c2) for c1, c2 in zip(matching_1, matching_2) if c1 != c2]) // 2 ) if not match_count: jaro = 0.0 else: jaro = ( 1 / 3 * ( match_count / len(str1) + match_count / len(str2) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters prefix_len = 0 for c1, c2 in zip(str1[:4], str2[:4]): if c1 == c2: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
"""https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance""" def jaro_winkler(str1: str, str2: str) -> float: """ Jaro–Winkler distance is a string metric measuring an edit distance between two sequences. Output value is between 0.0 and 1.0. >>> jaro_winkler("martha", "marhta") 0.9611111111111111 >>> jaro_winkler("CRATE", "TRACE") 0.7333333333333334 >>> jaro_winkler("test", "dbdbdbdb") 0.0 >>> jaro_winkler("test", "test") 1.0 >>> jaro_winkler("hello world", "HeLLo W0rlD") 0.6363636363636364 >>> jaro_winkler("test", "") 0.0 >>> jaro_winkler("hello", "world") 0.4666666666666666 >>> jaro_winkler("hell**o", "*world") 0.4365079365079365 """ def get_matched_characters(_str1: str, _str2: str) -> str: matched = [] limit = min(len(_str1), len(_str2)) // 2 for i, l in enumerate(_str1): left = int(max(0, i - limit)) right = int(min(i + limit + 1, len(_str2))) if l in _str2[left:right]: matched.append(l) _str2 = f"{_str2[0:_str2.index(l)]} {_str2[_str2.index(l) + 1:]}" return "".join(matched) # matching characters matching_1 = get_matched_characters(str1, str2) matching_2 = get_matched_characters(str2, str1) match_count = len(matching_1) # transposition transpositions = ( len([(c1, c2) for c1, c2 in zip(matching_1, matching_2) if c1 != c2]) // 2 ) if not match_count: jaro = 0.0 else: jaro = ( 1 / 3 * ( match_count / len(str1) + match_count / len(str2) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters prefix_len = 0 for c1, c2 in zip(str1[:4], str2[:4]): if c1 == c2: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 092: https://projecteuler.net/problem=92 Square digit chains A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before. For example, 44 → 32 → 13 → 10 → 1 → 1 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89. How many starting numbers below ten million will arrive at 89? """ DIGITS_SQUARED = [digit**2 for digit in range(10)] def next_number(number: int) -> int: """ Returns the next number of the chain by adding the square of each digit to form a new number. For example, if number = 12, next_number() will return 1^2 + 2^2 = 5. Therefore, 5 is the next number of the chain. >>> next_number(44) 32 >>> next_number(10) 1 >>> next_number(32) 13 """ sum_of_digits_squared = 0 while number: sum_of_digits_squared += DIGITS_SQUARED[number % 10] number //= 10 return sum_of_digits_squared CHAINS = {1: True, 58: False} def chain(number: int) -> bool: """ The function generates the chain of numbers until the next number is 1 or 89. For example, if starting number is 44, then the function generates the following chain of numbers: 44 → 32 → 13 → 10 → 1 → 1. Once the next number generated is 1 or 89, the function returns whether or not the next number generated by next_number() is 1. >>> chain(10) True >>> chain(58) False >>> chain(1) True """ if number in CHAINS: return CHAINS[number] number_chain = chain(next_number(number)) CHAINS[number] = number_chain return number_chain def solution(number: int = 10000000) -> int: """ The function returns the number of integers that end up being 89 in each chain. The function accepts a range number and the function checks all the values under value number. >>> solution(100) 80 >>> solution(10000000) 8581146 """ return sum(1 for i in range(1, number) if not chain(i)) if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
""" Project Euler Problem 092: https://projecteuler.net/problem=92 Square digit chains A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before. For example, 44 → 32 → 13 → 10 → 1 → 1 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89. How many starting numbers below ten million will arrive at 89? """ DIGITS_SQUARED = [digit**2 for digit in range(10)] def next_number(number: int) -> int: """ Returns the next number of the chain by adding the square of each digit to form a new number. For example, if number = 12, next_number() will return 1^2 + 2^2 = 5. Therefore, 5 is the next number of the chain. >>> next_number(44) 32 >>> next_number(10) 1 >>> next_number(32) 13 """ sum_of_digits_squared = 0 while number: sum_of_digits_squared += DIGITS_SQUARED[number % 10] number //= 10 return sum_of_digits_squared CHAINS = {1: True, 58: False} def chain(number: int) -> bool: """ The function generates the chain of numbers until the next number is 1 or 89. For example, if starting number is 44, then the function generates the following chain of numbers: 44 → 32 → 13 → 10 → 1 → 1. Once the next number generated is 1 or 89, the function returns whether or not the next number generated by next_number() is 1. >>> chain(10) True >>> chain(58) False >>> chain(1) True """ if number in CHAINS: return CHAINS[number] number_chain = chain(next_number(number)) CHAINS[number] = number_chain return number_chain def solution(number: int = 10000000) -> int: """ The function returns the number of integers that end up being 89 in each chain. The function accepts a range number and the function checks all the values under value number. >>> solution(100) 80 >>> solution(10000000) 8581146 """ return sum(1 for i in range(1, number) if not chain(i)) if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split data = datasets.load_iris() X = np.array(data["data"]) y = np.array(data["target"]) classes = data["target_names"] X_train, X_test, y_train, y_test = train_test_split(X, y) def euclidean_distance(a, b): """ Gives the euclidean distance between two points >>> euclidean_distance([0, 0], [3, 4]) 5.0 >>> euclidean_distance([1, 2, 3], [1, 8, 11]) 10.0 """ return np.linalg.norm(np.array(a) - np.array(b)) def classifier(train_data, train_target, classes, point, k=5): """ Classifies the point using the KNN algorithm k closest points are found (ranked in ascending order of euclidean distance) Params: :train_data: Set of points that are classified into two or more classes :train_target: List of classes in the order of train_data points :classes: Labels of the classes :point: The data point that needs to be classified >>> X_train = [[0, 0], [1, 0], [0, 1], [0.5, 0.5], [3, 3], [2, 3], [3, 2]] >>> y_train = [0, 0, 0, 0, 1, 1, 1] >>> classes = ['A','B']; point = [1.2,1.2] >>> classifier(X_train, y_train, classes,point) 'A' """ data = zip(train_data, train_target) # List of distances of all points from the point to be classified distances = [] for data_point in data: distance = euclidean_distance(data_point[0], point) distances.append((distance, data_point[1])) # Choosing 'k' points with the least distances. votes = [i[1] for i in sorted(distances)[:k]] # Most commonly occurring class among them # is the class into which the point is classified result = Counter(votes).most_common(1)[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split data = datasets.load_iris() X = np.array(data["data"]) y = np.array(data["target"]) classes = data["target_names"] X_train, X_test, y_train, y_test = train_test_split(X, y) def euclidean_distance(a, b): """ Gives the euclidean distance between two points >>> euclidean_distance([0, 0], [3, 4]) 5.0 >>> euclidean_distance([1, 2, 3], [1, 8, 11]) 10.0 """ return np.linalg.norm(np.array(a) - np.array(b)) def classifier(train_data, train_target, classes, point, k=5): """ Classifies the point using the KNN algorithm k closest points are found (ranked in ascending order of euclidean distance) Params: :train_data: Set of points that are classified into two or more classes :train_target: List of classes in the order of train_data points :classes: Labels of the classes :point: The data point that needs to be classified >>> X_train = [[0, 0], [1, 0], [0, 1], [0.5, 0.5], [3, 3], [2, 3], [3, 2]] >>> y_train = [0, 0, 0, 0, 1, 1, 1] >>> classes = ['A','B']; point = [1.2,1.2] >>> classifier(X_train, y_train, classes,point) 'A' """ data = zip(train_data, train_target) # List of distances of all points from the point to be classified distances = [] for data_point in data: distance = euclidean_distance(data_point[0], point) distances.append((distance, data_point[1])) # Choosing 'k' points with the least distances. votes = [i[1] for i in sorted(distances)[:k]] # Most commonly occurring class among them # is the class into which the point is classified result = Counter(votes).most_common(1)[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" author: Christian Bender date: 21.12.2017 class: XORCipher This class implements the XOR-cipher algorithm and provides some useful methods for encrypting and decrypting strings and files. Overview about methods - encrypt : list of char - decrypt : list of char - encrypt_string : str - decrypt_string : str - encrypt_file : boolean - decrypt_file : boolean """ from __future__ import annotations class XORCipher: def __init__(self, key: int = 0): """ simple constructor that receives a key or uses default key = 0 """ # private field self.__key = key def encrypt(self, content: str, key: int) -> list[str]: """ input: 'content' of type string and 'key' of type int output: encrypted string 'content' as a list of chars if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(ch) ^ key) for ch in content] def decrypt(self, content: str, key: int) -> list[str]: """ input: 'content' of type list and 'key' of type int output: decrypted string 'content' as a list of chars if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, list) key = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(ch) ^ key) for ch in content] def encrypt_string(self, content: str, key: int = 0) -> str: """ input: 'content' of type string and 'key' of type int output: encrypted string 'content' if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans def decrypt_string(self, content: str, key: int = 0) -> str: """ input: 'content' of type string and 'key' of type int output: decrypted string 'content' if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans def encrypt_file(self, file: str, key: int = 0) -> bool: """ input: filename (str) and a key (int) output: returns true if encrypt process was successful otherwise false if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(file, str) and isinstance(key, int) try: with open(file) as fin: with open("encrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(line, key)) except OSError: return False return True def decrypt_file(self, file: str, key: int) -> bool: """ input: filename (str) and a key (int) output: returns true if decrypt process was successful otherwise false if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(file, str) and isinstance(key, int) try: with open(file) as fin: with open("decrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(line, key)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
""" author: Christian Bender date: 21.12.2017 class: XORCipher This class implements the XOR-cipher algorithm and provides some useful methods for encrypting and decrypting strings and files. Overview about methods - encrypt : list of char - decrypt : list of char - encrypt_string : str - decrypt_string : str - encrypt_file : boolean - decrypt_file : boolean """ from __future__ import annotations class XORCipher: def __init__(self, key: int = 0): """ simple constructor that receives a key or uses default key = 0 """ # private field self.__key = key def encrypt(self, content: str, key: int) -> list[str]: """ input: 'content' of type string and 'key' of type int output: encrypted string 'content' as a list of chars if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(ch) ^ key) for ch in content] def decrypt(self, content: str, key: int) -> list[str]: """ input: 'content' of type list and 'key' of type int output: decrypted string 'content' as a list of chars if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, list) key = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(ch) ^ key) for ch in content] def encrypt_string(self, content: str, key: int = 0) -> str: """ input: 'content' of type string and 'key' of type int output: encrypted string 'content' if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans def decrypt_string(self, content: str, key: int = 0) -> str: """ input: 'content' of type string and 'key' of type int output: decrypted string 'content' if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans def encrypt_file(self, file: str, key: int = 0) -> bool: """ input: filename (str) and a key (int) output: returns true if encrypt process was successful otherwise false if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(file, str) and isinstance(key, int) try: with open(file) as fin: with open("encrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(line, key)) except OSError: return False return True def decrypt_file(self, file: str, key: int) -> bool: """ input: filename (str) and a key (int) output: returns true if decrypt process was successful otherwise false if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(file, str) and isinstance(key, int) try: with open(file) as fin: with open("decrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(line, key)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import unittest import numpy as np def schur_complement( mat_a: np.ndarray, mat_b: np.ndarray, mat_c: np.ndarray, pseudo_inv: np.ndarray = None, ) -> np.ndarray: """ Schur complement of a symmetric matrix X given as a 2x2 block matrix consisting of matrices A, B and C. Matrix A must be quadratic and non-singular. In case A is singular, a pseudo-inverse may be provided using the pseudo_inv argument. Link to Wiki: https://en.wikipedia.org/wiki/Schur_complement See also Convex Optimization – Boyd and Vandenberghe, A.5.5 >>> import numpy as np >>> a = np.array([[1, 2], [2, 1]]) >>> b = np.array([[0, 3], [3, 0]]) >>> c = np.array([[2, 1], [6, 3]]) >>> schur_complement(a, b, c) array([[ 5., -5.], [ 0., 6.]]) """ shape_a = np.shape(mat_a) shape_b = np.shape(mat_b) shape_c = np.shape(mat_c) if shape_a[0] != shape_b[0]: raise ValueError( f"Expected the same number of rows for A and B. \ Instead found A of size {shape_a} and B of size {shape_b}" ) if shape_b[1] != shape_c[1]: raise ValueError( f"Expected the same number of columns for B and C. \ Instead found B of size {shape_b} and C of size {shape_c}" ) a_inv = pseudo_inv if a_inv is None: try: a_inv = np.linalg.inv(mat_a) except np.linalg.LinAlgError: raise ValueError( "Input matrix A is not invertible. Cannot compute Schur complement." ) return mat_c - mat_b.T @ a_inv @ mat_b class TestSchurComplement(unittest.TestCase): def test_schur_complement(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) s = schur_complement(a, b, c) input_matrix = np.block([[a, b], [b.T, c]]) det_x = np.linalg.det(input_matrix) det_a = np.linalg.det(a) det_s = np.linalg.det(s) self.assertAlmostEqual(det_x, det_a * det_s) def test_improper_a_b_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) with self.assertRaises(ValueError): schur_complement(a, b, c) def test_improper_b_c_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1, 3], [6, 3, 5]]) with self.assertRaises(ValueError): schur_complement(a, b, c) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
import unittest import numpy as np def schur_complement( mat_a: np.ndarray, mat_b: np.ndarray, mat_c: np.ndarray, pseudo_inv: np.ndarray = None, ) -> np.ndarray: """ Schur complement of a symmetric matrix X given as a 2x2 block matrix consisting of matrices A, B and C. Matrix A must be quadratic and non-singular. In case A is singular, a pseudo-inverse may be provided using the pseudo_inv argument. Link to Wiki: https://en.wikipedia.org/wiki/Schur_complement See also Convex Optimization – Boyd and Vandenberghe, A.5.5 >>> import numpy as np >>> a = np.array([[1, 2], [2, 1]]) >>> b = np.array([[0, 3], [3, 0]]) >>> c = np.array([[2, 1], [6, 3]]) >>> schur_complement(a, b, c) array([[ 5., -5.], [ 0., 6.]]) """ shape_a = np.shape(mat_a) shape_b = np.shape(mat_b) shape_c = np.shape(mat_c) if shape_a[0] != shape_b[0]: raise ValueError( f"Expected the same number of rows for A and B. \ Instead found A of size {shape_a} and B of size {shape_b}" ) if shape_b[1] != shape_c[1]: raise ValueError( f"Expected the same number of columns for B and C. \ Instead found B of size {shape_b} and C of size {shape_c}" ) a_inv = pseudo_inv if a_inv is None: try: a_inv = np.linalg.inv(mat_a) except np.linalg.LinAlgError: raise ValueError( "Input matrix A is not invertible. Cannot compute Schur complement." ) return mat_c - mat_b.T @ a_inv @ mat_b class TestSchurComplement(unittest.TestCase): def test_schur_complement(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) s = schur_complement(a, b, c) input_matrix = np.block([[a, b], [b.T, c]]) det_x = np.linalg.det(input_matrix) det_a = np.linalg.det(a) det_s = np.linalg.det(s) self.assertAlmostEqual(det_x, det_a * det_s) def test_improper_a_b_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) with self.assertRaises(ValueError): schur_complement(a, b, c) def test_improper_b_c_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1, 3], [6, 3, 5]]) with self.assertRaises(ValueError): schur_complement(a, b, c) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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/Breadth-first_search pseudo-code: breadth_first_search(graph G, start vertex s): // all nodes initially unexplored mark s as explored let Q = queue data structure, initialized with s while Q is non-empty: remove the first node of Q, call it v for each edge(v, w): // for w in graph[v] if w unexplored: mark w as explored add w to Q (at the end) """ from __future__ import annotations from queue import Queue G = { "A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B"], "E": ["B", "F"], "F": ["C", "E"], } def breadth_first_search(graph: dict, start: str) -> set[str]: """ >>> ''.join(sorted(breadth_first_search(G, 'A'))) 'ABCDEF' """ explored = {start} queue: Queue = Queue() queue.put(start) while not queue.empty(): v = queue.get() for w in graph[v]: if w not in explored: explored.add(w) queue.put(w) return explored if __name__ == "__main__": import doctest doctest.testmod() print(breadth_first_search(G, "A"))
""" https://en.wikipedia.org/wiki/Breadth-first_search pseudo-code: breadth_first_search(graph G, start vertex s): // all nodes initially unexplored mark s as explored let Q = queue data structure, initialized with s while Q is non-empty: remove the first node of Q, call it v for each edge(v, w): // for w in graph[v] if w unexplored: mark w as explored add w to Q (at the end) """ from __future__ import annotations from queue import Queue G = { "A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B"], "E": ["B", "F"], "F": ["C", "E"], } def breadth_first_search(graph: dict, start: str) -> set[str]: """ >>> ''.join(sorted(breadth_first_search(G, 'A'))) 'ABCDEF' """ explored = {start} queue: Queue = Queue() queue.put(start) while not queue.empty(): v = queue.get() for w in graph[v]: if w not in explored: explored.add(w) queue.put(w) return explored if __name__ == "__main__": import doctest doctest.testmod() print(breadth_first_search(G, "A"))
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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/perl use strict; use warnings; use IPC::Open2; # An example hook script to integrate Watchman # (https://facebook.github.io/watchman/) with git to speed up detecting # new and modified files. # # The hook is passed a version (currently 1) and a time in nanoseconds # formatted as a string and outputs to stdout all files that have been # modified since the given time. Paths must be relative to the root of # the working tree and separated by a single NUL. # # To enable this hook, rename this file to "query-watchman" and set # 'git config core.fsmonitor .git/hooks/query-watchman' # my ($version, $time) = @ARGV; # Check the hook interface version if ($version == 1) { # convert nanoseconds to seconds # subtract one second to make sure watchman will return all changes $time = int ($time / 1000000000) - 1; } else { die "Unsupported query-fsmonitor hook version '$version'.\n" . "Falling back to scanning...\n"; } my $git_work_tree; if ($^O =~ 'msys' || $^O =~ 'cygwin') { $git_work_tree = Win32::GetCwd(); $git_work_tree =~ tr/\\/\//; } else { require Cwd; $git_work_tree = Cwd::cwd(); } my $retry = 1; launch_watchman(); sub launch_watchman { my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty') or die "open2() failed: $!\n" . "Falling back to scanning...\n"; # In the query expression below we're asking for names of files that # changed since $time but were not transient (ie created after # $time but no longer exist). # # To accomplish this, we're using the "since" generator to use the # recency index to select candidate nodes and "fields" to limit the # output to file names only. my $query = <<" END"; ["query", "$git_work_tree", { "since": $time, "fields": ["name"] }] END print CHLD_IN $query; close CHLD_IN; my $response = do {local $/; <CHLD_OUT>}; die "Watchman: command returned no output.\n" . "Falling back to scanning...\n" if $response eq ""; die "Watchman: command returned invalid output: $response\n" . "Falling back to scanning...\n" unless $response =~ /^\{/; my $json_pkg; eval { require JSON::XS; $json_pkg = "JSON::XS"; 1; } or do { require JSON::PP; $json_pkg = "JSON::PP"; }; my $o = $json_pkg->new->utf8->decode($response); if ($retry > 0 and $o->{error} and $o->{error} =~ m/unable to resolve root .* directory (.*) is not watched/) { print STDERR "Adding '$git_work_tree' to watchman's watch list.\n"; $retry--; qx/watchman watch "$git_work_tree"/; die "Failed to make watchman watch '$git_work_tree'.\n" . "Falling back to scanning...\n" if $? != 0; # Watchman will always return all files on the first query so # return the fast "everything is dirty" flag to git and do the # Watchman query just to get it over with now so we won't pay # the cost in git to look up each individual file. print "/\0"; eval { launch_watchman() }; exit 0; } die "Watchman: $o->{error}.\n" . "Falling back to scanning...\n" if $o->{error}; binmode STDOUT, ":utf8"; local $, = "\0"; print @{$o->{files}}; }
#!/usr/bin/perl use strict; use warnings; use IPC::Open2; # An example hook script to integrate Watchman # (https://facebook.github.io/watchman/) with git to speed up detecting # new and modified files. # # The hook is passed a version (currently 1) and a time in nanoseconds # formatted as a string and outputs to stdout all files that have been # modified since the given time. Paths must be relative to the root of # the working tree and separated by a single NUL. # # To enable this hook, rename this file to "query-watchman" and set # 'git config core.fsmonitor .git/hooks/query-watchman' # my ($version, $time) = @ARGV; # Check the hook interface version if ($version == 1) { # convert nanoseconds to seconds # subtract one second to make sure watchman will return all changes $time = int ($time / 1000000000) - 1; } else { die "Unsupported query-fsmonitor hook version '$version'.\n" . "Falling back to scanning...\n"; } my $git_work_tree; if ($^O =~ 'msys' || $^O =~ 'cygwin') { $git_work_tree = Win32::GetCwd(); $git_work_tree =~ tr/\\/\//; } else { require Cwd; $git_work_tree = Cwd::cwd(); } my $retry = 1; launch_watchman(); sub launch_watchman { my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty') or die "open2() failed: $!\n" . "Falling back to scanning...\n"; # In the query expression below we're asking for names of files that # changed since $time but were not transient (ie created after # $time but no longer exist). # # To accomplish this, we're using the "since" generator to use the # recency index to select candidate nodes and "fields" to limit the # output to file names only. my $query = <<" END"; ["query", "$git_work_tree", { "since": $time, "fields": ["name"] }] END print CHLD_IN $query; close CHLD_IN; my $response = do {local $/; <CHLD_OUT>}; die "Watchman: command returned no output.\n" . "Falling back to scanning...\n" if $response eq ""; die "Watchman: command returned invalid output: $response\n" . "Falling back to scanning...\n" unless $response =~ /^\{/; my $json_pkg; eval { require JSON::XS; $json_pkg = "JSON::XS"; 1; } or do { require JSON::PP; $json_pkg = "JSON::PP"; }; my $o = $json_pkg->new->utf8->decode($response); if ($retry > 0 and $o->{error} and $o->{error} =~ m/unable to resolve root .* directory (.*) is not watched/) { print STDERR "Adding '$git_work_tree' to watchman's watch list.\n"; $retry--; qx/watchman watch "$git_work_tree"/; die "Failed to make watchman watch '$git_work_tree'.\n" . "Falling back to scanning...\n" if $? != 0; # Watchman will always return all files on the first query so # return the fast "everything is dirty" flag to git and do the # Watchman query just to get it over with now so we won't pay # the cost in git to look up each individual file. print "/\0"; eval { launch_watchman() }; exit 0; } die "Watchman: $o->{error}.\n" . "Falling back to scanning...\n" if $o->{error}; binmode STDOUT, ":utf8"; local $, = "\0"; print @{$o->{files}}; }
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from collections import deque def tarjan(g): """ Tarjan's algo for finding strongly connected components in a directed graph Uses two main attributes of each node to track reachability, the index of that node within a component(index), and the lowest index reachable from that node(lowlink). We then perform a dfs of the each component making sure to update these parameters for each node and saving the nodes we visit on the way. If ever we find that the lowest reachable node from a current node is equal to the index of the current node then it must be the root of a strongly connected component and so we save it and it's equireachable vertices as a strongly connected component. Complexity: strong_connect() is called at most once for each node and has a complexity of O(|E|) as it is DFS. Therefore this has complexity O(|V| + |E|) for a graph G = (V, E) """ n = len(g) stack = deque() on_stack = [False for _ in range(n)] index_of = [-1 for _ in range(n)] lowlink_of = index_of[:] def strong_connect(v, index, components): index_of[v] = index # the number when this node is seen lowlink_of[v] = index # lowest rank node reachable from here index += 1 stack.append(v) on_stack[v] = True for w in g[v]: if index_of[w] == -1: index = strong_connect(w, index, components) lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: component = [] w = stack.pop() on_stack[w] = False component.append(w) while w != v: w = stack.pop() on_stack[w] = False component.append(w) components.append(component) return index components = [] for v in range(n): if index_of[v] == -1: strong_connect(v, 0, components) return components def create_graph(n, edges): g = [[] for _ in range(n)] for u, v in edges: g[u].append(v) return g if __name__ == "__main__": # Test n_vertices = 7 source = [0, 0, 1, 2, 3, 3, 4, 4, 6] target = [1, 3, 2, 0, 1, 4, 5, 6, 5] edges = [(u, v) for u, v in zip(source, target)] g = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
from collections import deque def tarjan(g): """ Tarjan's algo for finding strongly connected components in a directed graph Uses two main attributes of each node to track reachability, the index of that node within a component(index), and the lowest index reachable from that node(lowlink). We then perform a dfs of the each component making sure to update these parameters for each node and saving the nodes we visit on the way. If ever we find that the lowest reachable node from a current node is equal to the index of the current node then it must be the root of a strongly connected component and so we save it and it's equireachable vertices as a strongly connected component. Complexity: strong_connect() is called at most once for each node and has a complexity of O(|E|) as it is DFS. Therefore this has complexity O(|V| + |E|) for a graph G = (V, E) """ n = len(g) stack = deque() on_stack = [False for _ in range(n)] index_of = [-1 for _ in range(n)] lowlink_of = index_of[:] def strong_connect(v, index, components): index_of[v] = index # the number when this node is seen lowlink_of[v] = index # lowest rank node reachable from here index += 1 stack.append(v) on_stack[v] = True for w in g[v]: if index_of[w] == -1: index = strong_connect(w, index, components) lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: component = [] w = stack.pop() on_stack[w] = False component.append(w) while w != v: w = stack.pop() on_stack[w] = False component.append(w) components.append(component) return index components = [] for v in range(n): if index_of[v] == -1: strong_connect(v, 0, components) return components def create_graph(n, edges): g = [[] for _ in range(n)] for u, v in edges: g[u].append(v) return g if __name__ == "__main__": # Test n_vertices = 7 source = [0, 0, 1, 2, 3, 3, 4, 4, 6] target = [1, 3, 2, 0, 1, 4, 5, 6, 5] edges = [(u, v) for u, v in zip(source, target)] g = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Numerical integration or quadrature for a smooth function f with known values at x_i This method is the classical approach of suming 'Equally Spaced Abscissas' method 2: "Simpson Rule" """ def method_2(boundary, steps): # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 3.0) * f(a) cnt = 2 for i in x_i: y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i) cnt += 1 y += (h / 3.0) * f(b) return y def make_points(a, b, h): x = a + h while x < (b - h): yield x x = x + h def f(x): # enter your function here y = (x - 0) * (x - 0) return y def main(): a = 0.0 # Lower bound of integration b = 1.0 # Upper bound of integration steps = 10.0 # define number of steps or resolution boundary = [a, b] # define boundary of integration y = method_2(boundary, steps) print(f"y = {y}") if __name__ == "__main__": main()
""" Numerical integration or quadrature for a smooth function f with known values at x_i This method is the classical approach of suming 'Equally Spaced Abscissas' method 2: "Simpson Rule" """ def method_2(boundary, steps): # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 3.0) * f(a) cnt = 2 for i in x_i: y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i) cnt += 1 y += (h / 3.0) * f(b) return y def make_points(a, b, h): x = a + h while x < (b - h): yield x x = x + h def f(x): # enter your function here y = (x - 0) * (x - 0) return y def main(): a = 0.0 # Lower bound of integration b = 1.0 # Upper bound of integration steps = 10.0 # define number of steps or resolution boundary = [a, b] # define boundary of integration y = method_2(boundary, steps) print(f"y = {y}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Minimax helps to achieve maximum score in a game by checking all possible moves depth is current depth in game tree. nodeIndex is index of current node in scores[]. if move is of maximizer return true else false leaves of game tree is stored in scores[] height is maximum height of Game tree """ from __future__ import annotations import math def minimax( depth: int, node_index: int, is_max: bool, scores: list[int], height: float ) -> int: """ >>> import math >>> scores = [90, 23, 6, 33, 21, 65, 123, 34423] >>> height = math.log(len(scores), 2) >>> minimax(0, 0, True, scores, height) 65 >>> minimax(-1, 0, True, scores, height) Traceback (most recent call last): ... ValueError: Depth cannot be less than 0 >>> minimax(0, 0, True, [], 2) Traceback (most recent call last): ... ValueError: Scores cannot be empty >>> scores = [3, 5, 2, 9, 12, 5, 23, 23] >>> height = math.log(len(scores), 2) >>> minimax(0, 0, True, scores, height) 12 """ if depth < 0: raise ValueError("Depth cannot be less than 0") if len(scores) == 0: raise ValueError("Scores cannot be empty") if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1, node_index * 2, False, scores, height), minimax(depth + 1, node_index * 2 + 1, False, scores, height), ) return min( minimax(depth + 1, node_index * 2, True, scores, height), minimax(depth + 1, node_index * 2 + 1, True, scores, height), ) def main() -> None: scores = [90, 23, 6, 33, 21, 65, 123, 34423] height = math.log(len(scores), 2) print("Optimal value : ", end="") print(minimax(0, 0, True, scores, height)) if __name__ == "__main__": import doctest doctest.testmod() main()
""" Minimax helps to achieve maximum score in a game by checking all possible moves depth is current depth in game tree. nodeIndex is index of current node in scores[]. if move is of maximizer return true else false leaves of game tree is stored in scores[] height is maximum height of Game tree """ from __future__ import annotations import math def minimax( depth: int, node_index: int, is_max: bool, scores: list[int], height: float ) -> int: """ >>> import math >>> scores = [90, 23, 6, 33, 21, 65, 123, 34423] >>> height = math.log(len(scores), 2) >>> minimax(0, 0, True, scores, height) 65 >>> minimax(-1, 0, True, scores, height) Traceback (most recent call last): ... ValueError: Depth cannot be less than 0 >>> minimax(0, 0, True, [], 2) Traceback (most recent call last): ... ValueError: Scores cannot be empty >>> scores = [3, 5, 2, 9, 12, 5, 23, 23] >>> height = math.log(len(scores), 2) >>> minimax(0, 0, True, scores, height) 12 """ if depth < 0: raise ValueError("Depth cannot be less than 0") if len(scores) == 0: raise ValueError("Scores cannot be empty") if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1, node_index * 2, False, scores, height), minimax(depth + 1, node_index * 2 + 1, False, scores, height), ) return min( minimax(depth + 1, node_index * 2, True, scores, height), minimax(depth + 1, node_index * 2 + 1, True, scores, height), ) def main() -> None: scores = [90, 23, 6, 33, 21, 65, 123, 34423] height = math.log(len(scores), 2) print("Optimal value : ", end="") print(minimax(0, 0, True, scores, height)) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-,16,12,21,-,-,- 16,-,-,17,20,-,- 12,-,-,28,-,31,- 21,17,28,-,18,19,23 -,20,-,18,-,-,11 -,-,31,19,-,-,27 -,-,-,23,11,27,-
-,16,12,21,-,-,- 16,-,-,17,20,-,- 12,-,-,28,-,31,- 21,17,28,-,18,19,23 -,20,-,18,-,-,11 -,-,31,19,-,-,27 -,-,-,23,11,27,-
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Output: Enter an Infix Equation = a + b ^c Symbol | Stack | Postfix ---------------------------- c | | c ^ | ^ | c b | ^ | cb + | + | cb^ a | + | cb^a | | cb^a+ a+b^c (Infix) -> +a^bc (Prefix) """ def infix_2_postfix(infix): stack = [] post_fix = [] priority = { "^": 3, "*": 2, "/": 2, "%": 2, "+": 1, "-": 1, } # Priority of each operator print_width = len(infix) if (len(infix) > 7) else 7 # Print table header for output print( "Symbol".center(8), "Stack".center(print_width), "Postfix".center(print_width), sep=" | ", ) print("-" * (print_width * 3 + 7)) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(x) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(x) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop()) # Pop stack & add the content to Postfix stack.pop() else: if len(stack) == 0: stack.append(x) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(stack) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop()) # pop stack & add to Postfix stack.append(x) # push x to stack print( x.center(8), ("".join(stack)).ljust(print_width), ("".join(post_fix)).ljust(print_width), sep=" | ", ) # Output in tabular format while len(stack) > 0: # while stack is not empty post_fix.append(stack.pop()) # pop stack & add to Postfix print( " ".center(8), ("".join(stack)).ljust(print_width), ("".join(post_fix)).ljust(print_width), sep=" | ", ) # Output in tabular format return "".join(post_fix) # return Postfix as str def infix_2_prefix(infix): infix = list(infix[::-1]) # reverse the infix equation for i in range(len(infix)): if infix[i] == "(": infix[i] = ")" # change "(" to ")" elif infix[i] == ")": infix[i] = "(" # change ")" to "(" return (infix_2_postfix("".join(infix)))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": Infix = input("\nEnter an Infix Equation = ") # Input an Infix equation Infix = "".join(Infix.split()) # Remove spaces from the input print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
""" Output: Enter an Infix Equation = a + b ^c Symbol | Stack | Postfix ---------------------------- c | | c ^ | ^ | c b | ^ | cb + | + | cb^ a | + | cb^a | | cb^a+ a+b^c (Infix) -> +a^bc (Prefix) """ def infix_2_postfix(infix): stack = [] post_fix = [] priority = { "^": 3, "*": 2, "/": 2, "%": 2, "+": 1, "-": 1, } # Priority of each operator print_width = len(infix) if (len(infix) > 7) else 7 # Print table header for output print( "Symbol".center(8), "Stack".center(print_width), "Postfix".center(print_width), sep=" | ", ) print("-" * (print_width * 3 + 7)) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(x) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(x) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop()) # Pop stack & add the content to Postfix stack.pop() else: if len(stack) == 0: stack.append(x) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(stack) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop()) # pop stack & add to Postfix stack.append(x) # push x to stack print( x.center(8), ("".join(stack)).ljust(print_width), ("".join(post_fix)).ljust(print_width), sep=" | ", ) # Output in tabular format while len(stack) > 0: # while stack is not empty post_fix.append(stack.pop()) # pop stack & add to Postfix print( " ".center(8), ("".join(stack)).ljust(print_width), ("".join(post_fix)).ljust(print_width), sep=" | ", ) # Output in tabular format return "".join(post_fix) # return Postfix as str def infix_2_prefix(infix): infix = list(infix[::-1]) # reverse the infix equation for i in range(len(infix)): if infix[i] == "(": infix[i] = ")" # change "(" to ")" elif infix[i] == ")": infix[i] = "(" # change ")" to "(" return (infix_2_postfix("".join(infix)))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": Infix = input("\nEnter an Infix Equation = ") # Input an Infix equation Infix = "".join(Infix.split()) # Remove spaces from the input print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Just to check """ def add(a: float, b: float) -> float: """ >>> add(2, 2) 4 >>> add(2, -2) 0 """ return a + b if __name__ == "__main__": a = 5 b = 6 print(f"The sum of {a} + {b} is {add(a, b)}")
""" Just to check """ def add(a: float, b: float) -> float: """ >>> add(2, 2) 4 >>> add(2, -2) 0 """ return a + b if __name__ == "__main__": a = 5 b = 6 print(f"The sum of {a} + {b} is {add(a, b)}")
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 DIRECTIONS = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] # function to search the path def search( grid: list[list[int]], init: list[int], goal: list[int], cost: int, heuristic: list[list[int]], ) -> tuple[list[list[int]], list[list[int]]]: closed = [ [0 for col in range(len(grid[0]))] for row in range(len(grid)) ] # the reference grid closed[init[0]][init[1]] = 1 action = [ [0 for col in range(len(grid[0]))] for row in range(len(grid)) ] # the action grid x = init[0] y = init[1] g = 0 f = g + heuristic[x][y] # cost from starting cell to destination cell cell = [[f, g, x, y]] found = False # flag that is set when search is complete resign = False # flag set if we can't find expand while not found and not resign: if len(cell) == 0: raise ValueError("Algorithm is unable to find solution") else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() next_cell = cell.pop() x = next_cell[2] y = next_cell[3] g = next_cell[1] if x == goal[0] and y == goal[1]: found = True else: for i in range(len(DIRECTIONS)): # to try out different valid actions x2 = x + DIRECTIONS[i][0] y2 = y + DIRECTIONS[i][1] if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]): if closed[x2][y2] == 0 and grid[x2][y2] == 0: g2 = g + cost f2 = g2 + heuristic[x2][y2] cell.append([f2, g2, x2, y2]) closed[x2][y2] = 1 action[x2][y2] = i invpath = [] x = goal[0] y = goal[1] invpath.append([x, y]) # we get the reverse path from here while x != init[0] or y != init[1]: x2 = x - DIRECTIONS[action[x][y]][0] y2 = y - DIRECTIONS[action[x][y]][1] x = x2 y = y2 invpath.append([x, y]) path = [] for i in range(len(invpath)): path.append(invpath[len(invpath) - 1 - i]) return path, action if __name__ == "__main__": grid = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] init = [0, 0] # all coordinates are given in format [y,x] goal = [len(grid) - 1, len(grid[0]) - 1] cost = 1 # the cost map which pushes the path closer to the goal heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map heuristic[i][j] = 99 path, action = search(grid, init, goal, cost, heuristic) print("ACTION MAP") for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
from __future__ import annotations DIRECTIONS = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] # function to search the path def search( grid: list[list[int]], init: list[int], goal: list[int], cost: int, heuristic: list[list[int]], ) -> tuple[list[list[int]], list[list[int]]]: closed = [ [0 for col in range(len(grid[0]))] for row in range(len(grid)) ] # the reference grid closed[init[0]][init[1]] = 1 action = [ [0 for col in range(len(grid[0]))] for row in range(len(grid)) ] # the action grid x = init[0] y = init[1] g = 0 f = g + heuristic[x][y] # cost from starting cell to destination cell cell = [[f, g, x, y]] found = False # flag that is set when search is complete resign = False # flag set if we can't find expand while not found and not resign: if len(cell) == 0: raise ValueError("Algorithm is unable to find solution") else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() next_cell = cell.pop() x = next_cell[2] y = next_cell[3] g = next_cell[1] if x == goal[0] and y == goal[1]: found = True else: for i in range(len(DIRECTIONS)): # to try out different valid actions x2 = x + DIRECTIONS[i][0] y2 = y + DIRECTIONS[i][1] if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]): if closed[x2][y2] == 0 and grid[x2][y2] == 0: g2 = g + cost f2 = g2 + heuristic[x2][y2] cell.append([f2, g2, x2, y2]) closed[x2][y2] = 1 action[x2][y2] = i invpath = [] x = goal[0] y = goal[1] invpath.append([x, y]) # we get the reverse path from here while x != init[0] or y != init[1]: x2 = x - DIRECTIONS[action[x][y]][0] y2 = y - DIRECTIONS[action[x][y]][1] x = x2 y = y2 invpath.append([x, y]) path = [] for i in range(len(invpath)): path.append(invpath[len(invpath) - 1 - i]) return path, action if __name__ == "__main__": grid = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] init = [0, 0] # all coordinates are given in format [y,x] goal = [len(grid) - 1, len(grid[0]) - 1] cost = 1 # the cost map which pushes the path closer to the goal heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map heuristic[i][j] = 99 path, action = search(grid, init, goal, cost, heuristic) print("ACTION MAP") for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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_difference(a: list[int]) -> tuple[int, int]: """ We are given an array A[1..n] of integers, n >= 1. We want to find a pair of indices (i, j) such that 1 <= i <= j <= n and A[j] - A[i] is as large as possible. Explanation: https://www.geeksforgeeks.org/maximum-difference-between-two-elements/ >>> max_difference([5, 11, 2, 1, 7, 9, 0, 7]) (1, 9) """ # base case if len(a) == 1: return a[0], a[0] else: # split A into half. first = a[: len(a) // 2] second = a[len(a) // 2 :] # 2 sub problems, 1/2 of original size. small1, big1 = max_difference(first) small2, big2 = max_difference(second) # get min of first and max of second # linear time min_first = min(first) max_second = max(second) # 3 cases, either (small1, big1), # (min_first, max_second), (small2, big2) # constant comparisons if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1: return small2, big2 elif big1 - small1 > max_second - min_first: return small1, big1 else: return min_first, max_second if __name__ == "__main__": import doctest doctest.testmod()
def max_difference(a: list[int]) -> tuple[int, int]: """ We are given an array A[1..n] of integers, n >= 1. We want to find a pair of indices (i, j) such that 1 <= i <= j <= n and A[j] - A[i] is as large as possible. Explanation: https://www.geeksforgeeks.org/maximum-difference-between-two-elements/ >>> max_difference([5, 11, 2, 1, 7, 9, 0, 7]) (1, 9) """ # base case if len(a) == 1: return a[0], a[0] else: # split A into half. first = a[: len(a) // 2] second = a[len(a) // 2 :] # 2 sub problems, 1/2 of original size. small1, big1 = max_difference(first) small2, big2 = max_difference(second) # get min of first and max of second # linear time min_first = min(first) max_second = max(second) # 3 cases, either (small1, big1), # (min_first, max_second), (small2, big2) # constant comparisons if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1: return small2, big2 elif big1 - small1 > max_second - min_first: return small1, big1 else: return min_first, max_second if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Conversion of volume units. Available Units:- Cubic metre,Litre,KiloLitre,Gallon,Cubic yard,Cubic foot,cup USAGE : -> Import this file into their respective project. -> Use the function length_conversion() for conversion of volume units. -> Parameters : -> value : The number of from units you want to convert -> from_type : From which type you want to convert -> to_type : To which type you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Cubic_metre -> Wikipedia reference: https://en.wikipedia.org/wiki/Litre -> Wikipedia reference: https://en.wiktionary.org/wiki/kilolitre -> Wikipedia reference: https://en.wikipedia.org/wiki/Gallon -> Wikipedia reference: https://en.wikipedia.org/wiki/Cubic_yard -> Wikipedia reference: https://en.wikipedia.org/wiki/Cubic_foot -> Wikipedia reference: https://en.wikipedia.org/wiki/Cup_(unit) """ from collections import namedtuple from_to = namedtuple("from_to", "from_ to") METRIC_CONVERSION = { "cubicmeter": from_to(1, 1), "litre": from_to(0.001, 1000), "kilolitre": from_to(1, 1), "gallon": from_to(0.00454, 264.172), "cubicyard": from_to(0.76455, 1.30795), "cubicfoot": from_to(0.028, 35.3147), "cup": from_to(0.000236588, 4226.75), } def volume_conversion(value: float, from_type: str, to_type: str) -> float: """ Conversion between volume units. >>> volume_conversion(4, "cubicmeter", "litre") 4000 >>> volume_conversion(1, "litre", "gallon") 0.264172 >>> volume_conversion(1, "kilolitre", "cubicmeter") 1 >>> volume_conversion(3, "gallon", "cubicyard") 0.017814279 >>> volume_conversion(2, "cubicyard", "litre") 1529.1 >>> volume_conversion(4, "cubicfoot", "cup") 473.396 >>> volume_conversion(1, "cup", "kilolitre") 0.000236588 >>> volume_conversion(4, "wrongUnit", "litre") Traceback (most recent call last): ... ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are: cubicmeter, litre, kilolitre, gallon, cubicyard, cubicfoot, cup """ if from_type not in METRIC_CONVERSION: raise ValueError( f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + ", ".join(METRIC_CONVERSION) ) if to_type not in METRIC_CONVERSION: raise ValueError( f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + ", ".join(METRIC_CONVERSION) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
""" Conversion of volume units. Available Units:- Cubic metre,Litre,KiloLitre,Gallon,Cubic yard,Cubic foot,cup USAGE : -> Import this file into their respective project. -> Use the function length_conversion() for conversion of volume units. -> Parameters : -> value : The number of from units you want to convert -> from_type : From which type you want to convert -> to_type : To which type you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Cubic_metre -> Wikipedia reference: https://en.wikipedia.org/wiki/Litre -> Wikipedia reference: https://en.wiktionary.org/wiki/kilolitre -> Wikipedia reference: https://en.wikipedia.org/wiki/Gallon -> Wikipedia reference: https://en.wikipedia.org/wiki/Cubic_yard -> Wikipedia reference: https://en.wikipedia.org/wiki/Cubic_foot -> Wikipedia reference: https://en.wikipedia.org/wiki/Cup_(unit) """ from collections import namedtuple from_to = namedtuple("from_to", "from_ to") METRIC_CONVERSION = { "cubicmeter": from_to(1, 1), "litre": from_to(0.001, 1000), "kilolitre": from_to(1, 1), "gallon": from_to(0.00454, 264.172), "cubicyard": from_to(0.76455, 1.30795), "cubicfoot": from_to(0.028, 35.3147), "cup": from_to(0.000236588, 4226.75), } def volume_conversion(value: float, from_type: str, to_type: str) -> float: """ Conversion between volume units. >>> volume_conversion(4, "cubicmeter", "litre") 4000 >>> volume_conversion(1, "litre", "gallon") 0.264172 >>> volume_conversion(1, "kilolitre", "cubicmeter") 1 >>> volume_conversion(3, "gallon", "cubicyard") 0.017814279 >>> volume_conversion(2, "cubicyard", "litre") 1529.1 >>> volume_conversion(4, "cubicfoot", "cup") 473.396 >>> volume_conversion(1, "cup", "kilolitre") 0.000236588 >>> volume_conversion(4, "wrongUnit", "litre") Traceback (most recent call last): ... ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are: cubicmeter, litre, kilolitre, gallon, cubicyard, cubicfoot, cup """ if from_type not in METRIC_CONVERSION: raise ValueError( f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + ", ".join(METRIC_CONVERSION) ) if to_type not in METRIC_CONVERSION: raise ValueError( f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + ", ".join(METRIC_CONVERSION) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import cv2 import numpy as np from digital_image_processing.filters.convolve import img_convolve from digital_image_processing.filters.sobel_filter import sobel_filter PI = 180 def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = np.mgrid[0 - center : k_size - center, 0 - center : k_size - center] g = ( 1 / (2 * np.pi * sigma) * np.exp(-(np.square(x) + np.square(y)) / (2 * np.square(sigma))) ) return g def canny(image, threshold_low=15, threshold_high=30, weak=128, strong=255): image_row, image_col = image.shape[0], image.shape[1] # gaussian_filter gaussian_out = img_convolve(image, gen_gaussian_kernel(9, sigma=1.4)) # get the gradient and degree by sobel_filter sobel_grad, sobel_theta = sobel_filter(gaussian_out) gradient_direction = np.rad2deg(sobel_theta) gradient_direction += PI dst = np.zeros((image_row, image_col)) """ Non-maximum suppression. If the edge strength of the current pixel is the largest compared to the other pixels in the mask with the same direction, the value will be preserved. Otherwise, the value will be suppressed. """ for row in range(1, image_row - 1): for col in range(1, image_col - 1): direction = gradient_direction[row, col] if ( 0 <= direction < 22.5 or 15 * PI / 8 <= direction <= 2 * PI or 7 * PI / 8 <= direction <= 9 * PI / 8 ): w = sobel_grad[row, col - 1] e = sobel_grad[row, col + 1] if sobel_grad[row, col] >= w and sobel_grad[row, col] >= e: dst[row, col] = sobel_grad[row, col] elif (PI / 8 <= direction < 3 * PI / 8) or ( 9 * PI / 8 <= direction < 11 * PI / 8 ): sw = sobel_grad[row + 1, col - 1] ne = sobel_grad[row - 1, col + 1] if sobel_grad[row, col] >= sw and sobel_grad[row, col] >= ne: dst[row, col] = sobel_grad[row, col] elif (3 * PI / 8 <= direction < 5 * PI / 8) or ( 11 * PI / 8 <= direction < 13 * PI / 8 ): n = sobel_grad[row - 1, col] s = sobel_grad[row + 1, col] if sobel_grad[row, col] >= n and sobel_grad[row, col] >= s: dst[row, col] = sobel_grad[row, col] elif (5 * PI / 8 <= direction < 7 * PI / 8) or ( 13 * PI / 8 <= direction < 15 * PI / 8 ): nw = sobel_grad[row - 1, col - 1] se = sobel_grad[row + 1, col + 1] if sobel_grad[row, col] >= nw and sobel_grad[row, col] >= se: dst[row, col] = sobel_grad[row, col] """ High-Low threshold detection. If an edge pixel’s gradient value is higher than the high threshold value, it is marked as a strong edge pixel. If an edge pixel’s gradient value is smaller than the high threshold value and larger than the low threshold value, it is marked as a weak edge pixel. If an edge pixel's value is smaller than the low threshold value, it will be suppressed. """ if dst[row, col] >= threshold_high: dst[row, col] = strong elif dst[row, col] <= threshold_low: dst[row, col] = 0 else: dst[row, col] = weak """ Edge tracking. Usually a weak edge pixel caused from true edges will be connected to a strong edge pixel while noise responses are unconnected. As long as there is one strong edge pixel that is involved in its 8-connected neighborhood, that weak edge point can be identified as one that should be preserved. """ for row in range(1, image_row): for col in range(1, image_col): if dst[row, col] == weak: if 255 in ( dst[row, col + 1], dst[row, col - 1], dst[row - 1, col], dst[row + 1, col], dst[row - 1, col - 1], dst[row + 1, col - 1], dst[row - 1, col + 1], dst[row + 1, col + 1], ): dst[row, col] = strong else: dst[row, col] = 0 return dst if __name__ == "__main__": # read original image in gray mode lena = cv2.imread(r"../image_data/lena.jpg", 0) # canny edge detection canny_dst = canny(lena) cv2.imshow("canny", canny_dst) cv2.waitKey(0)
import cv2 import numpy as np from digital_image_processing.filters.convolve import img_convolve from digital_image_processing.filters.sobel_filter import sobel_filter PI = 180 def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = np.mgrid[0 - center : k_size - center, 0 - center : k_size - center] g = ( 1 / (2 * np.pi * sigma) * np.exp(-(np.square(x) + np.square(y)) / (2 * np.square(sigma))) ) return g def canny(image, threshold_low=15, threshold_high=30, weak=128, strong=255): image_row, image_col = image.shape[0], image.shape[1] # gaussian_filter gaussian_out = img_convolve(image, gen_gaussian_kernel(9, sigma=1.4)) # get the gradient and degree by sobel_filter sobel_grad, sobel_theta = sobel_filter(gaussian_out) gradient_direction = np.rad2deg(sobel_theta) gradient_direction += PI dst = np.zeros((image_row, image_col)) """ Non-maximum suppression. If the edge strength of the current pixel is the largest compared to the other pixels in the mask with the same direction, the value will be preserved. Otherwise, the value will be suppressed. """ for row in range(1, image_row - 1): for col in range(1, image_col - 1): direction = gradient_direction[row, col] if ( 0 <= direction < 22.5 or 15 * PI / 8 <= direction <= 2 * PI or 7 * PI / 8 <= direction <= 9 * PI / 8 ): w = sobel_grad[row, col - 1] e = sobel_grad[row, col + 1] if sobel_grad[row, col] >= w and sobel_grad[row, col] >= e: dst[row, col] = sobel_grad[row, col] elif (PI / 8 <= direction < 3 * PI / 8) or ( 9 * PI / 8 <= direction < 11 * PI / 8 ): sw = sobel_grad[row + 1, col - 1] ne = sobel_grad[row - 1, col + 1] if sobel_grad[row, col] >= sw and sobel_grad[row, col] >= ne: dst[row, col] = sobel_grad[row, col] elif (3 * PI / 8 <= direction < 5 * PI / 8) or ( 11 * PI / 8 <= direction < 13 * PI / 8 ): n = sobel_grad[row - 1, col] s = sobel_grad[row + 1, col] if sobel_grad[row, col] >= n and sobel_grad[row, col] >= s: dst[row, col] = sobel_grad[row, col] elif (5 * PI / 8 <= direction < 7 * PI / 8) or ( 13 * PI / 8 <= direction < 15 * PI / 8 ): nw = sobel_grad[row - 1, col - 1] se = sobel_grad[row + 1, col + 1] if sobel_grad[row, col] >= nw and sobel_grad[row, col] >= se: dst[row, col] = sobel_grad[row, col] """ High-Low threshold detection. If an edge pixel’s gradient value is higher than the high threshold value, it is marked as a strong edge pixel. If an edge pixel’s gradient value is smaller than the high threshold value and larger than the low threshold value, it is marked as a weak edge pixel. If an edge pixel's value is smaller than the low threshold value, it will be suppressed. """ if dst[row, col] >= threshold_high: dst[row, col] = strong elif dst[row, col] <= threshold_low: dst[row, col] = 0 else: dst[row, col] = weak """ Edge tracking. Usually a weak edge pixel caused from true edges will be connected to a strong edge pixel while noise responses are unconnected. As long as there is one strong edge pixel that is involved in its 8-connected neighborhood, that weak edge point can be identified as one that should be preserved. """ for row in range(1, image_row): for col in range(1, image_col): if dst[row, col] == weak: if 255 in ( dst[row, col + 1], dst[row, col - 1], dst[row - 1, col], dst[row + 1, col], dst[row - 1, col - 1], dst[row + 1, col - 1], dst[row - 1, col + 1], dst[row + 1, col + 1], ): dst[row, col] = strong else: dst[row, col] = 0 return dst if __name__ == "__main__": # read original image in gray mode lena = cv2.imread(r"../image_data/lena.jpg", 0) # canny edge detection canny_dst = canny(lena) cv2.imshow("canny", canny_dst) cv2.waitKey(0)
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#
#
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import numpy as np def runge_kutta(f, y0, x0, h, x_end): """ Calculate the numeric solution at each step to the ODE f(x, y) using RK4 https://en.wikipedia.org/wiki/Runge-Kutta_methods Arguments: f -- The ode as a function of x and y y0 -- the initial value for y x0 -- the initial value for x h -- the stepsize x_end -- the end value for x >>> # the exact solution is math.exp(x) >>> def f(x, y): ... return y >>> y0 = 1 >>> y = runge_kutta(f, y0, 0.0, 0.01, 5) >>> y[-1] 148.41315904125113 """ n = int(np.ceil((x_end - x0) / h)) y = np.zeros((n + 1,)) y[0] = y0 x = x0 for k in range(n): k1 = f(x, y[k]) k2 = f(x + 0.5 * h, y[k] + 0.5 * h * k1) k3 = f(x + 0.5 * h, y[k] + 0.5 * h * k2) k4 = f(x + h, y[k] + h * k3) y[k + 1] = y[k] + (1 / 6) * h * (k1 + 2 * k2 + 2 * k3 + k4) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
import numpy as np def runge_kutta(f, y0, x0, h, x_end): """ Calculate the numeric solution at each step to the ODE f(x, y) using RK4 https://en.wikipedia.org/wiki/Runge-Kutta_methods Arguments: f -- The ode as a function of x and y y0 -- the initial value for y x0 -- the initial value for x h -- the stepsize x_end -- the end value for x >>> # the exact solution is math.exp(x) >>> def f(x, y): ... return y >>> y0 = 1 >>> y = runge_kutta(f, y0, 0.0, 0.01, 5) >>> y[-1] 148.41315904125113 """ n = int(np.ceil((x_end - x0) / h)) y = np.zeros((n + 1,)) y[0] = y0 x = x0 for k in range(n): k1 = f(x, y[k]) k2 = f(x + 0.5 * h, y[k] + 0.5 * h * k1) k3 = f(x + 0.5 * h, y[k] + 0.5 * h * k2) k4 = f(x + h, y[k] + h * k3) y[k + 1] = y[k] + (1 / 6) * h * (k1 + 2 * k2 + 2 * k3 + k4) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 """ Build a half-adder quantum circuit that takes two bits as input, encodes them into qubits, then runs the half-adder circuit calculating the sum and carry qubits, observed over 1000 runs of the experiment . References: https://en.wikipedia.org/wiki/Adder_(electronics) https://qiskit.org/textbook/ch-states/atoms-computation.html#4.2-Remembering-how-to-add- """ import qiskit as q def half_adder(bit0: int, bit1: int) -> q.result.counts.Counts: """ >>> half_adder(0, 0) {'00': 1000} >>> half_adder(0, 1) {'01': 1000} >>> half_adder(1, 0) {'01': 1000} >>> half_adder(1, 1) {'10': 1000} """ # Use Aer's qasm_simulator simulator = q.Aer.get_backend("qasm_simulator") qc_ha = q.QuantumCircuit(4, 2) # encode inputs in qubits 0 and 1 if bit0 == 1: qc_ha.x(0) if bit1 == 1: qc_ha.x(1) qc_ha.barrier() # use cnots to write XOR of the inputs on qubit2 qc_ha.cx(0, 2) qc_ha.cx(1, 2) # use ccx / toffoli gate to write AND of the inputs on qubit3 qc_ha.ccx(0, 1, 3) qc_ha.barrier() # extract outputs qc_ha.measure(2, 0) # extract XOR value qc_ha.measure(3, 1) # extract AND value # Execute the circuit on the qasm simulator job = q.execute(qc_ha, simulator, shots=1000) # Return the histogram data of the results of the experiment. return job.result().get_counts(qc_ha) if __name__ == "__main__": counts = half_adder(1, 1) print(f"Half Adder Output Qubit Counts: {counts}")
#!/usr/bin/env python3 """ Build a half-adder quantum circuit that takes two bits as input, encodes them into qubits, then runs the half-adder circuit calculating the sum and carry qubits, observed over 1000 runs of the experiment . References: https://en.wikipedia.org/wiki/Adder_(electronics) https://qiskit.org/textbook/ch-states/atoms-computation.html#4.2-Remembering-how-to-add- """ import qiskit as q def half_adder(bit0: int, bit1: int) -> q.result.counts.Counts: """ >>> half_adder(0, 0) {'00': 1000} >>> half_adder(0, 1) {'01': 1000} >>> half_adder(1, 0) {'01': 1000} >>> half_adder(1, 1) {'10': 1000} """ # Use Aer's qasm_simulator simulator = q.Aer.get_backend("qasm_simulator") qc_ha = q.QuantumCircuit(4, 2) # encode inputs in qubits 0 and 1 if bit0 == 1: qc_ha.x(0) if bit1 == 1: qc_ha.x(1) qc_ha.barrier() # use cnots to write XOR of the inputs on qubit2 qc_ha.cx(0, 2) qc_ha.cx(1, 2) # use ccx / toffoli gate to write AND of the inputs on qubit3 qc_ha.ccx(0, 1, 3) qc_ha.barrier() # extract outputs qc_ha.measure(2, 0) # extract XOR value qc_ha.measure(3, 1) # extract AND value # Execute the circuit on the qasm simulator job = q.execute(qc_ha, simulator, shots=1000) # Return the histogram data of the results of the experiment. return job.result().get_counts(qc_ha) if __name__ == "__main__": counts = half_adder(1, 1) print(f"Half Adder Output Qubit Counts: {counts}")
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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: Alexander Joslin GitHub: github.com/echoaj Explanation: https://medium.com/@haleesammar/implemented-in-js-dijkstras-2-stack- algorithm-for-evaluating-mathematical-expressions-fc0837dae1ea We can use Dijkstra's two stack algorithm to solve an equation such as: (5 + ((4 * 2) * (2 + 3))) THESE ARE THE ALGORITHM'S RULES: RULE 1: Scan the expression from left to right. When an operand is encountered, push it onto the operand stack. RULE 2: When an operator is encountered in the expression, push it onto the operator stack. RULE 3: When a left parenthesis is encountered in the expression, ignore it. RULE 4: When a right parenthesis is encountered in the expression, pop an operator off the operator stack. The two operands it must operate on must be the last two operands pushed onto the operand stack. We therefore pop the operand stack twice, perform the operation, and push the result back onto the operand stack so it will be available for use as an operand of the next operator popped off the operator stack. RULE 5: When the entire infix expression has been scanned, the value left on the operand stack represents the value of the expression. NOTE: It only works with whole numbers. """ __author__ = "Alexander Joslin" import operator as op from .stack import Stack def dijkstras_two_stack_algorithm(equation: str) -> int: """ DocTests >>> dijkstras_two_stack_algorithm("(5 + 3)") 8 >>> dijkstras_two_stack_algorithm("((9 - (2 + 9)) + (8 - 1))") 5 >>> dijkstras_two_stack_algorithm("((((3 - 2) - (2 + 3)) + (2 - 4)) + 3)") -3 :param equation: a string :return: result: an integer """ operators = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} operand_stack: Stack[int] = Stack() operator_stack: Stack[str] = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(i)) elif i in operators: # RULE 2 operator_stack.push(i) elif i == ")": # RULE 4 opr = operator_stack.peek() operator_stack.pop() num1 = operand_stack.peek() operand_stack.pop() num2 = operand_stack.peek() operand_stack.pop() total = operators[opr](num2, num1) operand_stack.push(total) # RULE 5 return operand_stack.peek() if __name__ == "__main__": equation = "(5 + ((4 * 2) * (2 + 3)))" # answer = 45 print(f"{equation} = {dijkstras_two_stack_algorithm(equation)}")
""" Author: Alexander Joslin GitHub: github.com/echoaj Explanation: https://medium.com/@haleesammar/implemented-in-js-dijkstras-2-stack- algorithm-for-evaluating-mathematical-expressions-fc0837dae1ea We can use Dijkstra's two stack algorithm to solve an equation such as: (5 + ((4 * 2) * (2 + 3))) THESE ARE THE ALGORITHM'S RULES: RULE 1: Scan the expression from left to right. When an operand is encountered, push it onto the operand stack. RULE 2: When an operator is encountered in the expression, push it onto the operator stack. RULE 3: When a left parenthesis is encountered in the expression, ignore it. RULE 4: When a right parenthesis is encountered in the expression, pop an operator off the operator stack. The two operands it must operate on must be the last two operands pushed onto the operand stack. We therefore pop the operand stack twice, perform the operation, and push the result back onto the operand stack so it will be available for use as an operand of the next operator popped off the operator stack. RULE 5: When the entire infix expression has been scanned, the value left on the operand stack represents the value of the expression. NOTE: It only works with whole numbers. """ __author__ = "Alexander Joslin" import operator as op from .stack import Stack def dijkstras_two_stack_algorithm(equation: str) -> int: """ DocTests >>> dijkstras_two_stack_algorithm("(5 + 3)") 8 >>> dijkstras_two_stack_algorithm("((9 - (2 + 9)) + (8 - 1))") 5 >>> dijkstras_two_stack_algorithm("((((3 - 2) - (2 + 3)) + (2 - 4)) + 3)") -3 :param equation: a string :return: result: an integer """ operators = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} operand_stack: Stack[int] = Stack() operator_stack: Stack[str] = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(i)) elif i in operators: # RULE 2 operator_stack.push(i) elif i == ")": # RULE 4 opr = operator_stack.peek() operator_stack.pop() num1 = operand_stack.peek() operand_stack.pop() num2 = operand_stack.peek() operand_stack.pop() total = operators[opr](num2, num1) operand_stack.push(total) # RULE 5 return operand_stack.peek() if __name__ == "__main__": equation = "(5 + ((4 * 2) * (2 + 3)))" # answer = 45 print(f"{equation} = {dijkstras_two_stack_algorithm(equation)}")
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/bin/sh # # An example hook script to check the commit log message taken by # applypatch from an e-mail message. # # The hook should exit with non-zero status after issuing an # appropriate message if it wants to stop the commit. The hook is # allowed to edit the commit message file. # # To enable this hook, rename this file to "applypatch-msg". . git-sh-setup commitmsg="$(git rev-parse --git-path hooks/commit-msg)" test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"} :
#!/bin/sh # # An example hook script to check the commit log message taken by # applypatch from an e-mail message. # # The hook should exit with non-zero status after issuing an # appropriate message if it wants to stop the commit. The hook is # allowed to edit the commit message file. # # To enable this hook, rename this file to "applypatch-msg". . git-sh-setup commitmsg="$(git rev-parse --git-path hooks/commit-msg)" test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"} :
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 65: https://projecteuler.net/problem=65 The square root of 2 can be written as an infinite continued fraction. sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / (2 + ...)))) The infinite continued fraction can be written, sqrt(2) = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, sqrt(23) = [4;(1,3,1,8)]. It turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations. Let us consider the convergents for sqrt(2). 1 + 1 / 2 = 3/2 1 + 1 / (2 + 1 / 2) = 7/5 1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17/12 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/29 Hence the sequence of the first ten convergents for sqrt(2) are: 1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ... What is most surprising is that the important mathematical constant, e = [2;1,2,1,1,4,1,1,6,1,...,1,2k,1,...]. The first ten terms in the sequence of convergents for e are: 2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ... The sum of digits in the numerator of the 10th convergent is 1 + 4 + 5 + 7 = 17. Find the sum of the digits in the numerator of the 100th convergent of the continued fraction for e. ----- The solution mostly comes down to finding an equation that will generate the numerator of the continued fraction. For the i-th numerator, the pattern is: n_i = m_i * n_(i-1) + n_(i-2) for m_i = the i-th index of the continued fraction representation of e, n_0 = 1, and n_1 = 2 as the first 2 numbers of the representation. For example: n_9 = 6 * 193 + 106 = 1264 1 + 2 + 6 + 4 = 13 n_10 = 1 * 193 + 1264 = 1457 1 + 4 + 5 + 7 = 17 """ def sum_digits(num: int) -> int: """ Returns the sum of every digit in num. >>> sum_digits(1) 1 >>> sum_digits(12345) 15 >>> sum_digits(999001) 28 """ digit_sum = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def solution(max_n: int = 100) -> int: """ Returns the sum of the digits in the numerator of the max-th convergent of the continued fraction for e. >>> solution(9) 13 >>> solution(10) 17 >>> solution(50) 91 """ pre_numerator = 1 cur_numerator = 2 for i in range(2, max_n + 1): temp = pre_numerator e_cont = 2 * i // 3 if i % 3 == 0 else 1 pre_numerator = cur_numerator cur_numerator = e_cont * pre_numerator + temp return sum_digits(cur_numerator) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 65: https://projecteuler.net/problem=65 The square root of 2 can be written as an infinite continued fraction. sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / (2 + ...)))) The infinite continued fraction can be written, sqrt(2) = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, sqrt(23) = [4;(1,3,1,8)]. It turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations. Let us consider the convergents for sqrt(2). 1 + 1 / 2 = 3/2 1 + 1 / (2 + 1 / 2) = 7/5 1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17/12 1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/29 Hence the sequence of the first ten convergents for sqrt(2) are: 1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ... What is most surprising is that the important mathematical constant, e = [2;1,2,1,1,4,1,1,6,1,...,1,2k,1,...]. The first ten terms in the sequence of convergents for e are: 2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ... The sum of digits in the numerator of the 10th convergent is 1 + 4 + 5 + 7 = 17. Find the sum of the digits in the numerator of the 100th convergent of the continued fraction for e. ----- The solution mostly comes down to finding an equation that will generate the numerator of the continued fraction. For the i-th numerator, the pattern is: n_i = m_i * n_(i-1) + n_(i-2) for m_i = the i-th index of the continued fraction representation of e, n_0 = 1, and n_1 = 2 as the first 2 numbers of the representation. For example: n_9 = 6 * 193 + 106 = 1264 1 + 2 + 6 + 4 = 13 n_10 = 1 * 193 + 1264 = 1457 1 + 4 + 5 + 7 = 17 """ def sum_digits(num: int) -> int: """ Returns the sum of every digit in num. >>> sum_digits(1) 1 >>> sum_digits(12345) 15 >>> sum_digits(999001) 28 """ digit_sum = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def solution(max_n: int = 100) -> int: """ Returns the sum of the digits in the numerator of the max-th convergent of the continued fraction for e. >>> solution(9) 13 >>> solution(10) 17 >>> solution(50) 91 """ pre_numerator = 1 cur_numerator = 2 for i in range(2, max_n + 1): temp = pre_numerator e_cont = 2 * i // 3 if i % 3 == 0 else 1 pre_numerator = cur_numerator cur_numerator = e_cont * pre_numerator + temp return sum_digits(cur_numerator) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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(str(i)) == sorted(str(2 * i)) == sorted(str(3 * i)) == sorted(str(4 * i)) == sorted(str(5 * i)) == sorted(str(6 * i)) ): return i i += 1 if __name__ == "__main__": print(solution())
""" Permuted multiples Problem 52 It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. """ def solution(): """Returns the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. >>> solution() 142857 """ i = 1 while True: if ( sorted(str(i)) == sorted(str(2 * i)) == sorted(str(3 * i)) == sorted(str(4 * i)) == sorted(str(5 * i)) == sorted(str(6 * i)) ): return i i += 1 if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 A* algorithm combines features of uniform-cost search and pure heuristic search to efficiently compute optimal solutions. The A* algorithm is a best-first search algorithm in which the cost associated with a node is f(n) = g(n) + h(n), where g(n) is the cost of the path from the initial state to node n and h(n) is the heuristic estimate or the cost or a path from node n to a goal. The A* algorithm introduces a heuristic into a regular graph-searching algorithm, essentially planning ahead at each step so a more optimal decision is made. For this reason, A* is known as an algorithm with brains. https://en.wikipedia.org/wiki/A*_search_algorithm """ import numpy as np class Cell: """ Class cell represents a cell in the world which have the properties: position: represented by tuple of x and y coordinates initially set to (0,0). parent: Contains the parent cell object visited before we arrived at this cell. g, h, f: Parameters used when calling our heuristic function. """ def __init__(self): self.position = (0, 0) self.parent = None self.g = 0 self.h = 0 self.f = 0 """ Overrides equals method because otherwise cell assign will give wrong results. """ def __eq__(self, cell): return self.position == cell.position def showcell(self): print(self.position) class Gridworld: """ Gridworld class represents the external world here a grid M*M matrix. world_size: create a numpy array with the given world_size default is 5. """ def __init__(self, world_size=(5, 5)): self.w = np.zeros(world_size) self.world_x_limit = world_size[0] self.world_y_limit = world_size[1] def show(self): print(self.w) def get_neigbours(self, cell): """ Return the neighbours of cell """ neughbour_cord = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] current_x = cell.position[0] current_y = cell.position[1] neighbours = [] for n in neughbour_cord: x = current_x + n[0] y = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: c = Cell() c.position = (x, y) c.parent = cell neighbours.append(c) return neighbours def astar(world, start, goal): """ Implementation of a start algorithm. world : Object of the world object. start : Object of the cell as start position. stop : Object of the cell as goal position. >>> p = Gridworld() >>> start = Cell() >>> start.position = (0,0) >>> goal = Cell() >>> goal.position = (4,4) >>> astar(p, start, goal) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] """ _open = [] _closed = [] _open.append(start) while _open: min_f = np.argmin([n.f for n in _open]) current = _open[min_f] _closed.append(_open.pop(min_f)) if current == goal: break for n in world.get_neigbours(current): for c in _closed: if c == n: continue n.g = current.g + 1 x1, y1 = n.position x2, y2 = goal.position n.h = (y2 - y1) ** 2 + (x2 - x1) ** 2 n.f = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(n) path = [] while current.parent is not None: path.append(current.position) current = current.parent path.append(current.position) return path[::-1] if __name__ == "__main__": world = Gridworld() # Start position and goal start = Cell() start.position = (0, 0) goal = Cell() goal.position = (4, 4) print(f"path from {start.position} to {goal.position}") s = astar(world, start, goal) # Just for visual reasons. for i in s: world.w[i] = 1 print(world.w)
""" The A* algorithm combines features of uniform-cost search and pure heuristic search to efficiently compute optimal solutions. The A* algorithm is a best-first search algorithm in which the cost associated with a node is f(n) = g(n) + h(n), where g(n) is the cost of the path from the initial state to node n and h(n) is the heuristic estimate or the cost or a path from node n to a goal. The A* algorithm introduces a heuristic into a regular graph-searching algorithm, essentially planning ahead at each step so a more optimal decision is made. For this reason, A* is known as an algorithm with brains. https://en.wikipedia.org/wiki/A*_search_algorithm """ import numpy as np class Cell: """ Class cell represents a cell in the world which have the properties: position: represented by tuple of x and y coordinates initially set to (0,0). parent: Contains the parent cell object visited before we arrived at this cell. g, h, f: Parameters used when calling our heuristic function. """ def __init__(self): self.position = (0, 0) self.parent = None self.g = 0 self.h = 0 self.f = 0 """ Overrides equals method because otherwise cell assign will give wrong results. """ def __eq__(self, cell): return self.position == cell.position def showcell(self): print(self.position) class Gridworld: """ Gridworld class represents the external world here a grid M*M matrix. world_size: create a numpy array with the given world_size default is 5. """ def __init__(self, world_size=(5, 5)): self.w = np.zeros(world_size) self.world_x_limit = world_size[0] self.world_y_limit = world_size[1] def show(self): print(self.w) def get_neigbours(self, cell): """ Return the neighbours of cell """ neughbour_cord = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] current_x = cell.position[0] current_y = cell.position[1] neighbours = [] for n in neughbour_cord: x = current_x + n[0] y = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: c = Cell() c.position = (x, y) c.parent = cell neighbours.append(c) return neighbours def astar(world, start, goal): """ Implementation of a start algorithm. world : Object of the world object. start : Object of the cell as start position. stop : Object of the cell as goal position. >>> p = Gridworld() >>> start = Cell() >>> start.position = (0,0) >>> goal = Cell() >>> goal.position = (4,4) >>> astar(p, start, goal) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] """ _open = [] _closed = [] _open.append(start) while _open: min_f = np.argmin([n.f for n in _open]) current = _open[min_f] _closed.append(_open.pop(min_f)) if current == goal: break for n in world.get_neigbours(current): for c in _closed: if c == n: continue n.g = current.g + 1 x1, y1 = n.position x2, y2 = goal.position n.h = (y2 - y1) ** 2 + (x2 - x1) ** 2 n.f = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(n) path = [] while current.parent is not None: path.append(current.position) current = current.parent path.append(current.position) return path[::-1] if __name__ == "__main__": world = Gridworld() # Start position and goal start = Cell() start.position = (0, 0) goal = Cell() goal.position = (4, 4) print(f"path from {start.position} to {goal.position}") s = astar(world, start, goal) # Just for visual reasons. for i in s: world.w[i] = 1 print(world.w)
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,912
Misc fixes across multiple algorithms
### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CenTdemeern1
"2022-10-10T12:56:00Z"
"2022-10-16T05:25:38Z"
c94e215c8dbdfe1f349eab5708be6b5f337b6ddd
04698538d816fc5f70c850e8b89c6d1f5599fa84
Misc fixes across multiple algorithms. ### Describe your change: This change fixes a typo where `__name__ == "__main__"` was accidentally written as `__name__ == "main"`. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to 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 kmp(pattern: str, text: str) -> bool: """ The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text with complexity O(n + m) 1) Preprocess pattern to identify any suffixes that are identical to prefixes This tells us where to continue from if we get a mismatch between a character in our pattern and the text. 2) Step through the text one character at a time and compare it to a character in the pattern updating our location within the pattern if necessary """ # 1) Construct the failure array failure = get_failure_array(pattern) # 2) Step through text searching for pattern i, j = 0, 0 # index into text, pattern while i < len(text): if pattern[j] == text[i]: if j == (len(pattern) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: j = failure[j - 1] continue i += 1 return False def get_failure_array(pattern: str) -> list[int]: """ Calculates the new index we should go to if we fail a comparison :param pattern: :return: """ failure = [0] i = 0 j = 1 while j < len(pattern): if pattern[i] == pattern[j]: i += 1 elif i > 0: i = failure[i - 1] continue j += 1 failure.append(i) return failure if __name__ == "__main__": # Test 1) pattern = "abc1abc12" text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc" text2 = "alskfjaldsk23adsfabcabc" assert kmp(pattern, text1) and not kmp(pattern, text2) # Test 2) pattern = "ABABX" text = "ABABZABABYABABX" assert kmp(pattern, text) # Test 3) pattern = "AAAB" text = "ABAAAAAB" assert kmp(pattern, text) # Test 4) pattern = "abcdabcy" text = "abcxabcdabxabcdabcdabcy" assert kmp(pattern, text) # Test 5) pattern = "aabaabaaa" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
from __future__ import annotations def kmp(pattern: str, text: str) -> bool: """ The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text with complexity O(n + m) 1) Preprocess pattern to identify any suffixes that are identical to prefixes This tells us where to continue from if we get a mismatch between a character in our pattern and the text. 2) Step through the text one character at a time and compare it to a character in the pattern updating our location within the pattern if necessary """ # 1) Construct the failure array failure = get_failure_array(pattern) # 2) Step through text searching for pattern i, j = 0, 0 # index into text, pattern while i < len(text): if pattern[j] == text[i]: if j == (len(pattern) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: j = failure[j - 1] continue i += 1 return False def get_failure_array(pattern: str) -> list[int]: """ Calculates the new index we should go to if we fail a comparison :param pattern: :return: """ failure = [0] i = 0 j = 1 while j < len(pattern): if pattern[i] == pattern[j]: i += 1 elif i > 0: i = failure[i - 1] continue j += 1 failure.append(i) return failure if __name__ == "__main__": # Test 1) pattern = "abc1abc12" text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc" text2 = "alskfjaldsk23adsfabcabc" assert kmp(pattern, text1) and not kmp(pattern, text2) # Test 2) pattern = "ABABX" text = "ABABZABABYABABX" assert kmp(pattern, text) # Test 3) pattern = "AAAB" text = "ABAAAAAB" assert kmp(pattern, text) # Test 4) pattern = "abcdabcy" text = "abcxabcdabxabcdabcdabcy" assert kmp(pattern, text) # Test 5) pattern = "aabaabaaa" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
-1
TheAlgorithms/Python
6,629
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2022-10-03T19:21:25Z"
"2022-10-03T20:00:46Z"
e9862adafce9eb682cabcf8ac502893e0272ae65
756bb268eb22199534fc8d6478cf0e006f02b56b
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
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.6.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: v2.37.0 hooks: - id: pyupgrade args: - --py310-plus - repo: https://gitlab.com/pycqa/flake8 rev: 3.9.2 hooks: - id: flake8 args: - --ignore=E203,W503 - --max-complexity=25 - --max-line-length=88 - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.961 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.1.0 hooks: - id: codespell args: - --ignore-words-list=ans,crate,fo,followings,hist,iff,mater,secant,som,sur,tim - --skip="./.*,./strings/dictionary.txt,./strings/words.txt,./project_euler/problem_022/p022_names.txt" exclude: | (?x)^( strings/dictionary.txt | strings/words.txt | project_euler/problem_022/p022_names.txt )$ - repo: local hooks: - id: validate-filenames name: Validate filenames entry: ./scripts/validate_filenames.py language: script pass_filenames: false
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.8.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: v2.38.2 hooks: - id: pyupgrade args: - --py310-plus - repo: https://github.com/PyCQA/flake8 rev: 5.0.4 hooks: - id: flake8 args: - --ignore=E203,W503 - --max-complexity=25 - --max-line-length=88 - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.981 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
6,629
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2022-10-03T19:21:25Z"
"2022-10-03T20:00:46Z"
e9862adafce9eb682cabcf8ac502893e0272ae65
756bb268eb22199534fc8d6478cf0e006f02b56b
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
""" Implementation of double ended queue. """ from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from typing import Any class Deque: """ Deque data structure. Operations ---------- append(val: Any) -> None appendleft(val: Any) -> None extend(iter: Iterable) -> None extendleft(iter: Iterable) -> None pop() -> Any popleft() -> Any Observers --------- is_empty() -> bool Attributes ---------- _front: _Node front of the deque a.k.a. the first element _back: _Node back of the element a.k.a. the last element _len: int the number of nodes """ __slots__ = ["_front", "_back", "_len"] @dataclass class _Node: """ Representation of a node. Contains a value and a pointer to the next node as well as to the previous one. """ val: Any = None next: Deque._Node | None = None prev: Deque._Node | None = None class _Iterator: """ Helper class for iteration. Will be used to implement iteration. Attributes ---------- _cur: _Node the current node of the iteration. """ __slots__ = ["_cur"] def __init__(self, cur: Deque._Node | None) -> None: self._cur = cur def __iter__(self) -> Deque._Iterator: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) """ return self def __next__(self) -> Any: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) >>> next(iterator) 1 >>> next(iterator) 2 >>> next(iterator) 3 """ if self._cur is None: # finished iterating raise StopIteration val = self._cur.val self._cur = self._cur.next return val def __init__(self, iterable: Iterable[Any] | None = None) -> None: self._front: Any = None self._back: Any = None self._len: int = 0 if iterable is not None: # append every value to the deque for val in iterable: self.append(val) def append(self, val: Any) -> None: """ Adds val to the end of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.append(4) >>> our_deque_1 [1, 2, 3, 4] >>> our_deque_2 = Deque('ab') >>> our_deque_2.append('c') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.append(4) >>> deque_collections_1 deque([1, 2, 3, 4]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.append('c') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes self._back.next = node node.prev = self._back self._back = node # assign new back to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def appendleft(self, val: Any) -> None: """ Adds val to the beginning of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([2, 3]) >>> our_deque_1.appendleft(1) >>> our_deque_1 [1, 2, 3] >>> our_deque_2 = Deque('bc') >>> our_deque_2.appendleft('a') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([2, 3]) >>> deque_collections_1.appendleft(1) >>> deque_collections_1 deque([1, 2, 3]) >>> deque_collections_2 = deque('bc') >>> deque_collections_2.appendleft('a') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes node.next = self._front self._front.prev = node self._front = node # assign new front to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def extend(self, iter: Iterable[Any]) -> None: """ Appends every value of iter to the end of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extend([4, 5]) >>> our_deque_1 [1, 2, 3, 4, 5] >>> our_deque_2 = Deque('ab') >>> our_deque_2.extend('cd') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extend([4, 5]) >>> deque_collections_1 deque([1, 2, 3, 4, 5]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.extend('cd') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iter: self.append(val) def extendleft(self, iter: Iterable[Any]) -> None: """ Appends every value of iter to the beginning of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extendleft([0, -1]) >>> our_deque_1 [-1, 0, 1, 2, 3] >>> our_deque_2 = Deque('cd') >>> our_deque_2.extendleft('ba') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extendleft([0, -1]) >>> deque_collections_1 deque([-1, 0, 1, 2, 3]) >>> deque_collections_2 = deque('cd') >>> deque_collections_2.extendleft('ba') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iter: self.appendleft(val) def pop(self) -> Any: """ Removes the last element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([1, 2, 3, 15182]) >>> our_popped = our_deque.pop() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([1, 2, 3, 15182]) >>> collections_popped = deque_collections.pop() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._back self._back = self._back.prev # set new back self._back.next = ( None # drop the last node - python will deallocate memory automatically ) self._len -= 1 return topop.val def popleft(self) -> Any: """ Removes the first element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([15182, 1, 2, 3]) >>> our_popped = our_deque.popleft() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([15182, 1, 2, 3]) >>> collections_popped = deque_collections.popleft() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._front self._front = self._front.next # set new front and drop the first node self._front.prev = None self._len -= 1 return topop.val def is_empty(self) -> bool: """ Checks if the deque is empty. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> our_deque.is_empty() False >>> our_empty_deque = Deque() >>> our_empty_deque.is_empty() True >>> from collections import deque >>> empty_deque_collections = deque() >>> list(our_empty_deque) == list(empty_deque_collections) True """ return self._front is None def __len__(self) -> int: """ Implements len() function. Returns the length of the deque. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> len(our_deque) 3 >>> our_empty_deque = Deque() >>> len(our_empty_deque) 0 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> len(deque_collections) 3 >>> empty_deque_collections = deque() >>> len(empty_deque_collections) 0 >>> len(our_empty_deque) == len(empty_deque_collections) True """ return self._len def __eq__(self, other: object) -> bool: """ Implements "==" operator. Returns if *self* is equal to *other*. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_2 = Deque([1, 2, 3]) >>> our_deque_1 == our_deque_2 True >>> our_deque_3 = Deque([1, 2]) >>> our_deque_1 == our_deque_3 False >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_2 = deque([1, 2, 3]) >>> deque_collections_1 == deque_collections_2 True >>> deque_collections_3 = deque([1, 2]) >>> deque_collections_1 == deque_collections_3 False >>> (our_deque_1 == our_deque_2) == (deque_collections_1 == deque_collections_2) True >>> (our_deque_1 == our_deque_3) == (deque_collections_1 == deque_collections_3) True """ if not isinstance(other, Deque): return NotImplemented me = self._front oth = other._front # if the length of the deques are not the same, they are not equal if len(self) != len(other): return False while me is not None and oth is not None: # compare every value if me.val != oth.val: return False me = me.next oth = oth.next return True def __iter__(self) -> Deque._Iterator: """ Implements iteration. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> for v in our_deque: ... print(v) 1 2 3 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> for v in deque_collections: ... print(v) 1 2 3 """ return Deque._Iterator(self._front) def __repr__(self) -> str: """ Implements representation of the deque. Represents it as a list, with its values between '[' and ']'. Time complexity: O(n) >>> our_deque = Deque([1, 2, 3]) >>> our_deque [1, 2, 3] """ values_list = [] aux = self._front while aux is not None: # append the values in a list to display values_list.append(aux.val) aux = aux.next return "[" + ", ".join(repr(val) for val in values_list) + "]" if __name__ == "__main__": import doctest doctest.testmod()
""" Implementation of double ended queue. """ from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from typing import Any class Deque: """ Deque data structure. Operations ---------- append(val: Any) -> None appendleft(val: Any) -> None extend(iter: Iterable) -> None extendleft(iter: Iterable) -> None pop() -> Any popleft() -> Any Observers --------- is_empty() -> bool Attributes ---------- _front: _Node front of the deque a.k.a. the first element _back: _Node back of the element a.k.a. the last element _len: int the number of nodes """ __slots__ = ["_front", "_back", "_len"] @dataclass class _Node: """ Representation of a node. Contains a value and a pointer to the next node as well as to the previous one. """ val: Any = None next: Deque._Node | None = None prev: Deque._Node | None = None class _Iterator: """ Helper class for iteration. Will be used to implement iteration. Attributes ---------- _cur: _Node the current node of the iteration. """ __slots__ = ["_cur"] def __init__(self, cur: Deque._Node | None) -> None: self._cur = cur def __iter__(self) -> Deque._Iterator: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) """ return self def __next__(self) -> Any: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) >>> next(iterator) 1 >>> next(iterator) 2 >>> next(iterator) 3 """ if self._cur is None: # finished iterating raise StopIteration val = self._cur.val self._cur = self._cur.next return val def __init__(self, iterable: Iterable[Any] | None = None) -> None: self._front: Any = None self._back: Any = None self._len: int = 0 if iterable is not None: # append every value to the deque for val in iterable: self.append(val) def append(self, val: Any) -> None: """ Adds val to the end of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.append(4) >>> our_deque_1 [1, 2, 3, 4] >>> our_deque_2 = Deque('ab') >>> our_deque_2.append('c') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.append(4) >>> deque_collections_1 deque([1, 2, 3, 4]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.append('c') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes self._back.next = node node.prev = self._back self._back = node # assign new back to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def appendleft(self, val: Any) -> None: """ Adds val to the beginning of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([2, 3]) >>> our_deque_1.appendleft(1) >>> our_deque_1 [1, 2, 3] >>> our_deque_2 = Deque('bc') >>> our_deque_2.appendleft('a') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([2, 3]) >>> deque_collections_1.appendleft(1) >>> deque_collections_1 deque([1, 2, 3]) >>> deque_collections_2 = deque('bc') >>> deque_collections_2.appendleft('a') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes node.next = self._front self._front.prev = node self._front = node # assign new front to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def extend(self, iter: Iterable[Any]) -> None: """ Appends every value of iter to the end of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extend([4, 5]) >>> our_deque_1 [1, 2, 3, 4, 5] >>> our_deque_2 = Deque('ab') >>> our_deque_2.extend('cd') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extend([4, 5]) >>> deque_collections_1 deque([1, 2, 3, 4, 5]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.extend('cd') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iter: self.append(val) def extendleft(self, iter: Iterable[Any]) -> None: """ Appends every value of iter to the beginning of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extendleft([0, -1]) >>> our_deque_1 [-1, 0, 1, 2, 3] >>> our_deque_2 = Deque('cd') >>> our_deque_2.extendleft('ba') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extendleft([0, -1]) >>> deque_collections_1 deque([-1, 0, 1, 2, 3]) >>> deque_collections_2 = deque('cd') >>> deque_collections_2.extendleft('ba') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iter: self.appendleft(val) def pop(self) -> Any: """ Removes the last element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([1, 2, 3, 15182]) >>> our_popped = our_deque.pop() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([1, 2, 3, 15182]) >>> collections_popped = deque_collections.pop() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._back self._back = self._back.prev # set new back self._back.next = ( None # drop the last node - python will deallocate memory automatically ) self._len -= 1 return topop.val def popleft(self) -> Any: """ Removes the first element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([15182, 1, 2, 3]) >>> our_popped = our_deque.popleft() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([15182, 1, 2, 3]) >>> collections_popped = deque_collections.popleft() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._front self._front = self._front.next # set new front and drop the first node self._front.prev = None self._len -= 1 return topop.val def is_empty(self) -> bool: """ Checks if the deque is empty. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> our_deque.is_empty() False >>> our_empty_deque = Deque() >>> our_empty_deque.is_empty() True >>> from collections import deque >>> empty_deque_collections = deque() >>> list(our_empty_deque) == list(empty_deque_collections) True """ return self._front is None def __len__(self) -> int: """ Implements len() function. Returns the length of the deque. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> len(our_deque) 3 >>> our_empty_deque = Deque() >>> len(our_empty_deque) 0 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> len(deque_collections) 3 >>> empty_deque_collections = deque() >>> len(empty_deque_collections) 0 >>> len(our_empty_deque) == len(empty_deque_collections) True """ return self._len def __eq__(self, other: object) -> bool: """ Implements "==" operator. Returns if *self* is equal to *other*. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_2 = Deque([1, 2, 3]) >>> our_deque_1 == our_deque_2 True >>> our_deque_3 = Deque([1, 2]) >>> our_deque_1 == our_deque_3 False >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_2 = deque([1, 2, 3]) >>> deque_collections_1 == deque_collections_2 True >>> deque_collections_3 = deque([1, 2]) >>> deque_collections_1 == deque_collections_3 False >>> (our_deque_1 == our_deque_2) == (deque_collections_1 == deque_collections_2) True >>> (our_deque_1 == our_deque_3) == (deque_collections_1 == deque_collections_3) True """ if not isinstance(other, Deque): return NotImplemented me = self._front oth = other._front # if the length of the dequeues are not the same, they are not equal if len(self) != len(other): return False while me is not None and oth is not None: # compare every value if me.val != oth.val: return False me = me.next oth = oth.next return True def __iter__(self) -> Deque._Iterator: """ Implements iteration. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> for v in our_deque: ... print(v) 1 2 3 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> for v in deque_collections: ... print(v) 1 2 3 """ return Deque._Iterator(self._front) def __repr__(self) -> str: """ Implements representation of the deque. Represents it as a list, with its values between '[' and ']'. Time complexity: O(n) >>> our_deque = Deque([1, 2, 3]) >>> our_deque [1, 2, 3] """ values_list = [] aux = self._front while aux is not None: # append the values in a list to display values_list.append(aux.val) aux = aux.next return "[" + ", ".join(repr(val) for val in values_list) + "]" if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
6,629
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2022-10-03T19:21:25Z"
"2022-10-03T20:00:46Z"
e9862adafce9eb682cabcf8ac502893e0272ae65
756bb268eb22199534fc8d6478cf0e006f02b56b
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
import numpy as np def power_iteration( input_matrix: np.ndarray, vector: np.ndarray, error_tol: float = 1e-12, max_iterations: int = 100, ) -> tuple[float, np.ndarray]: """ Power Iteration. Find the largest eigenvalue and corresponding eigenvector of matrix input_matrix given a random vector in the same space. Will work so long as vector has component of largest eigenvector. input_matrix must be either real or Hermitian. Input input_matrix: input matrix whose largest eigenvalue we will find. Numpy array. np.shape(input_matrix) == (N,N). vector: random initial vector in same space as matrix. Numpy array. np.shape(vector) == (N,) or (N,1) Output largest_eigenvalue: largest eigenvalue of the matrix input_matrix. Float. Scalar. largest_eigenvector: eigenvector corresponding to largest_eigenvalue. Numpy array. np.shape(largest_eigenvector) == (N,) or (N,1). >>> import numpy as np >>> input_matrix = np.array([ ... [41, 4, 20], ... [ 4, 26, 30], ... [20, 30, 50] ... ]) >>> vector = np.array([41,4,20]) >>> power_iteration(input_matrix,vector) (79.66086378788381, array([0.44472726, 0.46209842, 0.76725662])) """ # Ensure matrix is square. assert np.shape(input_matrix)[0] == np.shape(input_matrix)[1] # Ensure proper dimensionality. assert np.shape(input_matrix)[0] == np.shape(vector)[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(input_matrix) == np.iscomplexobj(vector) is_complex = np.iscomplexobj(input_matrix) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(input_matrix, input_matrix.conj().T) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. convergence = False lamda_previous = 0 iterations = 0 error = 1e12 while not convergence: # Multiple matrix by the vector. w = np.dot(input_matrix, vector) # Normalize the resulting output vector. vector = w / np.linalg.norm(w) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) vectorH = vector.conj().T if is_complex else vector.T lamda = np.dot(vectorH, np.dot(input_matrix, vector)) # Check convergence. error = np.abs(lamda - lamda_previous) / lamda iterations += 1 if error <= error_tol or iterations >= max_iterations: convergence = True lamda_previous = lamda if is_complex: lamda = np.real(lamda) return lamda, vector def test_power_iteration() -> None: """ >>> test_power_iteration() # self running tests """ real_input_matrix = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]) real_vector = np.array([41, 4, 20]) complex_input_matrix = real_input_matrix.astype(np.complex128) imag_matrix = np.triu(1j * complex_input_matrix, 1) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T complex_vector = np.array([41, 4, 20]).astype(np.complex128) for problem_type in ["real", "complex"]: if problem_type == "real": input_matrix = real_input_matrix vector = real_vector elif problem_type == "complex": input_matrix = complex_input_matrix vector = complex_vector # Our implementation. eigen_value, eigen_vector = power_iteration(input_matrix, vector) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). eigen_values, eigen_vectors = np.linalg.eigh(input_matrix) # Last eigenvalue is the maximum one. eigen_value_max = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. eigen_vector_max = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max) <= 1e-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(eigen_vector) - np.abs(eigen_vector_max)) <= 1e-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
import numpy as np def power_iteration( input_matrix: np.ndarray, vector: np.ndarray, error_tol: float = 1e-12, max_iterations: int = 100, ) -> tuple[float, np.ndarray]: """ Power Iteration. Find the largest eigenvalue and corresponding eigenvector of matrix input_matrix given a random vector in the same space. Will work so long as vector has component of largest eigenvector. input_matrix must be either real or Hermitian. Input input_matrix: input matrix whose largest eigenvalue we will find. Numpy array. np.shape(input_matrix) == (N,N). vector: random initial vector in same space as matrix. Numpy array. np.shape(vector) == (N,) or (N,1) Output largest_eigenvalue: largest eigenvalue of the matrix input_matrix. Float. Scalar. largest_eigenvector: eigenvector corresponding to largest_eigenvalue. Numpy array. np.shape(largest_eigenvector) == (N,) or (N,1). >>> import numpy as np >>> input_matrix = np.array([ ... [41, 4, 20], ... [ 4, 26, 30], ... [20, 30, 50] ... ]) >>> vector = np.array([41,4,20]) >>> power_iteration(input_matrix,vector) (79.66086378788381, array([0.44472726, 0.46209842, 0.76725662])) """ # Ensure matrix is square. assert np.shape(input_matrix)[0] == np.shape(input_matrix)[1] # Ensure proper dimensionality. assert np.shape(input_matrix)[0] == np.shape(vector)[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(input_matrix) == np.iscomplexobj(vector) is_complex = np.iscomplexobj(input_matrix) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(input_matrix, input_matrix.conj().T) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. convergence = False lambda_previous = 0 iterations = 0 error = 1e12 while not convergence: # Multiple matrix by the vector. w = np.dot(input_matrix, vector) # Normalize the resulting output vector. vector = w / np.linalg.norm(w) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) vectorH = vector.conj().T if is_complex else vector.T lambda_ = np.dot(vectorH, np.dot(input_matrix, vector)) # Check convergence. error = np.abs(lambda_ - lambda_previous) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: convergence = True lambda_previous = lambda_ if is_complex: lambda_ = np.real(lambda_) return lambda_, vector def test_power_iteration() -> None: """ >>> test_power_iteration() # self running tests """ real_input_matrix = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]) real_vector = np.array([41, 4, 20]) complex_input_matrix = real_input_matrix.astype(np.complex128) imag_matrix = np.triu(1j * complex_input_matrix, 1) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T complex_vector = np.array([41, 4, 20]).astype(np.complex128) for problem_type in ["real", "complex"]: if problem_type == "real": input_matrix = real_input_matrix vector = real_vector elif problem_type == "complex": input_matrix = complex_input_matrix vector = complex_vector # Our implementation. eigen_value, eigen_vector = power_iteration(input_matrix, vector) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). eigen_values, eigen_vectors = np.linalg.eigh(input_matrix) # Last eigenvalue is the maximum one. eigen_value_max = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. eigen_vector_max = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max) <= 1e-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(eigen_vector) - np.abs(eigen_vector_max)) <= 1e-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
1
TheAlgorithms/Python
6,629
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2022-10-03T19:21:25Z"
"2022-10-03T20:00:46Z"
e9862adafce9eb682cabcf8ac502893e0272ae65
756bb268eb22199534fc8d6478cf0e006f02b56b
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
""" Implementation of sequential minimal optimization (SMO) for support vector machines (SVM). Sequential minimal optimization (SMO) is an algorithm for solving the quadratic programming (QP) problem that arises during the training of support vector machines. It was invented by John Platt in 1998. Input: 0: type: numpy.ndarray. 1: first column of ndarray must be tags of samples, must be 1 or -1. 2: rows of ndarray represent samples. Usage: Command: python3 sequential_minimum_optimization.py Code: from sequential_minimum_optimization import SmoSVM, Kernel kernel = Kernel(kernel='poly', degree=3., coef0=1., gamma=0.5) init_alphas = np.zeros(train.shape[0]) SVM = SmoSVM(train=train, alpha_list=init_alphas, kernel_func=kernel, cost=0.4, b=0.0, tolerance=0.001) SVM.fit() predict = SVM.predict(test_samples) Reference: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/smo-book.pdf https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-98-14.pdf http://web.cs.iastate.edu/~honavar/smo-svm.pdf """ import os import sys import urllib.request import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.datasets import make_blobs, make_circles from sklearn.preprocessing import StandardScaler CANCER_DATASET_URL = ( "http://archive.ics.uci.edu/ml/machine-learning-databases/" "breast-cancer-wisconsin/wdbc.data" ) class SmoSVM: def __init__( self, train, kernel_func, alpha_list=None, cost=0.4, b=0.0, tolerance=0.001, auto_norm=True, ): self._init = True self._auto_norm = auto_norm self._c = np.float64(cost) self._b = np.float64(b) self._tol = np.float64(tolerance) if tolerance > 0.0001 else np.float64(0.001) self.tags = train[:, 0] self.samples = self._norm(train[:, 1:]) if self._auto_norm else train[:, 1:] self.alphas = alpha_list if alpha_list is not None else np.zeros(train.shape[0]) self.Kernel = kernel_func self._eps = 0.001 self._all_samples = list(range(self.length)) self._K_matrix = self._calculate_k_matrix() self._error = np.zeros(self.length) self._unbound = [] self.choose_alpha = self._choose_alphas() # Calculate alphas using SMO algorithm def fit(self): K = self._k state = None while True: # 1: Find alpha1, alpha2 try: i1, i2 = self.choose_alpha.send(state) state = None except StopIteration: print("Optimization done!\nEvery sample satisfy the KKT condition!") break # 2: calculate new alpha2 and new alpha1 y1, y2 = self.tags[i1], self.tags[i2] a1, a2 = self.alphas[i1].copy(), self.alphas[i2].copy() e1, e2 = self._e(i1), self._e(i2) args = (i1, i2, a1, a2, e1, e2, y1, y2) a1_new, a2_new = self._get_new_alpha(*args) if not a1_new and not a2_new: state = False continue self.alphas[i1], self.alphas[i2] = a1_new, a2_new # 3: update threshold(b) b1_new = np.float64( -e1 - y1 * K(i1, i1) * (a1_new - a1) - y2 * K(i2, i1) * (a2_new - a2) + self._b ) b2_new = np.float64( -e2 - y2 * K(i2, i2) * (a2_new - a2) - y1 * K(i1, i2) * (a1_new - a1) + self._b ) if 0.0 < a1_new < self._c: b = b1_new if 0.0 < a2_new < self._c: b = b2_new if not (np.float64(0) < a2_new < self._c) and not ( np.float64(0) < a1_new < self._c ): b = (b1_new + b2_new) / 2.0 b_old = self._b self._b = b # 4: update error value,here we only calculate those non-bound samples' # error self._unbound = [i for i in self._all_samples if self._is_unbound(i)] for s in self.unbound: if s == i1 or s == i2: continue self._error[s] += ( y1 * (a1_new - a1) * K(i1, s) + y2 * (a2_new - a2) * K(i2, s) + (self._b - b_old) ) # if i1 or i2 is non-bound,update there error value to zero if self._is_unbound(i1): self._error[i1] = 0 if self._is_unbound(i2): self._error[i2] = 0 # Predict test samles def predict(self, test_samples, classify=True): if test_samples.shape[1] > self.samples.shape[1]: raise ValueError( "Test samples' feature length does not equal to that of train samples" ) if self._auto_norm: test_samples = self._norm(test_samples) results = [] for test_sample in test_samples: result = self._predict(test_sample) if classify: results.append(1 if result > 0 else -1) else: results.append(result) return np.array(results) # Check if alpha violate KKT condition def _check_obey_kkt(self, index): alphas = self.alphas tol = self._tol r = self._e(index) * self.tags[index] c = self._c return (r < -tol and alphas[index] < c) or (r > tol and alphas[index] > 0.0) # Get value calculated from kernel function def _k(self, i1, i2): # for test samples,use Kernel function if isinstance(i2, np.ndarray): return self.Kernel(self.samples[i1], i2) # for train samples,Kernel values have been saved in matrix else: return self._K_matrix[i1, i2] # Get sample's error def _e(self, index): """ Two cases: 1:Sample[index] is non-bound,Fetch error from list: _error 2:sample[index] is bound,Use predicted value deduct true value: g(xi) - yi """ # get from error data if self._is_unbound(index): return self._error[index] # get by g(xi) - yi else: gx = np.dot(self.alphas * self.tags, self._K_matrix[:, index]) + self._b yi = self.tags[index] return gx - yi # Calculate Kernel matrix of all possible i1,i2 ,saving time def _calculate_k_matrix(self): k_matrix = np.zeros([self.length, self.length]) for i in self._all_samples: for j in self._all_samples: k_matrix[i, j] = np.float64( self.Kernel(self.samples[i, :], self.samples[j, :]) ) return k_matrix # Predict test sample's tag def _predict(self, sample): k = self._k predicted_value = ( np.sum( [ self.alphas[i1] * self.tags[i1] * k(i1, sample) for i1 in self._all_samples ] ) + self._b ) return predicted_value # Choose alpha1 and alpha2 def _choose_alphas(self): locis = yield from self._choose_a1() if not locis: return return locis def _choose_a1(self): """ Choose first alpha ;steps: 1:First loop over all sample 2:Second loop over all non-bound samples till all non-bound samples does not voilate kkt condition. 3:Repeat this two process endlessly,till all samples does not voilate kkt condition samples after first loop. """ while True: all_not_obey = True # all sample print("scanning all sample!") for i1 in [i for i in self._all_samples if self._check_obey_kkt(i)]: all_not_obey = False yield from self._choose_a2(i1) # non-bound sample print("scanning non-bound sample!") while True: not_obey = True for i1 in [ i for i in self._all_samples if self._check_obey_kkt(i) and self._is_unbound(i) ]: not_obey = False yield from self._choose_a2(i1) if not_obey: print("all non-bound samples fit the KKT condition!") break if all_not_obey: print("all samples fit the KKT condition! Optimization done!") break return False def _choose_a2(self, i1): """ Choose the second alpha by using heuristic algorithm ;steps: 1: Choose alpha2 which gets the maximum step size (|E1 - E2|). 2: Start in a random point,loop over all non-bound samples till alpha1 and alpha2 are optimized. 3: Start in a random point,loop over all samples till alpha1 and alpha2 are optimized. """ self._unbound = [i for i in self._all_samples if self._is_unbound(i)] if len(self.unbound) > 0: tmp_error = self._error.copy().tolist() tmp_error_dict = { index: value for index, value in enumerate(tmp_error) if self._is_unbound(index) } if self._e(i1) >= 0: i2 = min(tmp_error_dict, key=lambda index: tmp_error_dict[index]) else: i2 = max(tmp_error_dict, key=lambda index: tmp_error_dict[index]) cmd = yield i1, i2 if cmd is None: return for i2 in np.roll(self.unbound, np.random.choice(self.length)): cmd = yield i1, i2 if cmd is None: return for i2 in np.roll(self._all_samples, np.random.choice(self.length)): cmd = yield i1, i2 if cmd is None: return # Get the new alpha2 and new alpha1 def _get_new_alpha(self, i1, i2, a1, a2, e1, e2, y1, y2): K = self._k if i1 == i2: return None, None # calculate L and H which bound the new alpha2 s = y1 * y2 if s == -1: L, H = max(0.0, a2 - a1), min(self._c, self._c + a2 - a1) else: L, H = max(0.0, a2 + a1 - self._c), min(self._c, a2 + a1) if L == H: return None, None # calculate eta k11 = K(i1, i1) k22 = K(i2, i2) k12 = K(i1, i2) eta = k11 + k22 - 2.0 * k12 # select the new alpha2 which could get the minimal objectives if eta > 0.0: a2_new_unc = a2 + (y2 * (e1 - e2)) / eta # a2_new has a boundary if a2_new_unc >= H: a2_new = H elif a2_new_unc <= L: a2_new = L else: a2_new = a2_new_unc else: b = self._b l1 = a1 + s * (a2 - L) h1 = a1 + s * (a2 - H) # way 1 f1 = y1 * (e1 + b) - a1 * K(i1, i1) - s * a2 * K(i1, i2) f2 = y2 * (e2 + b) - a2 * K(i2, i2) - s * a1 * K(i1, i2) ol = ( l1 * f1 + L * f2 + 1 / 2 * l1**2 * K(i1, i1) + 1 / 2 * L**2 * K(i2, i2) + s * L * l1 * K(i1, i2) ) oh = ( h1 * f1 + H * f2 + 1 / 2 * h1**2 * K(i1, i1) + 1 / 2 * H**2 * K(i2, i2) + s * H * h1 * K(i1, i2) ) """ # way 2 Use objective function check which alpha2 new could get the minimal objectives """ if ol < (oh - self._eps): a2_new = L elif ol > oh + self._eps: a2_new = H else: a2_new = a2 # a1_new has a boundary too a1_new = a1 + s * (a2 - a2_new) if a1_new < 0: a2_new += s * a1_new a1_new = 0 if a1_new > self._c: a2_new += s * (a1_new - self._c) a1_new = self._c return a1_new, a2_new # Normalise data using min_max way def _norm(self, data): if self._init: self._min = np.min(data, axis=0) self._max = np.max(data, axis=0) self._init = False return (data - self._min) / (self._max - self._min) else: return (data - self._min) / (self._max - self._min) def _is_unbound(self, index): if 0.0 < self.alphas[index] < self._c: return True else: return False def _is_support(self, index): if self.alphas[index] > 0: return True else: return False @property def unbound(self): return self._unbound @property def support(self): return [i for i in range(self.length) if self._is_support(i)] @property def length(self): return self.samples.shape[0] class Kernel: def __init__(self, kernel, degree=1.0, coef0=0.0, gamma=1.0): self.degree = np.float64(degree) self.coef0 = np.float64(coef0) self.gamma = np.float64(gamma) self._kernel_name = kernel self._kernel = self._get_kernel(kernel_name=kernel) self._check() def _polynomial(self, v1, v2): return (self.gamma * np.inner(v1, v2) + self.coef0) ** self.degree def _linear(self, v1, v2): return np.inner(v1, v2) + self.coef0 def _rbf(self, v1, v2): return np.exp(-1 * (self.gamma * np.linalg.norm(v1 - v2) ** 2)) def _check(self): if self._kernel == self._rbf: if self.gamma < 0: raise ValueError("gamma value must greater than 0") def _get_kernel(self, kernel_name): maps = {"linear": self._linear, "poly": self._polynomial, "rbf": self._rbf} return maps[kernel_name] def __call__(self, v1, v2): return self._kernel(v1, v2) def __repr__(self): return self._kernel_name def count_time(func): def call_func(*args, **kwargs): import time start_time = time.time() func(*args, **kwargs) end_time = time.time() print(f"smo algorithm cost {end_time - start_time} seconds") return call_func @count_time def test_cancel_data(): print("Hello!\nStart test svm by smo algorithm!") # 0: download dataset and load into pandas' dataframe if not os.path.exists(r"cancel_data.csv"): request = urllib.request.Request( CANCER_DATASET_URL, headers={"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"}, ) response = urllib.request.urlopen(request) content = response.read().decode("utf-8") with open(r"cancel_data.csv", "w") as f: f.write(content) data = pd.read_csv(r"cancel_data.csv", header=None) # 1: pre-processing data del data[data.columns.tolist()[0]] data = data.dropna(axis=0) data = data.replace({"M": np.float64(1), "B": np.float64(-1)}) samples = np.array(data)[:, :] # 2: dividing data into train_data data and test_data data train_data, test_data = samples[:328, :], samples[328:, :] test_tags, test_samples = test_data[:, 0], test_data[:, 1:] # 3: choose kernel function,and set initial alphas to zero(optional) mykernel = Kernel(kernel="rbf", degree=5, coef0=1, gamma=0.5) al = np.zeros(train_data.shape[0]) # 4: calculating best alphas using SMO algorithm and predict test_data samples mysvm = SmoSVM( train=train_data, kernel_func=mykernel, alpha_list=al, cost=0.4, b=0.0, tolerance=0.001, ) mysvm.fit() predict = mysvm.predict(test_samples) # 5: check accuracy score = 0 test_num = test_tags.shape[0] for i in range(test_tags.shape[0]): if test_tags[i] == predict[i]: score += 1 print(f"\nall: {test_num}\nright: {score}\nfalse: {test_num - score}") print(f"Rough Accuracy: {score / test_tags.shape[0]}") def test_demonstration(): # change stdout print("\nStart plot,please wait!!!") sys.stdout = open(os.devnull, "w") ax1 = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 0)) ax4 = plt.subplot2grid((2, 2), (1, 1)) ax1.set_title("linear svm,cost:0.1") test_linear_kernel(ax1, cost=0.1) ax2.set_title("linear svm,cost:500") test_linear_kernel(ax2, cost=500) ax3.set_title("rbf kernel svm,cost:0.1") test_rbf_kernel(ax3, cost=0.1) ax4.set_title("rbf kernel svm,cost:500") test_rbf_kernel(ax4, cost=500) sys.stdout = sys.__stdout__ print("Plot done!!!") def test_linear_kernel(ax, cost): train_x, train_y = make_blobs( n_samples=500, centers=2, n_features=2, random_state=1 ) train_y[train_y == 0] = -1 scaler = StandardScaler() train_x_scaled = scaler.fit_transform(train_x, train_y) train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled)) mykernel = Kernel(kernel="linear", degree=5, coef0=1, gamma=0.5) mysvm = SmoSVM( train=train_data, kernel_func=mykernel, cost=cost, tolerance=0.001, auto_norm=False, ) mysvm.fit() plot_partition_boundary(mysvm, train_data, ax=ax) def test_rbf_kernel(ax, cost): train_x, train_y = make_circles( n_samples=500, noise=0.1, factor=0.1, random_state=1 ) train_y[train_y == 0] = -1 scaler = StandardScaler() train_x_scaled = scaler.fit_transform(train_x, train_y) train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled)) mykernel = Kernel(kernel="rbf", degree=5, coef0=1, gamma=0.5) mysvm = SmoSVM( train=train_data, kernel_func=mykernel, cost=cost, tolerance=0.001, auto_norm=False, ) mysvm.fit() plot_partition_boundary(mysvm, train_data, ax=ax) def plot_partition_boundary( model, train_data, ax, resolution=100, colors=("b", "k", "r") ): """ We can not get the optimum w of our kernel svm model which is different from linear svm. For this reason, we generate randomly distributed points with high desity and prediced values of these points are calculated by using our tained model. Then we could use this prediced values to draw contour map. And this contour map can represent svm's partition boundary. """ train_data_x = train_data[:, 1] train_data_y = train_data[:, 2] train_data_tags = train_data[:, 0] xrange = np.linspace(train_data_x.min(), train_data_x.max(), resolution) yrange = np.linspace(train_data_y.min(), train_data_y.max(), resolution) test_samples = np.array([(x, y) for x in xrange for y in yrange]).reshape( resolution * resolution, 2 ) test_tags = model.predict(test_samples, classify=False) grid = test_tags.reshape((len(xrange), len(yrange))) # Plot contour map which represents the partition boundary ax.contour( xrange, yrange, np.mat(grid).T, levels=(-1, 0, 1), linestyles=("--", "-", "--"), linewidths=(1, 1, 1), colors=colors, ) # Plot all train samples ax.scatter( train_data_x, train_data_y, c=train_data_tags, cmap=plt.cm.Dark2, lw=0, alpha=0.5, ) # Plot support vectors support = model.support ax.scatter( train_data_x[support], train_data_y[support], c=train_data_tags[support], cmap=plt.cm.Dark2, ) if __name__ == "__main__": test_cancel_data() test_demonstration() plt.show()
""" Implementation of sequential minimal optimization (SMO) for support vector machines (SVM). Sequential minimal optimization (SMO) is an algorithm for solving the quadratic programming (QP) problem that arises during the training of support vector machines. It was invented by John Platt in 1998. Input: 0: type: numpy.ndarray. 1: first column of ndarray must be tags of samples, must be 1 or -1. 2: rows of ndarray represent samples. Usage: Command: python3 sequential_minimum_optimization.py Code: from sequential_minimum_optimization import SmoSVM, Kernel kernel = Kernel(kernel='poly', degree=3., coef0=1., gamma=0.5) init_alphas = np.zeros(train.shape[0]) SVM = SmoSVM(train=train, alpha_list=init_alphas, kernel_func=kernel, cost=0.4, b=0.0, tolerance=0.001) SVM.fit() predict = SVM.predict(test_samples) Reference: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/smo-book.pdf https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-98-14.pdf http://web.cs.iastate.edu/~honavar/smo-svm.pdf """ import os import sys import urllib.request import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.datasets import make_blobs, make_circles from sklearn.preprocessing import StandardScaler CANCER_DATASET_URL = ( "http://archive.ics.uci.edu/ml/machine-learning-databases/" "breast-cancer-wisconsin/wdbc.data" ) class SmoSVM: def __init__( self, train, kernel_func, alpha_list=None, cost=0.4, b=0.0, tolerance=0.001, auto_norm=True, ): self._init = True self._auto_norm = auto_norm self._c = np.float64(cost) self._b = np.float64(b) self._tol = np.float64(tolerance) if tolerance > 0.0001 else np.float64(0.001) self.tags = train[:, 0] self.samples = self._norm(train[:, 1:]) if self._auto_norm else train[:, 1:] self.alphas = alpha_list if alpha_list is not None else np.zeros(train.shape[0]) self.Kernel = kernel_func self._eps = 0.001 self._all_samples = list(range(self.length)) self._K_matrix = self._calculate_k_matrix() self._error = np.zeros(self.length) self._unbound = [] self.choose_alpha = self._choose_alphas() # Calculate alphas using SMO algorithm def fit(self): K = self._k state = None while True: # 1: Find alpha1, alpha2 try: i1, i2 = self.choose_alpha.send(state) state = None except StopIteration: print("Optimization done!\nEvery sample satisfy the KKT condition!") break # 2: calculate new alpha2 and new alpha1 y1, y2 = self.tags[i1], self.tags[i2] a1, a2 = self.alphas[i1].copy(), self.alphas[i2].copy() e1, e2 = self._e(i1), self._e(i2) args = (i1, i2, a1, a2, e1, e2, y1, y2) a1_new, a2_new = self._get_new_alpha(*args) if not a1_new and not a2_new: state = False continue self.alphas[i1], self.alphas[i2] = a1_new, a2_new # 3: update threshold(b) b1_new = np.float64( -e1 - y1 * K(i1, i1) * (a1_new - a1) - y2 * K(i2, i1) * (a2_new - a2) + self._b ) b2_new = np.float64( -e2 - y2 * K(i2, i2) * (a2_new - a2) - y1 * K(i1, i2) * (a1_new - a1) + self._b ) if 0.0 < a1_new < self._c: b = b1_new if 0.0 < a2_new < self._c: b = b2_new if not (np.float64(0) < a2_new < self._c) and not ( np.float64(0) < a1_new < self._c ): b = (b1_new + b2_new) / 2.0 b_old = self._b self._b = b # 4: update error value,here we only calculate those non-bound samples' # error self._unbound = [i for i in self._all_samples if self._is_unbound(i)] for s in self.unbound: if s == i1 or s == i2: continue self._error[s] += ( y1 * (a1_new - a1) * K(i1, s) + y2 * (a2_new - a2) * K(i2, s) + (self._b - b_old) ) # if i1 or i2 is non-bound,update there error value to zero if self._is_unbound(i1): self._error[i1] = 0 if self._is_unbound(i2): self._error[i2] = 0 # Predict test samples def predict(self, test_samples, classify=True): if test_samples.shape[1] > self.samples.shape[1]: raise ValueError( "Test samples' feature length does not equal to that of train samples" ) if self._auto_norm: test_samples = self._norm(test_samples) results = [] for test_sample in test_samples: result = self._predict(test_sample) if classify: results.append(1 if result > 0 else -1) else: results.append(result) return np.array(results) # Check if alpha violate KKT condition def _check_obey_kkt(self, index): alphas = self.alphas tol = self._tol r = self._e(index) * self.tags[index] c = self._c return (r < -tol and alphas[index] < c) or (r > tol and alphas[index] > 0.0) # Get value calculated from kernel function def _k(self, i1, i2): # for test samples,use Kernel function if isinstance(i2, np.ndarray): return self.Kernel(self.samples[i1], i2) # for train samples,Kernel values have been saved in matrix else: return self._K_matrix[i1, i2] # Get sample's error def _e(self, index): """ Two cases: 1:Sample[index] is non-bound,Fetch error from list: _error 2:sample[index] is bound,Use predicted value deduct true value: g(xi) - yi """ # get from error data if self._is_unbound(index): return self._error[index] # get by g(xi) - yi else: gx = np.dot(self.alphas * self.tags, self._K_matrix[:, index]) + self._b yi = self.tags[index] return gx - yi # Calculate Kernel matrix of all possible i1,i2 ,saving time def _calculate_k_matrix(self): k_matrix = np.zeros([self.length, self.length]) for i in self._all_samples: for j in self._all_samples: k_matrix[i, j] = np.float64( self.Kernel(self.samples[i, :], self.samples[j, :]) ) return k_matrix # Predict test sample's tag def _predict(self, sample): k = self._k predicted_value = ( np.sum( [ self.alphas[i1] * self.tags[i1] * k(i1, sample) for i1 in self._all_samples ] ) + self._b ) return predicted_value # Choose alpha1 and alpha2 def _choose_alphas(self): locis = yield from self._choose_a1() if not locis: return return locis def _choose_a1(self): """ Choose first alpha ;steps: 1:First loop over all sample 2:Second loop over all non-bound samples till all non-bound samples does not voilate kkt condition. 3:Repeat this two process endlessly,till all samples does not voilate kkt condition samples after first loop. """ while True: all_not_obey = True # all sample print("scanning all sample!") for i1 in [i for i in self._all_samples if self._check_obey_kkt(i)]: all_not_obey = False yield from self._choose_a2(i1) # non-bound sample print("scanning non-bound sample!") while True: not_obey = True for i1 in [ i for i in self._all_samples if self._check_obey_kkt(i) and self._is_unbound(i) ]: not_obey = False yield from self._choose_a2(i1) if not_obey: print("all non-bound samples fit the KKT condition!") break if all_not_obey: print("all samples fit the KKT condition! Optimization done!") break return False def _choose_a2(self, i1): """ Choose the second alpha by using heuristic algorithm ;steps: 1: Choose alpha2 which gets the maximum step size (|E1 - E2|). 2: Start in a random point,loop over all non-bound samples till alpha1 and alpha2 are optimized. 3: Start in a random point,loop over all samples till alpha1 and alpha2 are optimized. """ self._unbound = [i for i in self._all_samples if self._is_unbound(i)] if len(self.unbound) > 0: tmp_error = self._error.copy().tolist() tmp_error_dict = { index: value for index, value in enumerate(tmp_error) if self._is_unbound(index) } if self._e(i1) >= 0: i2 = min(tmp_error_dict, key=lambda index: tmp_error_dict[index]) else: i2 = max(tmp_error_dict, key=lambda index: tmp_error_dict[index]) cmd = yield i1, i2 if cmd is None: return for i2 in np.roll(self.unbound, np.random.choice(self.length)): cmd = yield i1, i2 if cmd is None: return for i2 in np.roll(self._all_samples, np.random.choice(self.length)): cmd = yield i1, i2 if cmd is None: return # Get the new alpha2 and new alpha1 def _get_new_alpha(self, i1, i2, a1, a2, e1, e2, y1, y2): K = self._k if i1 == i2: return None, None # calculate L and H which bound the new alpha2 s = y1 * y2 if s == -1: L, H = max(0.0, a2 - a1), min(self._c, self._c + a2 - a1) else: L, H = max(0.0, a2 + a1 - self._c), min(self._c, a2 + a1) if L == H: return None, None # calculate eta k11 = K(i1, i1) k22 = K(i2, i2) k12 = K(i1, i2) eta = k11 + k22 - 2.0 * k12 # select the new alpha2 which could get the minimal objectives if eta > 0.0: a2_new_unc = a2 + (y2 * (e1 - e2)) / eta # a2_new has a boundary if a2_new_unc >= H: a2_new = H elif a2_new_unc <= L: a2_new = L else: a2_new = a2_new_unc else: b = self._b l1 = a1 + s * (a2 - L) h1 = a1 + s * (a2 - H) # way 1 f1 = y1 * (e1 + b) - a1 * K(i1, i1) - s * a2 * K(i1, i2) f2 = y2 * (e2 + b) - a2 * K(i2, i2) - s * a1 * K(i1, i2) ol = ( l1 * f1 + L * f2 + 1 / 2 * l1**2 * K(i1, i1) + 1 / 2 * L**2 * K(i2, i2) + s * L * l1 * K(i1, i2) ) oh = ( h1 * f1 + H * f2 + 1 / 2 * h1**2 * K(i1, i1) + 1 / 2 * H**2 * K(i2, i2) + s * H * h1 * K(i1, i2) ) """ # way 2 Use objective function check which alpha2 new could get the minimal objectives """ if ol < (oh - self._eps): a2_new = L elif ol > oh + self._eps: a2_new = H else: a2_new = a2 # a1_new has a boundary too a1_new = a1 + s * (a2 - a2_new) if a1_new < 0: a2_new += s * a1_new a1_new = 0 if a1_new > self._c: a2_new += s * (a1_new - self._c) a1_new = self._c return a1_new, a2_new # Normalise data using min_max way def _norm(self, data): if self._init: self._min = np.min(data, axis=0) self._max = np.max(data, axis=0) self._init = False return (data - self._min) / (self._max - self._min) else: return (data - self._min) / (self._max - self._min) def _is_unbound(self, index): if 0.0 < self.alphas[index] < self._c: return True else: return False def _is_support(self, index): if self.alphas[index] > 0: return True else: return False @property def unbound(self): return self._unbound @property def support(self): return [i for i in range(self.length) if self._is_support(i)] @property def length(self): return self.samples.shape[0] class Kernel: def __init__(self, kernel, degree=1.0, coef0=0.0, gamma=1.0): self.degree = np.float64(degree) self.coef0 = np.float64(coef0) self.gamma = np.float64(gamma) self._kernel_name = kernel self._kernel = self._get_kernel(kernel_name=kernel) self._check() def _polynomial(self, v1, v2): return (self.gamma * np.inner(v1, v2) + self.coef0) ** self.degree def _linear(self, v1, v2): return np.inner(v1, v2) + self.coef0 def _rbf(self, v1, v2): return np.exp(-1 * (self.gamma * np.linalg.norm(v1 - v2) ** 2)) def _check(self): if self._kernel == self._rbf: if self.gamma < 0: raise ValueError("gamma value must greater than 0") def _get_kernel(self, kernel_name): maps = {"linear": self._linear, "poly": self._polynomial, "rbf": self._rbf} return maps[kernel_name] def __call__(self, v1, v2): return self._kernel(v1, v2) def __repr__(self): return self._kernel_name def count_time(func): def call_func(*args, **kwargs): import time start_time = time.time() func(*args, **kwargs) end_time = time.time() print(f"smo algorithm cost {end_time - start_time} seconds") return call_func @count_time def test_cancel_data(): print("Hello!\nStart test svm by smo algorithm!") # 0: download dataset and load into pandas' dataframe if not os.path.exists(r"cancel_data.csv"): request = urllib.request.Request( CANCER_DATASET_URL, headers={"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"}, ) response = urllib.request.urlopen(request) content = response.read().decode("utf-8") with open(r"cancel_data.csv", "w") as f: f.write(content) data = pd.read_csv(r"cancel_data.csv", header=None) # 1: pre-processing data del data[data.columns.tolist()[0]] data = data.dropna(axis=0) data = data.replace({"M": np.float64(1), "B": np.float64(-1)}) samples = np.array(data)[:, :] # 2: dividing data into train_data data and test_data data train_data, test_data = samples[:328, :], samples[328:, :] test_tags, test_samples = test_data[:, 0], test_data[:, 1:] # 3: choose kernel function,and set initial alphas to zero(optional) mykernel = Kernel(kernel="rbf", degree=5, coef0=1, gamma=0.5) al = np.zeros(train_data.shape[0]) # 4: calculating best alphas using SMO algorithm and predict test_data samples mysvm = SmoSVM( train=train_data, kernel_func=mykernel, alpha_list=al, cost=0.4, b=0.0, tolerance=0.001, ) mysvm.fit() predict = mysvm.predict(test_samples) # 5: check accuracy score = 0 test_num = test_tags.shape[0] for i in range(test_tags.shape[0]): if test_tags[i] == predict[i]: score += 1 print(f"\nall: {test_num}\nright: {score}\nfalse: {test_num - score}") print(f"Rough Accuracy: {score / test_tags.shape[0]}") def test_demonstration(): # change stdout print("\nStart plot,please wait!!!") sys.stdout = open(os.devnull, "w") ax1 = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 0)) ax4 = plt.subplot2grid((2, 2), (1, 1)) ax1.set_title("linear svm,cost:0.1") test_linear_kernel(ax1, cost=0.1) ax2.set_title("linear svm,cost:500") test_linear_kernel(ax2, cost=500) ax3.set_title("rbf kernel svm,cost:0.1") test_rbf_kernel(ax3, cost=0.1) ax4.set_title("rbf kernel svm,cost:500") test_rbf_kernel(ax4, cost=500) sys.stdout = sys.__stdout__ print("Plot done!!!") def test_linear_kernel(ax, cost): train_x, train_y = make_blobs( n_samples=500, centers=2, n_features=2, random_state=1 ) train_y[train_y == 0] = -1 scaler = StandardScaler() train_x_scaled = scaler.fit_transform(train_x, train_y) train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled)) mykernel = Kernel(kernel="linear", degree=5, coef0=1, gamma=0.5) mysvm = SmoSVM( train=train_data, kernel_func=mykernel, cost=cost, tolerance=0.001, auto_norm=False, ) mysvm.fit() plot_partition_boundary(mysvm, train_data, ax=ax) def test_rbf_kernel(ax, cost): train_x, train_y = make_circles( n_samples=500, noise=0.1, factor=0.1, random_state=1 ) train_y[train_y == 0] = -1 scaler = StandardScaler() train_x_scaled = scaler.fit_transform(train_x, train_y) train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled)) mykernel = Kernel(kernel="rbf", degree=5, coef0=1, gamma=0.5) mysvm = SmoSVM( train=train_data, kernel_func=mykernel, cost=cost, tolerance=0.001, auto_norm=False, ) mysvm.fit() plot_partition_boundary(mysvm, train_data, ax=ax) def plot_partition_boundary( model, train_data, ax, resolution=100, colors=("b", "k", "r") ): """ We can not get the optimum w of our kernel svm model which is different from linear svm. For this reason, we generate randomly distributed points with high desity and prediced values of these points are calculated by using our tained model. Then we could use this prediced values to draw contour map. And this contour map can represent svm's partition boundary. """ train_data_x = train_data[:, 1] train_data_y = train_data[:, 2] train_data_tags = train_data[:, 0] xrange = np.linspace(train_data_x.min(), train_data_x.max(), resolution) yrange = np.linspace(train_data_y.min(), train_data_y.max(), resolution) test_samples = np.array([(x, y) for x in xrange for y in yrange]).reshape( resolution * resolution, 2 ) test_tags = model.predict(test_samples, classify=False) grid = test_tags.reshape((len(xrange), len(yrange))) # Plot contour map which represents the partition boundary ax.contour( xrange, yrange, np.mat(grid).T, levels=(-1, 0, 1), linestyles=("--", "-", "--"), linewidths=(1, 1, 1), colors=colors, ) # Plot all train samples ax.scatter( train_data_x, train_data_y, c=train_data_tags, cmap=plt.cm.Dark2, lw=0, alpha=0.5, ) # Plot support vectors support = model.support ax.scatter( train_data_x[support], train_data_y[support], c=train_data_tags[support], cmap=plt.cm.Dark2, ) if __name__ == "__main__": test_cancel_data() test_demonstration() plt.show()
1
TheAlgorithms/Python
6,629
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2022-10-03T19:21:25Z"
"2022-10-03T20:00:46Z"
e9862adafce9eb682cabcf8ac502893e0272ae65
756bb268eb22199534fc8d6478cf0e006f02b56b
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
""" Problem 45: https://projecteuler.net/problem=45 Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle T(n) = (n * (n + 1)) / 2 1, 3, 6, 10, 15, ... Pentagonal P(n) = (n * (3 * n − 1)) / 2 1, 5, 12, 22, 35, ... Hexagonal H(n) = n * (2 * n − 1) 1, 6, 15, 28, 45, ... It can be verified that T(285) = P(165) = H(143) = 40755. Find the next triangle number that is also pentagonal and hexagonal. All trinagle numbers are hexagonal numbers. T(2n-1) = n * (2 * n - 1) = H(n) So we shall check only for hexagonal numbers which are also pentagonal. """ def hexagonal_num(n: int) -> int: """ Returns nth hexagonal number >>> hexagonal_num(143) 40755 >>> hexagonal_num(21) 861 >>> hexagonal_num(10) 190 """ return n * (2 * n - 1) def is_pentagonal(n: int) -> bool: """ Returns True if n is pentagonal, False otherwise. >>> is_pentagonal(330) True >>> is_pentagonal(7683) False >>> is_pentagonal(2380) True """ root = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def solution(start: int = 144) -> int: """ Returns the next number which is triangular, pentagonal and hexagonal. >>> solution(144) 1533776805 """ n = start num = hexagonal_num(n) while not is_pentagonal(num): n += 1 num = hexagonal_num(n) return num if __name__ == "__main__": print(f"{solution()} = ")
""" Problem 45: https://projecteuler.net/problem=45 Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle T(n) = (n * (n + 1)) / 2 1, 3, 6, 10, 15, ... Pentagonal P(n) = (n * (3 * n − 1)) / 2 1, 5, 12, 22, 35, ... Hexagonal H(n) = n * (2 * n − 1) 1, 6, 15, 28, 45, ... It can be verified that T(285) = P(165) = H(143) = 40755. Find the next triangle number that is also pentagonal and hexagonal. All triangle numbers are hexagonal numbers. T(2n-1) = n * (2 * n - 1) = H(n) So we shall check only for hexagonal numbers which are also pentagonal. """ def hexagonal_num(n: int) -> int: """ Returns nth hexagonal number >>> hexagonal_num(143) 40755 >>> hexagonal_num(21) 861 >>> hexagonal_num(10) 190 """ return n * (2 * n - 1) def is_pentagonal(n: int) -> bool: """ Returns True if n is pentagonal, False otherwise. >>> is_pentagonal(330) True >>> is_pentagonal(7683) False >>> is_pentagonal(2380) True """ root = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def solution(start: int = 144) -> int: """ Returns the next number which is triangular, pentagonal and hexagonal. >>> solution(144) 1533776805 """ n = start num = hexagonal_num(n) while not is_pentagonal(num): n += 1 num = hexagonal_num(n) return num if __name__ == "__main__": print(f"{solution()} = ")
1
TheAlgorithms/Python
6,629
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2022-10-03T19:21:25Z"
"2022-10-03T20:00:46Z"
e9862adafce9eb682cabcf8ac502893e0272ae65
756bb268eb22199534fc8d6478cf0e006f02b56b
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
""" Project Euler Problem 113: https://projecteuler.net/problem=113 Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349. As n increases, the proportion of bouncy numbers below n increases such that there are only 12951 numbers below one-million that are not bouncy and only 277032 non-bouncy numbers below 10^10. How many numbers below a googol (10^100) are not bouncy? """ def choose(n: int, r: int) -> int: """ Calculate the binomial coefficient c(n,r) using the multiplicative formula. >>> choose(4,2) 6 >>> choose(5,3) 10 >>> choose(20,6) 38760 """ ret = 1.0 for i in range(1, r + 1): ret *= (n + 1 - i) / i return round(ret) def non_bouncy_exact(n: int) -> int: """ Calculate the number of non-bouncy numbers with at most n digits. >>> non_bouncy_exact(1) 9 >>> non_bouncy_exact(6) 7998 >>> non_bouncy_exact(10) 136126 """ return choose(8 + n, n) + choose(9 + n, n) - 10 def non_bouncy_upto(n: int) -> int: """ Calculate the number of non-bouncy numbers with at most n digits. >>> non_bouncy_upto(1) 9 >>> non_bouncy_upto(6) 12951 >>> non_bouncy_upto(10) 277032 """ return sum(non_bouncy_exact(i) for i in range(1, n + 1)) def solution(num_digits: int = 100) -> int: """ Caclulate the number of non-bouncy numbers less than a googol. >>> solution(6) 12951 >>> solution(10) 277032 """ return non_bouncy_upto(num_digits) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 113: https://projecteuler.net/problem=113 Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349. As n increases, the proportion of bouncy numbers below n increases such that there are only 12951 numbers below one-million that are not bouncy and only 277032 non-bouncy numbers below 10^10. How many numbers below a googol (10^100) are not bouncy? """ def choose(n: int, r: int) -> int: """ Calculate the binomial coefficient c(n,r) using the multiplicative formula. >>> choose(4,2) 6 >>> choose(5,3) 10 >>> choose(20,6) 38760 """ ret = 1.0 for i in range(1, r + 1): ret *= (n + 1 - i) / i return round(ret) def non_bouncy_exact(n: int) -> int: """ Calculate the number of non-bouncy numbers with at most n digits. >>> non_bouncy_exact(1) 9 >>> non_bouncy_exact(6) 7998 >>> non_bouncy_exact(10) 136126 """ return choose(8 + n, n) + choose(9 + n, n) - 10 def non_bouncy_upto(n: int) -> int: """ Calculate the number of non-bouncy numbers with at most n digits. >>> non_bouncy_upto(1) 9 >>> non_bouncy_upto(6) 12951 >>> non_bouncy_upto(10) 277032 """ return sum(non_bouncy_exact(i) for i in range(1, n + 1)) def solution(num_digits: int = 100) -> int: """ Calculate the number of non-bouncy numbers less than a googol. >>> solution(6) 12951 >>> solution(10) 277032 """ return non_bouncy_upto(num_digits) if __name__ == "__main__": print(f"{solution() = }")
1
TheAlgorithms/Python
6,629
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2022-10-03T19:21:25Z"
"2022-10-03T20:00:46Z"
e9862adafce9eb682cabcf8ac502893e0272ae65
756bb268eb22199534fc8d6478cf0e006f02b56b
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
from collections import deque class Process: def __init__(self, process_name: str, arrival_time: int, burst_time: int) -> None: self.process_name = process_name # process name self.arrival_time = arrival_time # arrival time of the process # completion time of finished process or last interrupted time self.stop_time = arrival_time self.burst_time = burst_time # remaining burst time self.waiting_time = 0 # total time of the process wait in ready queue self.turnaround_time = 0 # time from arrival time to completion time class MLFQ: """ MLFQ(Multi Level Feedback Queue) https://en.wikipedia.org/wiki/Multilevel_feedback_queue MLFQ has a lot of queues that have different priority In this MLFQ, The first Queue(0) to last second Queue(N-2) of MLFQ have Round Robin Algorithm The last Queue(N-1) has First Come, First Served Algorithm """ def __init__( self, number_of_queues: int, time_slices: list[int], queue: deque[Process], current_time: int, ) -> None: # total number of mlfq's queues self.number_of_queues = number_of_queues # time slice of queues that round robin algorithm applied self.time_slices = time_slices # unfinished process is in this ready_queue self.ready_queue = queue # current time self.current_time = current_time # finished process is in this sequence queue self.finish_queue: deque[Process] = deque() def calculate_sequence_of_finish_queue(self) -> list[str]: """ This method returns the sequence of finished processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_sequence_of_finish_queue() ['P2', 'P4', 'P1', 'P3'] """ sequence = [] for i in range(len(self.finish_queue)): sequence.append(self.finish_queue[i].process_name) return sequence def calculate_waiting_time(self, queue: list[Process]) -> list[int]: """ This method calculates waiting time of processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_waiting_time([P1, P2, P3, P4]) [83, 17, 94, 101] """ waiting_times = [] for i in range(len(queue)): waiting_times.append(queue[i].waiting_time) return waiting_times def calculate_turnaround_time(self, queue: list[Process]) -> list[int]: """ This method calculates turnaround time of processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_turnaround_time([P1, P2, P3, P4]) [136, 34, 162, 125] """ turnaround_times = [] for i in range(len(queue)): turnaround_times.append(queue[i].turnaround_time) return turnaround_times def calculate_completion_time(self, queue: list[Process]) -> list[int]: """ This method calculates completion time of processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_turnaround_time([P1, P2, P3, P4]) [136, 34, 162, 125] """ completion_times = [] for i in range(len(queue)): completion_times.append(queue[i].stop_time) return completion_times def calculate_remaining_burst_time_of_processes( self, queue: deque[Process] ) -> list[int]: """ This method calculate remaining burst time of processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> finish_queue, ready_queue = mlfq.round_robin(deque([P1, P2, P3, P4]), 17) >>> mlfq.calculate_remaining_burst_time_of_processes(mlfq.finish_queue) [0] >>> mlfq.calculate_remaining_burst_time_of_processes(ready_queue) [36, 51, 7] >>> finish_queue, ready_queue = mlfq.round_robin(ready_queue, 25) >>> mlfq.calculate_remaining_burst_time_of_processes(mlfq.finish_queue) [0, 0] >>> mlfq.calculate_remaining_burst_time_of_processes(ready_queue) [11, 26] """ return [q.burst_time for q in queue] def update_waiting_time(self, process: Process) -> int: """ This method updates waiting times of unfinished processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> mlfq.current_time = 10 >>> P1.stop_time = 5 >>> mlfq.update_waiting_time(P1) 5 """ process.waiting_time += self.current_time - process.stop_time return process.waiting_time def first_come_first_served(self, ready_queue: deque[Process]) -> deque[Process]: """ FCFS(First Come, First Served) FCFS will be applied to MLFQ's last queue A first came process will be finished at first >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.first_come_first_served(mlfq.ready_queue) >>> mlfq.calculate_sequence_of_finish_queue() ['P1', 'P2', 'P3', 'P4'] """ finished: deque[Process] = deque() # sequence deque of finished process while len(ready_queue) != 0: cp = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(cp) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 cp.burst_time = 0 # set the process's turnaround time because it is finished cp.turnaround_time = self.current_time - cp.arrival_time # set the completion time cp.stop_time = self.current_time # add the process to queue that has finished queue finished.append(cp) self.finish_queue.extend(finished) # add finished process to finish queue # FCFS will finish all remaining processes return finished def round_robin( self, ready_queue: deque[Process], time_slice: int ) -> tuple[deque[Process], deque[Process]]: """ RR(Round Robin) RR will be applied to MLFQ's all queues except last queue All processes can't use CPU for time more than time_slice If the process consume CPU up to time_slice, it will go back to ready queue >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> finish_queue, ready_queue = mlfq.round_robin(mlfq.ready_queue, 17) >>> mlfq.calculate_sequence_of_finish_queue() ['P2'] """ finished: deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for i in range(len(ready_queue)): cp = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(cp) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time cp.stop_time = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(cp) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished cp.burst_time = 0 # set the finish time cp.stop_time = self.current_time # update the process' turnaround time because it is finished cp.turnaround_time = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(cp) self.finish_queue.extend(finished) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def multi_level_feedback_queue(self) -> deque[Process]: """ MLFQ(Multi Level Feedback Queue) >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> finish_queue = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_sequence_of_finish_queue() ['P2', 'P4', 'P1', 'P3'] """ # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1): finished, self.ready_queue = self.round_robin( self.ready_queue, self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue) return self.finish_queue if __name__ == "__main__": import doctest P1 = Process("P1", 0, 53) P2 = Process("P2", 0, 17) P3 = Process("P3", 0, 68) P4 = Process("P4", 0, 24) number_of_queues = 3 time_slices = [17, 25] queue = deque([P1, P2, P3, P4]) if len(time_slices) != number_of_queues - 1: exit() doctest.testmod(extraglobs={"queue": deque([P1, P2, P3, P4])}) P1 = Process("P1", 0, 53) P2 = Process("P2", 0, 17) P3 = Process("P3", 0, 68) P4 = Process("P4", 0, 24) number_of_queues = 3 time_slices = [17, 25] queue = deque([P1, P2, P3, P4]) mlfq = MLFQ(number_of_queues, time_slices, queue, 0) finish_queue = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f"waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [P1, P2, P3, P4])}" ) # print completion times of processes(P1, P2, P3, P4) print( f"completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [P1, P2, P3, P4])}" ) # print total turnaround times of processes(P1, P2, P3, P4) print( f"turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [P1, P2, P3, P4])}" ) # print sequence of finished processes print( f"sequnece of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}" )
from collections import deque class Process: def __init__(self, process_name: str, arrival_time: int, burst_time: int) -> None: self.process_name = process_name # process name self.arrival_time = arrival_time # arrival time of the process # completion time of finished process or last interrupted time self.stop_time = arrival_time self.burst_time = burst_time # remaining burst time self.waiting_time = 0 # total time of the process wait in ready queue self.turnaround_time = 0 # time from arrival time to completion time class MLFQ: """ MLFQ(Multi Level Feedback Queue) https://en.wikipedia.org/wiki/Multilevel_feedback_queue MLFQ has a lot of queues that have different priority In this MLFQ, The first Queue(0) to last second Queue(N-2) of MLFQ have Round Robin Algorithm The last Queue(N-1) has First Come, First Served Algorithm """ def __init__( self, number_of_queues: int, time_slices: list[int], queue: deque[Process], current_time: int, ) -> None: # total number of mlfq's queues self.number_of_queues = number_of_queues # time slice of queues that round robin algorithm applied self.time_slices = time_slices # unfinished process is in this ready_queue self.ready_queue = queue # current time self.current_time = current_time # finished process is in this sequence queue self.finish_queue: deque[Process] = deque() def calculate_sequence_of_finish_queue(self) -> list[str]: """ This method returns the sequence of finished processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_sequence_of_finish_queue() ['P2', 'P4', 'P1', 'P3'] """ sequence = [] for i in range(len(self.finish_queue)): sequence.append(self.finish_queue[i].process_name) return sequence def calculate_waiting_time(self, queue: list[Process]) -> list[int]: """ This method calculates waiting time of processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_waiting_time([P1, P2, P3, P4]) [83, 17, 94, 101] """ waiting_times = [] for i in range(len(queue)): waiting_times.append(queue[i].waiting_time) return waiting_times def calculate_turnaround_time(self, queue: list[Process]) -> list[int]: """ This method calculates turnaround time of processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_turnaround_time([P1, P2, P3, P4]) [136, 34, 162, 125] """ turnaround_times = [] for i in range(len(queue)): turnaround_times.append(queue[i].turnaround_time) return turnaround_times def calculate_completion_time(self, queue: list[Process]) -> list[int]: """ This method calculates completion time of processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_turnaround_time([P1, P2, P3, P4]) [136, 34, 162, 125] """ completion_times = [] for i in range(len(queue)): completion_times.append(queue[i].stop_time) return completion_times def calculate_remaining_burst_time_of_processes( self, queue: deque[Process] ) -> list[int]: """ This method calculate remaining burst time of processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> finish_queue, ready_queue = mlfq.round_robin(deque([P1, P2, P3, P4]), 17) >>> mlfq.calculate_remaining_burst_time_of_processes(mlfq.finish_queue) [0] >>> mlfq.calculate_remaining_burst_time_of_processes(ready_queue) [36, 51, 7] >>> finish_queue, ready_queue = mlfq.round_robin(ready_queue, 25) >>> mlfq.calculate_remaining_burst_time_of_processes(mlfq.finish_queue) [0, 0] >>> mlfq.calculate_remaining_burst_time_of_processes(ready_queue) [11, 26] """ return [q.burst_time for q in queue] def update_waiting_time(self, process: Process) -> int: """ This method updates waiting times of unfinished processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> mlfq.current_time = 10 >>> P1.stop_time = 5 >>> mlfq.update_waiting_time(P1) 5 """ process.waiting_time += self.current_time - process.stop_time return process.waiting_time def first_come_first_served(self, ready_queue: deque[Process]) -> deque[Process]: """ FCFS(First Come, First Served) FCFS will be applied to MLFQ's last queue A first came process will be finished at first >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.first_come_first_served(mlfq.ready_queue) >>> mlfq.calculate_sequence_of_finish_queue() ['P1', 'P2', 'P3', 'P4'] """ finished: deque[Process] = deque() # sequence deque of finished process while len(ready_queue) != 0: cp = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(cp) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 cp.burst_time = 0 # set the process's turnaround time because it is finished cp.turnaround_time = self.current_time - cp.arrival_time # set the completion time cp.stop_time = self.current_time # add the process to queue that has finished queue finished.append(cp) self.finish_queue.extend(finished) # add finished process to finish queue # FCFS will finish all remaining processes return finished def round_robin( self, ready_queue: deque[Process], time_slice: int ) -> tuple[deque[Process], deque[Process]]: """ RR(Round Robin) RR will be applied to MLFQ's all queues except last queue All processes can't use CPU for time more than time_slice If the process consume CPU up to time_slice, it will go back to ready queue >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> finish_queue, ready_queue = mlfq.round_robin(mlfq.ready_queue, 17) >>> mlfq.calculate_sequence_of_finish_queue() ['P2'] """ finished: deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for i in range(len(ready_queue)): cp = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(cp) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time cp.stop_time = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(cp) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished cp.burst_time = 0 # set the finish time cp.stop_time = self.current_time # update the process' turnaround time because it is finished cp.turnaround_time = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(cp) self.finish_queue.extend(finished) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def multi_level_feedback_queue(self) -> deque[Process]: """ MLFQ(Multi Level Feedback Queue) >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> finish_queue = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_sequence_of_finish_queue() ['P2', 'P4', 'P1', 'P3'] """ # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1): finished, self.ready_queue = self.round_robin( self.ready_queue, self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue) return self.finish_queue if __name__ == "__main__": import doctest P1 = Process("P1", 0, 53) P2 = Process("P2", 0, 17) P3 = Process("P3", 0, 68) P4 = Process("P4", 0, 24) number_of_queues = 3 time_slices = [17, 25] queue = deque([P1, P2, P3, P4]) if len(time_slices) != number_of_queues - 1: exit() doctest.testmod(extraglobs={"queue": deque([P1, P2, P3, P4])}) P1 = Process("P1", 0, 53) P2 = Process("P2", 0, 17) P3 = Process("P3", 0, 68) P4 = Process("P4", 0, 24) number_of_queues = 3 time_slices = [17, 25] queue = deque([P1, P2, P3, P4]) mlfq = MLFQ(number_of_queues, time_slices, queue, 0) finish_queue = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f"waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [P1, P2, P3, P4])}" ) # print completion times of processes(P1, P2, P3, P4) print( f"completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [P1, P2, P3, P4])}" ) # print total turnaround times of processes(P1, P2, P3, P4) print( f"turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [P1, P2, P3, P4])}" ) # print sequence of finished processes print( f"sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}" )
1
TheAlgorithms/Python
6,629
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2022-10-03T19:21:25Z"
"2022-10-03T20:00:46Z"
e9862adafce9eb682cabcf8ac502893e0272ae65
756bb268eb22199534fc8d6478cf0e006f02b56b
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
import json import os import re import sys import urllib.request import requests from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } def download_images_from_google_query(query: str = "dhaka", max_images: int = 5) -> int: """Searches google using the provided query term and downloads the images in a folder. Args: query : The image search term to be provided by the user. Defaults to "dhaka". image_numbers : [description]. Defaults to 5. Returns: The number of images successfully downloaded. # Comment out slow (4.20s call) doctests # >>> download_images_from_google_query() 5 # >>> download_images_from_google_query("potato") 5 """ max_images = min(max_images, 50) # Prevent abuse! params = { "q": query, "tbm": "isch", "hl": "en", "ijn": "0", } html = requests.get("https://www.google.com/search", params=params, headers=headers) soup = BeautifulSoup(html.text, "html.parser") matched_images_data = "".join( re.findall(r"AF_initDataCallback\(([^<]+)\);", str(soup.select("script"))) ) matched_images_data_fix = json.dumps(matched_images_data) matched_images_data_json = json.loads(matched_images_data_fix) matched_google_image_data = re.findall( r"\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",", matched_images_data_json, ) if not matched_google_image_data: return 0 removed_matched_google_images_thumbnails = re.sub( r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]", "", str(matched_google_image_data), ) matched_google_full_resolution_images = re.findall( r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]", removed_matched_google_images_thumbnails, ) for index, fixed_full_res_image in enumerate(matched_google_full_resolution_images): if index >= max_images: return index original_size_img_not_fixed = bytes(fixed_full_res_image, "ascii").decode( "unicode-escape" ) original_size_img = bytes(original_size_img_not_fixed, "ascii").decode( "unicode-escape" ) opener = urllib.request.build_opener() opener.addheaders = [ ( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582", ) ] urllib.request.install_opener(opener) path_name = f"query_{query.replace(' ', '_')}" if not os.path.exists(path_name): os.makedirs(path_name) urllib.request.urlretrieve( original_size_img, f"{path_name}/original_size_img_{index}.jpg" ) return index if __name__ == "__main__": try: image_count = download_images_from_google_query(sys.argv[1]) print(f"{image_count} images were downloaded to disk.") except IndexError: print("Please provide a search term.") raise
import json import os import re import sys import urllib.request import requests from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } def download_images_from_google_query(query: str = "dhaka", max_images: int = 5) -> int: """ Searches google using the provided query term and downloads the images in a folder. Args: query : The image search term to be provided by the user. Defaults to "dhaka". image_numbers : [description]. Defaults to 5. Returns: The number of images successfully downloaded. # Comment out slow (4.20s call) doctests # >>> download_images_from_google_query() 5 # >>> download_images_from_google_query("potato") 5 """ max_images = min(max_images, 50) # Prevent abuse! params = { "q": query, "tbm": "isch", "hl": "en", "ijn": "0", } html = requests.get("https://www.google.com/search", params=params, headers=headers) soup = BeautifulSoup(html.text, "html.parser") matched_images_data = "".join( re.findall(r"AF_initDataCallback\(([^<]+)\);", str(soup.select("script"))) ) matched_images_data_fix = json.dumps(matched_images_data) matched_images_data_json = json.loads(matched_images_data_fix) matched_google_image_data = re.findall( r"\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",", matched_images_data_json, ) if not matched_google_image_data: return 0 removed_matched_google_images_thumbnails = re.sub( r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]", "", str(matched_google_image_data), ) matched_google_full_resolution_images = re.findall( r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]", removed_matched_google_images_thumbnails, ) for index, fixed_full_res_image in enumerate(matched_google_full_resolution_images): if index >= max_images: return index original_size_img_not_fixed = bytes(fixed_full_res_image, "ascii").decode( "unicode-escape" ) original_size_img = bytes(original_size_img_not_fixed, "ascii").decode( "unicode-escape" ) opener = urllib.request.build_opener() opener.addheaders = [ ( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582", ) ] urllib.request.install_opener(opener) path_name = f"query_{query.replace(' ', '_')}" if not os.path.exists(path_name): os.makedirs(path_name) urllib.request.urlretrieve( original_size_img, f"{path_name}/original_size_img_{index}.jpg" ) return index if __name__ == "__main__": try: image_count = download_images_from_google_query(sys.argv[1]) print(f"{image_count} images were downloaded to disk.") except IndexError: print("Please provide a search term.") raise
1
TheAlgorithms/Python
6,629
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2022-10-03T19:21:25Z"
"2022-10-03T20:00:46Z"
e9862adafce9eb682cabcf8ac502893e0272ae65
756bb268eb22199534fc8d6478cf0e006f02b56b
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) <!--pre-commit.ci end-->
""" The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ from collections.abc import Generator def fibonacci_generator() -> Generator[int, None, None]: """ A generator that produces numbers in the Fibonacci sequence >>> generator = fibonacci_generator() >>> next(generator) 1 >>> next(generator) 2 >>> next(generator) 3 >>> next(generator) 5 >>> next(generator) 8 """ a, b = 0, 1 while True: a, b = b, a + b yield b def solution(n: int = 1000) -> int: """Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ answer = 1 gen = fibonacci_generator() while len(str(next(gen))) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
""" The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ from collections.abc import Generator def fibonacci_generator() -> Generator[int, None, None]: """ A generator that produces numbers in the Fibonacci sequence >>> generator = fibonacci_generator() >>> next(generator) 1 >>> next(generator) 2 >>> next(generator) 3 >>> next(generator) 5 >>> next(generator) 8 """ a, b = 0, 1 while True: a, b = b, a + b yield b def solution(n: int = 1000) -> int: """Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ answer = 1 gen = fibonacci_generator() while len(str(next(gen))) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
-1