repo_name
stringclasses
1 value
pr_number
int64
4.12k
11.2k
pr_title
stringlengths
9
107
pr_description
stringlengths
107
5.48k
author
stringlengths
4
18
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
118
5.52k
before_content
stringlengths
0
7.93M
after_content
stringlengths
0
7.93M
label
int64
-1
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Best-first_search#Greedy_BFS """ from __future__ import annotations Path = list[tuple[int, int]] grid = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] delta = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class Node: """ >>> k = Node(0, 0, 4, 5, 0, None) >>> k.calculate_heuristic() 9 >>> n = Node(1, 4, 3, 4, 2, None) >>> n.calculate_heuristic() 2 >>> l = [k, n] >>> n == l[0] False >>> l.sort() >>> n == l[0] True """ def __init__( self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, g_cost: float, parent: Node | None, ): self.pos_x = pos_x self.pos_y = pos_y self.pos = (pos_y, pos_x) self.goal_x = goal_x self.goal_y = goal_y self.g_cost = g_cost self.parent = parent self.f_cost = self.calculate_heuristic() def calculate_heuristic(self) -> float: """ The heuristic here is the Manhattan Distance Could elaborate to offer more than one choice """ dy = abs(self.pos_x - self.goal_x) dx = abs(self.pos_y - self.goal_y) return dx + dy def __lt__(self, other) -> bool: return self.f_cost < other.f_cost class GreedyBestFirst: """ >>> gbf = GreedyBestFirst((0, 0), (len(grid) - 1, len(grid[0]) - 1)) >>> [x.pos for x in gbf.get_successors(gbf.start)] [(1, 0), (0, 1)] >>> (gbf.start.pos_y + delta[3][0], gbf.start.pos_x + delta[3][1]) (0, 1) >>> (gbf.start.pos_y + delta[2][0], gbf.start.pos_x + delta[2][1]) (1, 0) >>> gbf.retrace_path(gbf.start) [(0, 0)] >>> gbf.search() # doctest: +NORMALIZE_WHITESPACE [(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 1), (5, 1), (6, 1), (6, 2), (6, 3), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)] """ def __init__(self, start: tuple[int, int], goal: tuple[int, int]): self.start = Node(start[1], start[0], goal[1], goal[0], 0, None) self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None) self.open_nodes = [self.start] self.closed_nodes: list[Node] = [] self.reached = False def search(self) -> Path | None: """ Search for the path, if a path is not found, only the starting position is returned """ while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() current_node = self.open_nodes.pop(0) if current_node.pos == self.target.pos: self.reached = True return self.retrace_path(current_node) self.closed_nodes.append(current_node) successors = self.get_successors(current_node) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(child_node) else: # retrieve the best current path better_node = self.open_nodes.pop(self.open_nodes.index(child_node)) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(child_node) else: self.open_nodes.append(better_node) if not self.reached: return [self.start.pos] return None def get_successors(self, parent: Node) -> list[Node]: """ Returns a list of successors (both in the grid and free spaces) """ successors = [] for action in delta: pos_x = parent.pos_x + action[1] pos_y = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( pos_x, pos_y, self.target.pos_y, self.target.pos_x, parent.g_cost + 1, parent, ) ) return successors def retrace_path(self, node: Node | None) -> Path: """ Retrace the path from parents to parents until start node """ current_node = node path = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) current_node = current_node.parent path.reverse() return path if __name__ == "__main__": init = (0, 0) goal = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print("------") greedy_bf = GreedyBestFirst(init, goal) path = greedy_bf.search() if path: for pos_x, pos_y in path: grid[pos_x][pos_y] = 2 for elem in grid: print(elem)
""" https://en.wikipedia.org/wiki/Best-first_search#Greedy_BFS """ from __future__ import annotations Path = list[tuple[int, int]] grid = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] delta = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class Node: """ >>> k = Node(0, 0, 4, 5, 0, None) >>> k.calculate_heuristic() 9 >>> n = Node(1, 4, 3, 4, 2, None) >>> n.calculate_heuristic() 2 >>> l = [k, n] >>> n == l[0] False >>> l.sort() >>> n == l[0] True """ def __init__( self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, g_cost: float, parent: Node | None, ): self.pos_x = pos_x self.pos_y = pos_y self.pos = (pos_y, pos_x) self.goal_x = goal_x self.goal_y = goal_y self.g_cost = g_cost self.parent = parent self.f_cost = self.calculate_heuristic() def calculate_heuristic(self) -> float: """ The heuristic here is the Manhattan Distance Could elaborate to offer more than one choice """ dy = abs(self.pos_x - self.goal_x) dx = abs(self.pos_y - self.goal_y) return dx + dy def __lt__(self, other) -> bool: return self.f_cost < other.f_cost class GreedyBestFirst: """ >>> gbf = GreedyBestFirst((0, 0), (len(grid) - 1, len(grid[0]) - 1)) >>> [x.pos for x in gbf.get_successors(gbf.start)] [(1, 0), (0, 1)] >>> (gbf.start.pos_y + delta[3][0], gbf.start.pos_x + delta[3][1]) (0, 1) >>> (gbf.start.pos_y + delta[2][0], gbf.start.pos_x + delta[2][1]) (1, 0) >>> gbf.retrace_path(gbf.start) [(0, 0)] >>> gbf.search() # doctest: +NORMALIZE_WHITESPACE [(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 1), (5, 1), (6, 1), (6, 2), (6, 3), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)] """ def __init__(self, start: tuple[int, int], goal: tuple[int, int]): self.start = Node(start[1], start[0], goal[1], goal[0], 0, None) self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None) self.open_nodes = [self.start] self.closed_nodes: list[Node] = [] self.reached = False def search(self) -> Path | None: """ Search for the path, if a path is not found, only the starting position is returned """ while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() current_node = self.open_nodes.pop(0) if current_node.pos == self.target.pos: self.reached = True return self.retrace_path(current_node) self.closed_nodes.append(current_node) successors = self.get_successors(current_node) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(child_node) else: # retrieve the best current path better_node = self.open_nodes.pop(self.open_nodes.index(child_node)) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(child_node) else: self.open_nodes.append(better_node) if not self.reached: return [self.start.pos] return None def get_successors(self, parent: Node) -> list[Node]: """ Returns a list of successors (both in the grid and free spaces) """ successors = [] for action in delta: pos_x = parent.pos_x + action[1] pos_y = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( pos_x, pos_y, self.target.pos_y, self.target.pos_x, parent.g_cost + 1, parent, ) ) return successors def retrace_path(self, node: Node | None) -> Path: """ Retrace the path from parents to parents until start node """ current_node = node path = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) current_node = current_node.parent path.reverse() return path if __name__ == "__main__": init = (0, 0) goal = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print("------") greedy_bf = GreedyBestFirst(init, goal) path = greedy_bf.search() if path: for pos_x, pos_y in path: grid[pos_x][pos_y] = 2 for elem in grid: print(elem)
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 64: https://projecteuler.net/problem=64 All square roots are periodic when written as continued fractions. For example, let us consider sqrt(23). It can be seen that the sequence is repeating. For conciseness, we use the notation sqrt(23)=[4;(1,3,1,8)], to indicate that the block (1,3,1,8) repeats indefinitely. Exactly four continued fractions, for N<=13, have an odd period. How many continued fractions for N<=10000 have an odd period? References: - https://en.wikipedia.org/wiki/Continued_fraction """ from math import floor, sqrt def continuous_fraction_period(n: int) -> int: """ Returns the continued fraction period of a number n. >>> continuous_fraction_period(2) 1 >>> continuous_fraction_period(5) 1 >>> continuous_fraction_period(7) 4 >>> continuous_fraction_period(11) 2 >>> continuous_fraction_period(13) 5 """ numerator = 0.0 denominator = 1.0 ROOT = int(sqrt(n)) integer_part = ROOT period = 0 while integer_part != 2 * ROOT: numerator = denominator * integer_part - numerator denominator = (n - numerator**2) / denominator integer_part = int((ROOT + numerator) / denominator) period += 1 return period def solution(n: int = 10000) -> int: """ Returns the count of numbers <= 10000 with odd periods. This function calls continuous_fraction_period for numbers which are not perfect squares. This is checked in if sr - floor(sr) != 0 statement. If an odd period is returned by continuous_fraction_period, count_odd_periods is increased by 1. >>> solution(2) 1 >>> solution(5) 2 >>> solution(7) 2 >>> solution(11) 3 >>> solution(13) 4 """ count_odd_periods = 0 for i in range(2, n + 1): sr = sqrt(i) if sr - floor(sr) != 0: if continuous_fraction_period(i) % 2 == 1: count_odd_periods += 1 return count_odd_periods if __name__ == "__main__": print(f"{solution(int(input().strip()))}")
""" Project Euler Problem 64: https://projecteuler.net/problem=64 All square roots are periodic when written as continued fractions. For example, let us consider sqrt(23). It can be seen that the sequence is repeating. For conciseness, we use the notation sqrt(23)=[4;(1,3,1,8)], to indicate that the block (1,3,1,8) repeats indefinitely. Exactly four continued fractions, for N<=13, have an odd period. How many continued fractions for N<=10000 have an odd period? References: - https://en.wikipedia.org/wiki/Continued_fraction """ from math import floor, sqrt def continuous_fraction_period(n: int) -> int: """ Returns the continued fraction period of a number n. >>> continuous_fraction_period(2) 1 >>> continuous_fraction_period(5) 1 >>> continuous_fraction_period(7) 4 >>> continuous_fraction_period(11) 2 >>> continuous_fraction_period(13) 5 """ numerator = 0.0 denominator = 1.0 ROOT = int(sqrt(n)) integer_part = ROOT period = 0 while integer_part != 2 * ROOT: numerator = denominator * integer_part - numerator denominator = (n - numerator**2) / denominator integer_part = int((ROOT + numerator) / denominator) period += 1 return period def solution(n: int = 10000) -> int: """ Returns the count of numbers <= 10000 with odd periods. This function calls continuous_fraction_period for numbers which are not perfect squares. This is checked in if sr - floor(sr) != 0 statement. If an odd period is returned by continuous_fraction_period, count_odd_periods is increased by 1. >>> solution(2) 1 >>> solution(5) 2 >>> solution(7) 2 >>> solution(11) 3 >>> solution(13) 4 """ count_odd_periods = 0 for i in range(2, n + 1): sr = sqrt(i) if sr - floor(sr) != 0: if continuous_fraction_period(i) % 2 == 1: count_odd_periods += 1 return count_odd_periods if __name__ == "__main__": print(f"{solution(int(input().strip()))}")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Changing contrast with PIL This algorithm is used in https://noivce.pythonanywhere.com/ Python web app. python/black: True flake8 : True """ from PIL import Image def change_contrast(img: Image, level: int) -> Image: """ Function to change contrast """ factor = (259 * (level + 255)) / (255 * (259 - level)) def contrast(c: int) -> int: """ Fundamental Transformation/Operation that'll be performed on every bit. """ return int(128 + factor * (c - 128)) return img.point(contrast) if __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change contrast to 170 cont_img = change_contrast(img, 170) cont_img.save("image_data/lena_high_contrast.png", format="png")
""" Changing contrast with PIL This algorithm is used in https://noivce.pythonanywhere.com/ Python web app. python/black: True flake8 : True """ from PIL import Image def change_contrast(img: Image, level: int) -> Image: """ Function to change contrast """ factor = (259 * (level + 255)) / (255 * (259 - level)) def contrast(c: int) -> int: """ Fundamental Transformation/Operation that'll be performed on every bit. """ return int(128 + factor * (c - 128)) return img.point(contrast) if __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change contrast to 170 cont_img = change_contrast(img, 170) cont_img.save("image_data/lena_high_contrast.png", format="png")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? """ import os # Precomputes a list of the 100 first triangular numbers TRIANGULAR_NUMBERS = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def solution(): """ Finds the amount of triangular words in the words file. >>> solution() 162 """ script_dir = os.path.dirname(os.path.realpath(__file__)) wordsFilePath = os.path.join(script_dir, "words.txt") words = "" with open(wordsFilePath) as f: words = f.readline() words = list(map(lambda word: word.strip('"'), words.strip("\r\n").split(","))) words = list( filter( lambda word: word in TRIANGULAR_NUMBERS, map(lambda word: sum(map(lambda x: ord(x) - 64, word)), words), ) ) return len(words) if __name__ == "__main__": print(solution())
""" The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? """ import os # Precomputes a list of the 100 first triangular numbers TRIANGULAR_NUMBERS = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def solution(): """ Finds the amount of triangular words in the words file. >>> solution() 162 """ script_dir = os.path.dirname(os.path.realpath(__file__)) wordsFilePath = os.path.join(script_dir, "words.txt") words = "" with open(wordsFilePath) as f: words = f.readline() words = list(map(lambda word: word.strip('"'), words.strip("\r\n").split(","))) words = list( filter( lambda word: word in TRIANGULAR_NUMBERS, map(lambda word: sum(map(lambda x: ord(x) - 64, word)), words), ) ) return len(words) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from typing import Generic, TypeVar T = TypeVar("T") class StackOverflowError(BaseException): pass class StackUnderflowError(BaseException): pass class Stack(Generic[T]): """A stack is an abstract data type that serves as a collection of elements with two principal operations: push() and pop(). push() adds an element to the top of the stack, and pop() removes an element from the top of a stack. The order in which elements come off of a stack are Last In, First Out (LIFO). https://en.wikipedia.org/wiki/Stack_(abstract_data_type) """ def __init__(self, limit: int = 10): self.stack: list[T] = [] self.limit = limit def __bool__(self) -> bool: return bool(self.stack) def __str__(self) -> str: return str(self.stack) def push(self, data: T) -> None: """Push an element to the top of the stack.""" if len(self.stack) >= self.limit: raise StackOverflowError self.stack.append(data) def pop(self) -> T: """ Pop an element off of the top of the stack. >>> Stack().pop() Traceback (most recent call last): ... data_structures.stacks.stack.StackUnderflowError """ if not self.stack: raise StackUnderflowError return self.stack.pop() def peek(self) -> T: """ Peek at the top-most element of the stack. >>> Stack().pop() Traceback (most recent call last): ... data_structures.stacks.stack.StackUnderflowError """ if not self.stack: raise StackUnderflowError return self.stack[-1] def is_empty(self) -> bool: """Check if a stack is empty.""" return not bool(self.stack) def is_full(self) -> bool: return self.size() == self.limit def size(self) -> int: """Return the size of the stack.""" return len(self.stack) def __contains__(self, item: T) -> bool: """Check if item is in stack""" return item in self.stack def test_stack() -> None: """ >>> test_stack() """ stack: Stack[int] = Stack(10) assert bool(stack) is False assert stack.is_empty() is True assert stack.is_full() is False assert str(stack) == "[]" try: _ = stack.pop() assert False # This should not happen except StackUnderflowError: assert True # This should happen try: _ = stack.peek() assert False # This should not happen except StackUnderflowError: assert True # This should happen for i in range(10): assert stack.size() == i stack.push(i) assert bool(stack) assert not stack.is_empty() assert stack.is_full() assert str(stack) == str(list(range(10))) assert stack.pop() == 9 assert stack.peek() == 8 stack.push(100) assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100]) try: stack.push(200) assert False # This should not happen except StackOverflowError: assert True # This should happen assert not stack.is_empty() assert stack.size() == 10 assert 5 in stack assert 55 not in stack if __name__ == "__main__": test_stack()
from __future__ import annotations from typing import Generic, TypeVar T = TypeVar("T") class StackOverflowError(BaseException): pass class StackUnderflowError(BaseException): pass class Stack(Generic[T]): """A stack is an abstract data type that serves as a collection of elements with two principal operations: push() and pop(). push() adds an element to the top of the stack, and pop() removes an element from the top of a stack. The order in which elements come off of a stack are Last In, First Out (LIFO). https://en.wikipedia.org/wiki/Stack_(abstract_data_type) """ def __init__(self, limit: int = 10): self.stack: list[T] = [] self.limit = limit def __bool__(self) -> bool: return bool(self.stack) def __str__(self) -> str: return str(self.stack) def push(self, data: T) -> None: """Push an element to the top of the stack.""" if len(self.stack) >= self.limit: raise StackOverflowError self.stack.append(data) def pop(self) -> T: """ Pop an element off of the top of the stack. >>> Stack().pop() Traceback (most recent call last): ... data_structures.stacks.stack.StackUnderflowError """ if not self.stack: raise StackUnderflowError return self.stack.pop() def peek(self) -> T: """ Peek at the top-most element of the stack. >>> Stack().pop() Traceback (most recent call last): ... data_structures.stacks.stack.StackUnderflowError """ if not self.stack: raise StackUnderflowError return self.stack[-1] def is_empty(self) -> bool: """Check if a stack is empty.""" return not bool(self.stack) def is_full(self) -> bool: return self.size() == self.limit def size(self) -> int: """Return the size of the stack.""" return len(self.stack) def __contains__(self, item: T) -> bool: """Check if item is in stack""" return item in self.stack def test_stack() -> None: """ >>> test_stack() """ stack: Stack[int] = Stack(10) assert bool(stack) is False assert stack.is_empty() is True assert stack.is_full() is False assert str(stack) == "[]" try: _ = stack.pop() assert False # This should not happen except StackUnderflowError: assert True # This should happen try: _ = stack.peek() assert False # This should not happen except StackUnderflowError: assert True # This should happen for i in range(10): assert stack.size() == i stack.push(i) assert bool(stack) assert not stack.is_empty() assert stack.is_full() assert str(stack) == str(list(range(10))) assert stack.pop() == 9 assert stack.peek() == 8 stack.push(100) assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100]) try: stack.push(200) assert False # This should not happen except StackOverflowError: assert True # This should happen assert not stack.is_empty() assert stack.size() == 10 assert 5 in stack assert 55 not in stack if __name__ == "__main__": test_stack()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" this is code for forecasting but i modified it and used it for safety checker of data for ex: you have a online shop and for some reason some data are missing (the amount of data that u expected are not supposed to be) then we can use it *ps : 1. ofc we can use normal statistic method but in this case the data is quite absurd and only a little^^ 2. ofc u can use this and modified it for forecasting purpose for the next 3 months sales or something, u can just adjust it for ur own purpose """ import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def linear_regression_prediction( train_dt: list, train_usr: list, train_mtch: list, test_dt: list, test_mtch: list ) -> float: """ First method: linear regression input : training data (date, total_user, total_event) in list of float output : list of total user prediction in float >>> n = linear_regression_prediction([2,3,4,5], [5,3,4,6], [3,1,2,4], [2,1], [2,2]) >>> abs(n - 5.0) < 1e-6 # Checking precision because of floating point errors True """ x = np.array([[1, item, train_mtch[i]] for i, item in enumerate(train_dt)]) y = np.array(train_usr) beta = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose(), x)), x.transpose()), y) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2]) def sarimax_predictor(train_user: list, train_match: list, test_match: list) -> float: """ second method: Sarimax sarimax is a statistic method which using previous input and learn its pattern to predict future data input : training data (total_user, with exog data = total_event) in list of float output : list of total user prediction in float >>> sarimax_predictor([4,2,6,8], [3,1,2,4], [2]) 6.6666671111109626 """ order = (1, 2, 1) seasonal_order = (1, 1, 0, 7) model = SARIMAX( train_user, exog=train_match, order=order, seasonal_order=seasonal_order ) model_fit = model.fit(disp=False, maxiter=600, method="nm") result = model_fit.predict(1, len(test_match), exog=[test_match]) return result[0] def support_vector_regressor(x_train: list, x_test: list, train_user: list) -> float: """ Third method: Support vector regressor svr is quite the same with svm(support vector machine) it uses the same principles as the SVM for classification, with only a few minor differences and the only different is that it suits better for regression purpose input : training data (date, total_user, total_event) in list of float where x = list of set (date and total event) output : list of total user prediction in float >>> support_vector_regressor([[5,2],[1,5],[6,2]], [[3,2]], [2,1,4]) 1.634932078116079 """ regressor = SVR(kernel="rbf", C=1, gamma=0.1, epsilon=0.1) regressor.fit(x_train, train_user) y_pred = regressor.predict(x_test) return y_pred[0] def interquartile_range_checker(train_user: list) -> float: """ Optional method: interquatile range input : list of total user in float output : low limit of input in float this method can be used to check whether some data is outlier or not >>> interquartile_range_checker([1,2,3,4,5,6,7,8,9,10]) 2.8 """ train_user.sort() q1 = np.percentile(train_user, 25) q3 = np.percentile(train_user, 75) iqr = q3 - q1 low_lim = q1 - (iqr * 0.1) return low_lim def data_safety_checker(list_vote: list, actual_result: float) -> None: """ Used to review all the votes (list result prediction) and compare it to the actual result. input : list of predictions output : print whether it's safe or not >>> data_safety_checker([2,3,4],5.0) Today's data is not safe. """ safe = 0 not_safe = 0 for i in list_vote: if i > actual_result: safe = not_safe + 1 else: if abs(abs(i) - abs(actual_result)) <= 0.1: safe = safe + 1 else: not_safe = not_safe + 1 print(f"Today's data is {'not ' if safe <= not_safe else ''}safe.") # data_input_df = pd.read_csv("ex_data.csv", header=None) data_input = [[18231, 0.0, 1], [22621, 1.0, 2], [15675, 0.0, 3], [23583, 1.0, 4]] data_input_df = pd.DataFrame(data_input, columns=["total_user", "total_even", "days"]) """ data column = total user in a day, how much online event held in one day, what day is that(sunday-saturday) """ # start normalization normalize_df = Normalizer().fit_transform(data_input_df.values) # split data total_date = normalize_df[:, 2].tolist() total_user = normalize_df[:, 0].tolist() total_match = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) x = normalize_df[:, [1, 2]].tolist() x_train = x[: len(x) - 1] x_test = x[len(x) - 1 :] # for linear reression & sarimax trn_date = total_date[: len(total_date) - 1] trn_user = total_user[: len(total_user) - 1] trn_match = total_match[: len(total_match) - 1] tst_date = total_date[len(total_date) - 1 :] tst_user = total_user[len(total_user) - 1 :] tst_match = total_match[len(total_match) - 1 :] # voting system with forecasting res_vote = [] res_vote.append( linear_regression_prediction(trn_date, trn_user, trn_match, tst_date, tst_match) ) res_vote.append(sarimax_predictor(trn_user, trn_match, tst_match)) res_vote.append(support_vector_regressor(x_train, x_test, trn_user)) # check the safety of todays'data^^ data_safety_checker(res_vote, tst_user)
""" this is code for forecasting but i modified it and used it for safety checker of data for ex: you have a online shop and for some reason some data are missing (the amount of data that u expected are not supposed to be) then we can use it *ps : 1. ofc we can use normal statistic method but in this case the data is quite absurd and only a little^^ 2. ofc u can use this and modified it for forecasting purpose for the next 3 months sales or something, u can just adjust it for ur own purpose """ import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def linear_regression_prediction( train_dt: list, train_usr: list, train_mtch: list, test_dt: list, test_mtch: list ) -> float: """ First method: linear regression input : training data (date, total_user, total_event) in list of float output : list of total user prediction in float >>> n = linear_regression_prediction([2,3,4,5], [5,3,4,6], [3,1,2,4], [2,1], [2,2]) >>> abs(n - 5.0) < 1e-6 # Checking precision because of floating point errors True """ x = np.array([[1, item, train_mtch[i]] for i, item in enumerate(train_dt)]) y = np.array(train_usr) beta = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose(), x)), x.transpose()), y) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2]) def sarimax_predictor(train_user: list, train_match: list, test_match: list) -> float: """ second method: Sarimax sarimax is a statistic method which using previous input and learn its pattern to predict future data input : training data (total_user, with exog data = total_event) in list of float output : list of total user prediction in float >>> sarimax_predictor([4,2,6,8], [3,1,2,4], [2]) 6.6666671111109626 """ order = (1, 2, 1) seasonal_order = (1, 1, 0, 7) model = SARIMAX( train_user, exog=train_match, order=order, seasonal_order=seasonal_order ) model_fit = model.fit(disp=False, maxiter=600, method="nm") result = model_fit.predict(1, len(test_match), exog=[test_match]) return result[0] def support_vector_regressor(x_train: list, x_test: list, train_user: list) -> float: """ Third method: Support vector regressor svr is quite the same with svm(support vector machine) it uses the same principles as the SVM for classification, with only a few minor differences and the only different is that it suits better for regression purpose input : training data (date, total_user, total_event) in list of float where x = list of set (date and total event) output : list of total user prediction in float >>> support_vector_regressor([[5,2],[1,5],[6,2]], [[3,2]], [2,1,4]) 1.634932078116079 """ regressor = SVR(kernel="rbf", C=1, gamma=0.1, epsilon=0.1) regressor.fit(x_train, train_user) y_pred = regressor.predict(x_test) return y_pred[0] def interquartile_range_checker(train_user: list) -> float: """ Optional method: interquatile range input : list of total user in float output : low limit of input in float this method can be used to check whether some data is outlier or not >>> interquartile_range_checker([1,2,3,4,5,6,7,8,9,10]) 2.8 """ train_user.sort() q1 = np.percentile(train_user, 25) q3 = np.percentile(train_user, 75) iqr = q3 - q1 low_lim = q1 - (iqr * 0.1) return low_lim def data_safety_checker(list_vote: list, actual_result: float) -> None: """ Used to review all the votes (list result prediction) and compare it to the actual result. input : list of predictions output : print whether it's safe or not >>> data_safety_checker([2,3,4],5.0) Today's data is not safe. """ safe = 0 not_safe = 0 for i in list_vote: if i > actual_result: safe = not_safe + 1 else: if abs(abs(i) - abs(actual_result)) <= 0.1: safe = safe + 1 else: not_safe = not_safe + 1 print(f"Today's data is {'not ' if safe <= not_safe else ''}safe.") # data_input_df = pd.read_csv("ex_data.csv", header=None) data_input = [[18231, 0.0, 1], [22621, 1.0, 2], [15675, 0.0, 3], [23583, 1.0, 4]] data_input_df = pd.DataFrame(data_input, columns=["total_user", "total_even", "days"]) """ data column = total user in a day, how much online event held in one day, what day is that(sunday-saturday) """ # start normalization normalize_df = Normalizer().fit_transform(data_input_df.values) # split data total_date = normalize_df[:, 2].tolist() total_user = normalize_df[:, 0].tolist() total_match = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) x = normalize_df[:, [1, 2]].tolist() x_train = x[: len(x) - 1] x_test = x[len(x) - 1 :] # for linear reression & sarimax trn_date = total_date[: len(total_date) - 1] trn_user = total_user[: len(total_user) - 1] trn_match = total_match[: len(total_match) - 1] tst_date = total_date[len(total_date) - 1 :] tst_user = total_user[len(total_user) - 1 :] tst_match = total_match[len(total_match) - 1 :] # voting system with forecasting res_vote = [] res_vote.append( linear_regression_prediction(trn_date, trn_user, trn_match, tst_date, tst_match) ) res_vote.append(sarimax_predictor(trn_user, trn_match, tst_match)) res_vote.append(support_vector_regressor(x_train, x_test, trn_user)) # check the safety of todays'data^^ data_safety_checker(res_vote, tst_user)
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from math import asin, atan, cos, radians, sin, sqrt, tan def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """ Calculate great circle distance between two points in a sphere, given longitudes and latitudes https://en.wikipedia.org/wiki/Haversine_formula We know that the globe is "sort of" spherical, so a path between two points isn't exactly a straight line. We need to account for the Earth's curvature when calculating distance from point A to B. This effect is negligible for small distances but adds up as distance increases. The Haversine method treats the earth as a sphere which allows us to "project" the two points A and B onto the surface of that sphere and approximate the spherical distance between them. Since the Earth is not a perfect sphere, other methods which model the Earth's ellipsoidal nature are more accurate but a quick and modifiable computation like Haversine can be handy for shorter range distances. Args: lat1, lon1: latitude and longitude of coordinate 1 lat2, lon2: latitude and longitude of coordinate 2 Returns: geographical distance between two points in metres >>> from collections import namedtuple >>> point_2d = namedtuple("point_2d", "lat lon") >>> SAN_FRANCISCO = point_2d(37.774856, -122.424227) >>> YOSEMITE = point_2d(37.864742, -119.537521) >>> f"{haversine_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters" '254,352 meters' """ # CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System # Distance in metres(m) AXIS_A = 6378137.0 AXIS_B = 6356752.314245 RADIUS = 6378137 # Equation parameters # Equation https://en.wikipedia.org/wiki/Haversine_formula#Formulation flattening = (AXIS_A - AXIS_B) / AXIS_A phi_1 = atan((1 - flattening) * tan(radians(lat1))) phi_2 = atan((1 - flattening) * tan(radians(lat2))) lambda_1 = radians(lon1) lambda_2 = radians(lon2) # Equation sin_sq_phi = sin((phi_2 - phi_1) / 2) sin_sq_lambda = sin((lambda_2 - lambda_1) / 2) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda h_value = sqrt(sin_sq_phi + (cos(phi_1) * cos(phi_2) * sin_sq_lambda)) return 2 * RADIUS * asin(h_value) if __name__ == "__main__": import doctest doctest.testmod()
from math import asin, atan, cos, radians, sin, sqrt, tan def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """ Calculate great circle distance between two points in a sphere, given longitudes and latitudes https://en.wikipedia.org/wiki/Haversine_formula We know that the globe is "sort of" spherical, so a path between two points isn't exactly a straight line. We need to account for the Earth's curvature when calculating distance from point A to B. This effect is negligible for small distances but adds up as distance increases. The Haversine method treats the earth as a sphere which allows us to "project" the two points A and B onto the surface of that sphere and approximate the spherical distance between them. Since the Earth is not a perfect sphere, other methods which model the Earth's ellipsoidal nature are more accurate but a quick and modifiable computation like Haversine can be handy for shorter range distances. Args: lat1, lon1: latitude and longitude of coordinate 1 lat2, lon2: latitude and longitude of coordinate 2 Returns: geographical distance between two points in metres >>> from collections import namedtuple >>> point_2d = namedtuple("point_2d", "lat lon") >>> SAN_FRANCISCO = point_2d(37.774856, -122.424227) >>> YOSEMITE = point_2d(37.864742, -119.537521) >>> f"{haversine_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters" '254,352 meters' """ # CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System # Distance in metres(m) AXIS_A = 6378137.0 AXIS_B = 6356752.314245 RADIUS = 6378137 # Equation parameters # Equation https://en.wikipedia.org/wiki/Haversine_formula#Formulation flattening = (AXIS_A - AXIS_B) / AXIS_A phi_1 = atan((1 - flattening) * tan(radians(lat1))) phi_2 = atan((1 - flattening) * tan(radians(lat2))) lambda_1 = radians(lon1) lambda_2 = radians(lon2) # Equation sin_sq_phi = sin((phi_2 - phi_1) / 2) sin_sq_lambda = sin((lambda_2 - lambda_1) / 2) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda h_value = sqrt(sin_sq_phi + (cos(phi_1) * cos(phi_2) * sin_sq_lambda)) return 2 * RADIUS * asin(h_value) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A hexagonal number sequence is a sequence of figurate numbers where the nth hexagonal number hₙ is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots, when the hexagons are overlaid so that they share one vertex. Calculates the hexagonal numbers sequence with a formula hₙ = n(2n-1) where: hₙ --> is nth element of the sequence n --> is the number of element in the sequence reference-->"Hexagonal number" Wikipedia <https://en.wikipedia.org/wiki/Hexagonal_number> """ def hexagonal_numbers(length: int) -> list[int]: """ :param len: max number of elements :type len: int :return: Hexagonal numbers as a list Tests: >>> hexagonal_numbers(10) [0, 1, 6, 15, 28, 45, 66, 91, 120, 153] >>> hexagonal_numbers(5) [0, 1, 6, 15, 28] >>> hexagonal_numbers(0) Traceback (most recent call last): ... ValueError: Length must be a positive integer. """ if length <= 0 or not isinstance(length, int): raise ValueError("Length must be a positive integer.") return [n * (2 * n - 1) for n in range(length)] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
""" A hexagonal number sequence is a sequence of figurate numbers where the nth hexagonal number hₙ is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots, when the hexagons are overlaid so that they share one vertex. Calculates the hexagonal numbers sequence with a formula hₙ = n(2n-1) where: hₙ --> is nth element of the sequence n --> is the number of element in the sequence reference-->"Hexagonal number" Wikipedia <https://en.wikipedia.org/wiki/Hexagonal_number> """ def hexagonal_numbers(length: int) -> list[int]: """ :param len: max number of elements :type len: int :return: Hexagonal numbers as a list Tests: >>> hexagonal_numbers(10) [0, 1, 6, 15, 28, 45, 66, 91, 120, 153] >>> hexagonal_numbers(5) [0, 1, 6, 15, 28] >>> hexagonal_numbers(0) Traceback (most recent call last): ... ValueError: Length must be a positive integer. """ if length <= 0 or not isinstance(length, int): raise ValueError("Length must be a positive integer.") return [n * (2 * n - 1) for n in range(length)] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from collections import deque def _input(message): return input(message).strip().split(" ") def initialize_unweighted_directed_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) return graph def initialize_unweighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) graph[y].append(x) return graph def initialize_weighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[tuple[int, int]]]: graph: dict[int, list[tuple[int, int]]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y, w = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> <weight> ")) graph[x].append((y, w)) graph[y].append((x, w)) return graph if __name__ == "__main__": n, m = (int(i) for i in _input("Number of nodes and edges: ")) graph_choice = int( _input( "Press 1 or 2 or 3 \n" "1. Unweighted directed \n" "2. Unweighted undirected \n" "3. Weighted undirected \n" )[0] ) g = { 1: initialize_unweighted_directed_graph, 2: initialize_unweighted_undirected_graph, 3: initialize_weighted_undirected_graph, }[graph_choice](n, m) """ -------------------------------------------------------------------------------- Depth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes S - Traversal Stack -------------------------------------------------------------------------------- """ def dfs(G, s): vis, S = {s}, [s] print(s) while S: flag = 0 for i in G[S[-1]]: if i not in vis: S.append(i) vis.add(i) flag = 1 print(i) break if not flag: S.pop() """ -------------------------------------------------------------------------------- Breadth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes Q - Traversal Stack -------------------------------------------------------------------------------- """ def bfs(G, s): vis, Q = {s}, deque([s]) print(s) while Q: u = Q.popleft() for v in G[u]: if v not in vis: vis.add(v) Q.append(v) print(v) """ -------------------------------------------------------------------------------- Dijkstra's shortest path Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def dijk(G, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(G) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in G[u]: if v[0] not in known: if dist[u] + v[1] < dist.get(v[0], 100000): dist[v[0]] = dist[u] + v[1] path[v[0]] = u for i in dist: if i != s: print(dist[i]) """ -------------------------------------------------------------------------------- Topological Sort -------------------------------------------------------------------------------- """ def topo(G, ind=None, Q=None): if Q is None: Q = [1] if ind is None: ind = [0] * (len(G) + 1) # SInce oth Index is ignored for u in G: for v in G[u]: ind[v] += 1 Q = deque() for i in G: if ind[i] == 0: Q.append(i) if len(Q) == 0: return v = Q.popleft() print(v) for w in G[v]: ind[w] -= 1 if ind[w] == 0: Q.append(w) topo(G, ind, Q) """ -------------------------------------------------------------------------------- Reading an Adjacency matrix -------------------------------------------------------------------------------- """ def adjm(): n = input().strip() a = [] for i in range(n): a.append(map(int, input().strip().split())) return a, n """ -------------------------------------------------------------------------------- Floyd Warshall's algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def floy(A_and_n): (A, n) = A_and_n dist = list(A) path = [[0] * n for i in range(n)] for k in range(n): for i in range(n): for j in range(n): if dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] path[i][k] = k print(dist) """ -------------------------------------------------------------------------------- Prim's MST Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to nearest node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def prim(G, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(G) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in G[u]: if v[0] not in known: if v[1] < dist.get(v[0], 100000): dist[v[0]] = v[1] path[v[0]] = u return dist """ -------------------------------------------------------------------------------- Accepting Edge list Vars : n - Number of nodes m - Number of edges Returns : l - Edge list n - Number of Nodes -------------------------------------------------------------------------------- """ def edglist(): n, m = map(int, input().split(" ")) edges = [] for i in range(m): edges.append(map(int, input().split(" "))) return edges, n """ -------------------------------------------------------------------------------- Kruskal's MST Algorithm Args : E - Edge list n - Number of Nodes Vars : s - Set of all nodes as unique disjoint sets (initially) -------------------------------------------------------------------------------- """ def krusk(E_and_n): # Sort edges on the basis of distance (E, n) = E_and_n E.sort(reverse=True, key=lambda x: x[2]) s = [{i} for i in range(1, n + 1)] while True: if len(s) == 1: break print(s) x = E.pop() for i in range(len(s)): if x[0] in s[i]: break for j in range(len(s)): if x[1] in s[j]: if i == j: break s[j].update(s[i]) s.pop(i) break # find the isolated node in the graph def find_isolated_nodes(graph): isolated = [] for node in graph: if not graph[node]: isolated.append(node) return isolated
from collections import deque def _input(message): return input(message).strip().split(" ") def initialize_unweighted_directed_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) return graph def initialize_unweighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) graph[y].append(x) return graph def initialize_weighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[tuple[int, int]]]: graph: dict[int, list[tuple[int, int]]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y, w = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> <weight> ")) graph[x].append((y, w)) graph[y].append((x, w)) return graph if __name__ == "__main__": n, m = (int(i) for i in _input("Number of nodes and edges: ")) graph_choice = int( _input( "Press 1 or 2 or 3 \n" "1. Unweighted directed \n" "2. Unweighted undirected \n" "3. Weighted undirected \n" )[0] ) g = { 1: initialize_unweighted_directed_graph, 2: initialize_unweighted_undirected_graph, 3: initialize_weighted_undirected_graph, }[graph_choice](n, m) """ -------------------------------------------------------------------------------- Depth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes S - Traversal Stack -------------------------------------------------------------------------------- """ def dfs(G, s): vis, S = {s}, [s] print(s) while S: flag = 0 for i in G[S[-1]]: if i not in vis: S.append(i) vis.add(i) flag = 1 print(i) break if not flag: S.pop() """ -------------------------------------------------------------------------------- Breadth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes Q - Traversal Stack -------------------------------------------------------------------------------- """ def bfs(G, s): vis, Q = {s}, deque([s]) print(s) while Q: u = Q.popleft() for v in G[u]: if v not in vis: vis.add(v) Q.append(v) print(v) """ -------------------------------------------------------------------------------- Dijkstra's shortest path Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def dijk(G, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(G) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in G[u]: if v[0] not in known: if dist[u] + v[1] < dist.get(v[0], 100000): dist[v[0]] = dist[u] + v[1] path[v[0]] = u for i in dist: if i != s: print(dist[i]) """ -------------------------------------------------------------------------------- Topological Sort -------------------------------------------------------------------------------- """ def topo(G, ind=None, Q=None): if Q is None: Q = [1] if ind is None: ind = [0] * (len(G) + 1) # SInce oth Index is ignored for u in G: for v in G[u]: ind[v] += 1 Q = deque() for i in G: if ind[i] == 0: Q.append(i) if len(Q) == 0: return v = Q.popleft() print(v) for w in G[v]: ind[w] -= 1 if ind[w] == 0: Q.append(w) topo(G, ind, Q) """ -------------------------------------------------------------------------------- Reading an Adjacency matrix -------------------------------------------------------------------------------- """ def adjm(): n = input().strip() a = [] for i in range(n): a.append(map(int, input().strip().split())) return a, n """ -------------------------------------------------------------------------------- Floyd Warshall's algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def floy(A_and_n): (A, n) = A_and_n dist = list(A) path = [[0] * n for i in range(n)] for k in range(n): for i in range(n): for j in range(n): if dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] path[i][k] = k print(dist) """ -------------------------------------------------------------------------------- Prim's MST Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to nearest node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def prim(G, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(G) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in G[u]: if v[0] not in known: if v[1] < dist.get(v[0], 100000): dist[v[0]] = v[1] path[v[0]] = u return dist """ -------------------------------------------------------------------------------- Accepting Edge list Vars : n - Number of nodes m - Number of edges Returns : l - Edge list n - Number of Nodes -------------------------------------------------------------------------------- """ def edglist(): n, m = map(int, input().split(" ")) edges = [] for i in range(m): edges.append(map(int, input().split(" "))) return edges, n """ -------------------------------------------------------------------------------- Kruskal's MST Algorithm Args : E - Edge list n - Number of Nodes Vars : s - Set of all nodes as unique disjoint sets (initially) -------------------------------------------------------------------------------- """ def krusk(E_and_n): # Sort edges on the basis of distance (E, n) = E_and_n E.sort(reverse=True, key=lambda x: x[2]) s = [{i} for i in range(1, n + 1)] while True: if len(s) == 1: break print(s) x = E.pop() for i in range(len(s)): if x[0] in s[i]: break for j in range(len(s)): if x[1] in s[j]: if i == j: break s[j].update(s[i]) s.pop(i) break # find the isolated node in the graph def find_isolated_nodes(graph): isolated = [] for node in graph: if not graph[node]: isolated.append(node) return isolated
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Description : Newton's second law of motion pertains to the behavior of objects for which all existing forces are not balanced. The second law states that the acceleration of an object is dependent upon two variables - the net force acting upon the object and the mass of the object. The acceleration of an object depends directly upon the net force acting upon the object, and inversely upon the mass of the object. As the force acting upon an object is increased, the acceleration of the object is increased. As the mass of an object is increased, the acceleration of the object is decreased. Source: https://www.physicsclassroom.com/class/newtlaws/Lesson-3/Newton-s-Second-Law Formulation: Fnet = m • a Diagrammatic Explanation: Forces are unbalanced | | | V There is acceleration /\ / \ / \ / \ / \ / \ / \ __________________ ____ ________________ |The acceleration | |The acceleration | |depends directly | |depends inversely | |on the net Force | |upon the object's | |_________________| |mass_______________| Units: 1 Newton = 1 kg X meters / (seconds^2) How to use? Inputs: ___________________________________________________ |Name | Units | Type | |-------------|-------------------------|-----------| |mass | (in kgs) | float | |-------------|-------------------------|-----------| |acceleration | (in meters/(seconds^2)) | float | |_____________|_________________________|___________| Output: ___________________________________________________ |Name | Units | Type | |-------------|-------------------------|-----------| |force | (in Newtons) | float | |_____________|_________________________|___________| """ def newtons_second_law_of_motion(mass: float, acceleration: float) -> float: """ >>> newtons_second_law_of_motion(10, 10) 100 >>> newtons_second_law_of_motion(2.0, 1) 2.0 """ force = float() try: force = mass * acceleration except Exception: return -0.0 return force if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo mass = 12.5 acceleration = 10 force = newtons_second_law_of_motion(mass, acceleration) print("The force is ", force, "N")
""" Description : Newton's second law of motion pertains to the behavior of objects for which all existing forces are not balanced. The second law states that the acceleration of an object is dependent upon two variables - the net force acting upon the object and the mass of the object. The acceleration of an object depends directly upon the net force acting upon the object, and inversely upon the mass of the object. As the force acting upon an object is increased, the acceleration of the object is increased. As the mass of an object is increased, the acceleration of the object is decreased. Source: https://www.physicsclassroom.com/class/newtlaws/Lesson-3/Newton-s-Second-Law Formulation: Fnet = m • a Diagrammatic Explanation: Forces are unbalanced | | | V There is acceleration /\ / \ / \ / \ / \ / \ / \ __________________ ____ ________________ |The acceleration | |The acceleration | |depends directly | |depends inversely | |on the net Force | |upon the object's | |_________________| |mass_______________| Units: 1 Newton = 1 kg X meters / (seconds^2) How to use? Inputs: ___________________________________________________ |Name | Units | Type | |-------------|-------------------------|-----------| |mass | (in kgs) | float | |-------------|-------------------------|-----------| |acceleration | (in meters/(seconds^2)) | float | |_____________|_________________________|___________| Output: ___________________________________________________ |Name | Units | Type | |-------------|-------------------------|-----------| |force | (in Newtons) | float | |_____________|_________________________|___________| """ def newtons_second_law_of_motion(mass: float, acceleration: float) -> float: """ >>> newtons_second_law_of_motion(10, 10) 100 >>> newtons_second_law_of_motion(2.0, 1) 2.0 """ force = float() try: force = mass * acceleration except Exception: return -0.0 return force if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo mass = 12.5 acceleration = 10 force = newtons_second_law_of_motion(mass, acceleration) print("The force is ", force, "N")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def diophantine(a: int, b: int, c: int) -> tuple[float, float]: """ Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the diophantine equation a*x + b*y = c has a solution (where x and y are integers) iff gcd(a,b) divides c. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) >>> diophantine(10,6,14) (-7.0, 14.0) >>> diophantine(391,299,-69) (9.0, -12.0) But above equation has one more solution i.e., x = -4, y = 5. That's why we need diophantine all solution function. """ assert ( c % greatest_common_divisor(a, b) == 0 ) # greatest_common_divisor(a,b) function implemented below (d, x, y) = extended_gcd(a, b) # extended_gcd(a,b) function implemented below r = c / d return (r * x, r * y) def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: """ Lemma : if n|ab and gcd(a,n) = 1, then n|b. Finding All solutions of Diophantine Equations: Theorem : Let gcd(a,b) = d, a = d*p, b = d*q. If (x0,y0) is a solution of Diophantine Equation a*x + b*y = c. a*x0 + b*y0 = c, then all the solutions have the form a(x0 + t*q) + b(y0 - t*p) = c, where t is an arbitrary integer. n is the number of solution you want, n = 2 by default >>> diophantine_all_soln(10, 6, 14) -7.0 14.0 -4.0 9.0 >>> diophantine_all_soln(10, 6, 14, 4) -7.0 14.0 -4.0 9.0 -1.0 4.0 2.0 -1.0 >>> diophantine_all_soln(391, 299, -69, n = 4) 9.0 -12.0 22.0 -29.0 35.0 -46.0 48.0 -63.0 """ (x0, y0) = diophantine(a, b, c) # Initial value d = greatest_common_divisor(a, b) p = a // d q = b // d for i in range(n): x = x0 + i * q y = y0 - i * p print(x, y) def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1. >>> greatest_common_divisor(121, 11) 11 """ if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b def extended_gcd(a: int, b: int) -> tuple[int, int, int]: """ Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) """ assert a >= 0 and b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and b % d == 0 assert d == a * x + b * y return (d, x, y) if __name__ == "__main__": from doctest import testmod testmod(name="diophantine", verbose=True) testmod(name="diophantine_all_soln", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
from __future__ import annotations def diophantine(a: int, b: int, c: int) -> tuple[float, float]: """ Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the diophantine equation a*x + b*y = c has a solution (where x and y are integers) iff gcd(a,b) divides c. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) >>> diophantine(10,6,14) (-7.0, 14.0) >>> diophantine(391,299,-69) (9.0, -12.0) But above equation has one more solution i.e., x = -4, y = 5. That's why we need diophantine all solution function. """ assert ( c % greatest_common_divisor(a, b) == 0 ) # greatest_common_divisor(a,b) function implemented below (d, x, y) = extended_gcd(a, b) # extended_gcd(a,b) function implemented below r = c / d return (r * x, r * y) def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: """ Lemma : if n|ab and gcd(a,n) = 1, then n|b. Finding All solutions of Diophantine Equations: Theorem : Let gcd(a,b) = d, a = d*p, b = d*q. If (x0,y0) is a solution of Diophantine Equation a*x + b*y = c. a*x0 + b*y0 = c, then all the solutions have the form a(x0 + t*q) + b(y0 - t*p) = c, where t is an arbitrary integer. n is the number of solution you want, n = 2 by default >>> diophantine_all_soln(10, 6, 14) -7.0 14.0 -4.0 9.0 >>> diophantine_all_soln(10, 6, 14, 4) -7.0 14.0 -4.0 9.0 -1.0 4.0 2.0 -1.0 >>> diophantine_all_soln(391, 299, -69, n = 4) 9.0 -12.0 22.0 -29.0 35.0 -46.0 48.0 -63.0 """ (x0, y0) = diophantine(a, b, c) # Initial value d = greatest_common_divisor(a, b) p = a // d q = b // d for i in range(n): x = x0 + i * q y = y0 - i * p print(x, y) def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1. >>> greatest_common_divisor(121, 11) 11 """ if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b def extended_gcd(a: int, b: int) -> tuple[int, int, int]: """ Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) """ assert a >= 0 and b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and b % d == 0 assert d == a * x + b * y return (d, x, y) if __name__ == "__main__": from doctest import testmod testmod(name="diophantine", verbose=True) testmod(name="diophantine_all_soln", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def sum_of_geometric_progression( first_term: int, common_ratio: int, num_of_terms: int ) -> float: """ " Return the sum of n terms in a geometric progression. >>> sum_of_geometric_progression(1, 2, 10) 1023.0 >>> sum_of_geometric_progression(1, 10, 5) 11111.0 >>> sum_of_geometric_progression(0, 2, 10) 0.0 >>> sum_of_geometric_progression(1, 0, 10) 1.0 >>> sum_of_geometric_progression(1, 2, 0) -0.0 >>> sum_of_geometric_progression(-1, 2, 10) -1023.0 >>> sum_of_geometric_progression(1, -2, 10) -341.0 >>> sum_of_geometric_progression(1, 2, -10) -0.9990234375 """ if common_ratio == 1: # Formula for sum if common ratio is 1 return num_of_terms * first_term # Formula for finding sum of n terms of a GeometricProgression return (first_term / (1 - common_ratio)) * (1 - common_ratio**num_of_terms)
def sum_of_geometric_progression( first_term: int, common_ratio: int, num_of_terms: int ) -> float: """ " Return the sum of n terms in a geometric progression. >>> sum_of_geometric_progression(1, 2, 10) 1023.0 >>> sum_of_geometric_progression(1, 10, 5) 11111.0 >>> sum_of_geometric_progression(0, 2, 10) 0.0 >>> sum_of_geometric_progression(1, 0, 10) 1.0 >>> sum_of_geometric_progression(1, 2, 0) -0.0 >>> sum_of_geometric_progression(-1, 2, 10) -1023.0 >>> sum_of_geometric_progression(1, -2, 10) -341.0 >>> sum_of_geometric_progression(1, 2, -10) -0.9990234375 """ if common_ratio == 1: # Formula for sum if common ratio is 1 return num_of_terms * first_term # Formula for finding sum of n terms of a GeometricProgression return (first_term / (1 - common_ratio)) * (1 - common_ratio**num_of_terms)
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Heap's (iterative) algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
""" Heap's (iterative) algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# @Author : lightXu # @File : convolve.py # @Time : 2019/7/8 0008 下午 16:13 from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import array, dot, pad, ravel, uint8, zeros def im2col(image, block_size): rows, cols = image.shape dst_height = cols - block_size[1] + 1 dst_width = rows - block_size[0] + 1 image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0])) row = 0 for i in range(0, dst_height): for j in range(0, dst_width): window = ravel(image[i : i + block_size[0], j : j + block_size[1]]) image_array[row, :] = window row += 1 return image_array def img_convolve(image, filter_kernel): height, width = image.shape[0], image.shape[1] k_size = filter_kernel.shape[0] pad_size = k_size // 2 # Pads image with the edge values of array. image_tmp = pad(image, pad_size, mode="edge") # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows image_array = im2col(image_tmp, (k_size, k_size)) # turn the kernel into shape(k*k, 1) kernel_array = ravel(filter_kernel) # reshape and get the dst image dst = dot(image_array, kernel_array).reshape(height, width) return dst if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # Laplace operator Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) out = img_convolve(gray, Laplace_kernel).astype(uint8) imshow("Laplacian", out) waitKey(0)
# @Author : lightXu # @File : convolve.py # @Time : 2019/7/8 0008 下午 16:13 from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import array, dot, pad, ravel, uint8, zeros def im2col(image, block_size): rows, cols = image.shape dst_height = cols - block_size[1] + 1 dst_width = rows - block_size[0] + 1 image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0])) row = 0 for i in range(0, dst_height): for j in range(0, dst_width): window = ravel(image[i : i + block_size[0], j : j + block_size[1]]) image_array[row, :] = window row += 1 return image_array def img_convolve(image, filter_kernel): height, width = image.shape[0], image.shape[1] k_size = filter_kernel.shape[0] pad_size = k_size // 2 # Pads image with the edge values of array. image_tmp = pad(image, pad_size, mode="edge") # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows image_array = im2col(image_tmp, (k_size, k_size)) # turn the kernel into shape(k*k, 1) kernel_array = ravel(filter_kernel) # reshape and get the dst image dst = dot(image_array, kernel_array).reshape(height, width) return dst if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # Laplace operator Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) out = img_convolve(gray, Laplace_kernel).astype(uint8) imshow("Laplacian", out) waitKey(0)
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from .stack import Stack def balanced_parentheses(parentheses: str) -> bool: """Use a stack to check if a string of parentheses is balanced. >>> balanced_parentheses("([]{})") True >>> balanced_parentheses("[()]{}{[()()]()}") True >>> balanced_parentheses("[(])") False >>> balanced_parentheses("1+2*3-4") True >>> balanced_parentheses("") True """ stack: Stack[str] = Stack() bracket_pairs = {"(": ")", "[": "]", "{": "}"} for bracket in parentheses: if bracket in bracket_pairs: stack.push(bracket) elif bracket in (")", "]", "}"): if stack.is_empty() or bracket_pairs[stack.pop()] != bracket: return False return stack.is_empty() if __name__ == "__main__": from doctest import testmod testmod() examples = ["((()))", "((())", "(()))"] print("Balanced parentheses demonstration:\n") for example in examples: not_str = "" if balanced_parentheses(example) else "not " print(f"{example} is {not_str}balanced")
from .stack import Stack def balanced_parentheses(parentheses: str) -> bool: """Use a stack to check if a string of parentheses is balanced. >>> balanced_parentheses("([]{})") True >>> balanced_parentheses("[()]{}{[()()]()}") True >>> balanced_parentheses("[(])") False >>> balanced_parentheses("1+2*3-4") True >>> balanced_parentheses("") True """ stack: Stack[str] = Stack() bracket_pairs = {"(": ")", "[": "]", "{": "}"} for bracket in parentheses: if bracket in bracket_pairs: stack.push(bracket) elif bracket in (")", "]", "}"): if stack.is_empty() or bracket_pairs[stack.pop()] != bracket: return False return stack.is_empty() if __name__ == "__main__": from doctest import testmod testmod() examples = ["((()))", "((())", "(()))"] print("Balanced parentheses demonstration:\n") for example in examples: not_str = "" if balanced_parentheses(example) else "not " print(f"{example} is {not_str}balanced")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
hex_table = {hex(i)[2:]: i for i in range(16)} # Use [:2] to strip off the leading '0x' def hex_to_decimal(hex_string: str) -> int: """ Convert a hexadecimal value to its decimal equivalent #https://www.programiz.com/python-programming/methods/built-in/hex >>> hex_to_decimal("a") 10 >>> hex_to_decimal("12f") 303 >>> hex_to_decimal(" 12f ") 303 >>> hex_to_decimal("FfFf") 65535 >>> hex_to_decimal("-Ff") -255 >>> hex_to_decimal("F-f") Traceback (most recent call last): ... ValueError: Non-hexadecimal value was passed to the function >>> hex_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> hex_to_decimal("12m") Traceback (most recent call last): ... ValueError: Non-hexadecimal value was passed to the function """ hex_string = hex_string.strip().lower() if not hex_string: raise ValueError("Empty string was passed to the function") is_negative = hex_string[0] == "-" if is_negative: hex_string = hex_string[1:] if not all(char in hex_table for char in hex_string): raise ValueError("Non-hexadecimal value was passed to the function") decimal_number = 0 for char in hex_string: decimal_number = 16 * decimal_number + hex_table[char] return -decimal_number if is_negative else decimal_number if __name__ == "__main__": from doctest import testmod testmod()
hex_table = {hex(i)[2:]: i for i in range(16)} # Use [:2] to strip off the leading '0x' def hex_to_decimal(hex_string: str) -> int: """ Convert a hexadecimal value to its decimal equivalent #https://www.programiz.com/python-programming/methods/built-in/hex >>> hex_to_decimal("a") 10 >>> hex_to_decimal("12f") 303 >>> hex_to_decimal(" 12f ") 303 >>> hex_to_decimal("FfFf") 65535 >>> hex_to_decimal("-Ff") -255 >>> hex_to_decimal("F-f") Traceback (most recent call last): ... ValueError: Non-hexadecimal value was passed to the function >>> hex_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> hex_to_decimal("12m") Traceback (most recent call last): ... ValueError: Non-hexadecimal value was passed to the function """ hex_string = hex_string.strip().lower() if not hex_string: raise ValueError("Empty string was passed to the function") is_negative = hex_string[0] == "-" if is_negative: hex_string = hex_string[1:] if not all(char in hex_table for char in hex_string): raise ValueError("Non-hexadecimal value was passed to the function") decimal_number = 0 for char in hex_string: decimal_number = 16 * decimal_number + hex_table[char] return -decimal_number if is_negative else decimal_number if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" 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,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from collections import defaultdict from graphs.minimum_spanning_tree_prims import PrimsAlgorithm as mst def test_prim_successful_result(): num_nodes, num_edges = 9, 14 # noqa: F841 edges = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] adjancency = defaultdict(list) for node1, node2, cost in edges: adjancency[node1].append([node2, cost]) adjancency[node2].append([node1, cost]) result = mst(adjancency) expected = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: edge = tuple(answer[:2]) reverse = tuple(edge[::-1]) assert edge in result or reverse in result
from collections import defaultdict from graphs.minimum_spanning_tree_prims import PrimsAlgorithm as mst def test_prim_successful_result(): num_nodes, num_edges = 9, 14 # noqa: F841 edges = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] adjancency = defaultdict(list) for node1, node2, cost in edges: adjancency[node1].append([node2, cost]) adjancency[node2].append([node1, cost]) result = mst(adjancency) expected = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: edge = tuple(answer[:2]) reverse = tuple(edge[::-1]) assert edge in result or reverse in result
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Calculate the nth Proth number Source: https://handwiki.org/wiki/Proth_number """ import math def proth(number: int) -> int: """ :param number: nth number to calculate in the sequence :return: the nth number in Proth number Note: indexing starts at 1 i.e. proth(1) gives the first Proth number of 3 >>> proth(6) 25 >>> proth(0) Traceback (most recent call last): ... ValueError: Input value of [number=0] must be > 0 >>> proth(-1) Traceback (most recent call last): ... ValueError: Input value of [number=-1] must be > 0 >>> proth(6.0) Traceback (most recent call last): ... TypeError: Input value of [number=6.0] must be an integer """ if not isinstance(number, int): raise TypeError(f"Input value of [number={number}] must be an integer") if number < 1: raise ValueError(f"Input value of [number={number}] must be > 0") elif number == 1: return 3 elif number == 2: return 5 else: """ +1 for binary starting at 0 i.e. 2^0, 2^1, etc. +1 to start the sequence at the 3rd Proth number Hence, we have a +2 in the below statement """ block_index = int(math.log(number // 3, 2)) + 2 proth_list = [3, 5] proth_index = 2 increment = 3 for block in range(1, block_index): for move in range(increment): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1]) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): value = 0 try: value = proth(number) except ValueError: print(f"ValueError: there is no {number}th Proth number") continue print(f"The {number}th Proth number: {value}")
""" Calculate the nth Proth number Source: https://handwiki.org/wiki/Proth_number """ import math def proth(number: int) -> int: """ :param number: nth number to calculate in the sequence :return: the nth number in Proth number Note: indexing starts at 1 i.e. proth(1) gives the first Proth number of 3 >>> proth(6) 25 >>> proth(0) Traceback (most recent call last): ... ValueError: Input value of [number=0] must be > 0 >>> proth(-1) Traceback (most recent call last): ... ValueError: Input value of [number=-1] must be > 0 >>> proth(6.0) Traceback (most recent call last): ... TypeError: Input value of [number=6.0] must be an integer """ if not isinstance(number, int): raise TypeError(f"Input value of [number={number}] must be an integer") if number < 1: raise ValueError(f"Input value of [number={number}] must be > 0") elif number == 1: return 3 elif number == 2: return 5 else: """ +1 for binary starting at 0 i.e. 2^0, 2^1, etc. +1 to start the sequence at the 3rd Proth number Hence, we have a +2 in the below statement """ block_index = int(math.log(number // 3, 2)) + 2 proth_list = [3, 5] proth_index = 2 increment = 3 for block in range(1, block_index): for move in range(increment): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1]) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): value = 0 try: value = proth(number) except ValueError: print(f"ValueError: there is no {number}th Proth number") continue print(f"The {number}th Proth number: {value}")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from typing import Callable, Generic, TypeVar T = TypeVar("T") U = TypeVar("U") class DoubleLinkedListNode(Generic[T, U]): """ Double Linked List Node built specifically for LFU Cache >>> node = DoubleLinkedListNode(1,1) >>> node Node: key: 1, val: 1, freq: 0, has next: False, has prev: False """ def __init__(self, key: T | None, val: U | None): self.key = key self.val = val self.freq: int = 0 self.next: DoubleLinkedListNode[T, U] | None = None self.prev: DoubleLinkedListNode[T, U] | None = None def __repr__(self) -> str: return "Node: key: {}, val: {}, freq: {}, has next: {}, has prev: {}".format( self.key, self.val, self.freq, self.next is not None, self.prev is not None ) class DoubleLinkedList(Generic[T, U]): """ Double Linked List built specifically for LFU Cache >>> dll: DoubleLinkedList = DoubleLinkedList() >>> dll DoubleLinkedList, Node: key: None, val: None, freq: 0, has next: True, has prev: False, Node: key: None, val: None, freq: 0, has next: False, has prev: True >>> first_node = DoubleLinkedListNode(1,10) >>> first_node Node: key: 1, val: 10, freq: 0, has next: False, has prev: False >>> dll.add(first_node) >>> dll DoubleLinkedList, Node: key: None, val: None, freq: 0, has next: True, has prev: False, Node: key: 1, val: 10, freq: 1, has next: True, has prev: True, Node: key: None, val: None, freq: 0, has next: False, has prev: True >>> # node is mutated >>> first_node Node: key: 1, val: 10, freq: 1, has next: True, has prev: True >>> second_node = DoubleLinkedListNode(2,20) >>> second_node Node: key: 2, val: 20, freq: 0, has next: False, has prev: False >>> dll.add(second_node) >>> dll DoubleLinkedList, Node: key: None, val: None, freq: 0, has next: True, has prev: False, Node: key: 1, val: 10, freq: 1, has next: True, has prev: True, Node: key: 2, val: 20, freq: 1, has next: True, has prev: True, Node: key: None, val: None, freq: 0, has next: False, has prev: True >>> removed_node = dll.remove(first_node) >>> assert removed_node == first_node >>> dll DoubleLinkedList, Node: key: None, val: None, freq: 0, has next: True, has prev: False, Node: key: 2, val: 20, freq: 1, has next: True, has prev: True, Node: key: None, val: None, freq: 0, has next: False, has prev: True >>> # Attempt to remove node not on list >>> removed_node = dll.remove(first_node) >>> removed_node is None True >>> # Attempt to remove head or rear >>> dll.head Node: key: None, val: None, freq: 0, has next: True, has prev: False >>> dll.remove(dll.head) is None True >>> # Attempt to remove head or rear >>> dll.rear Node: key: None, val: None, freq: 0, has next: False, has prev: True >>> dll.remove(dll.rear) is None True """ def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.head.next, self.rear.prev = self.rear, self.head def __repr__(self) -> str: rep = ["DoubleLinkedList"] node = self.head while node.next is not None: rep.append(str(node)) node = node.next rep.append(str(self.rear)) return ",\n ".join(rep) def add(self, node: DoubleLinkedListNode[T, U]) -> None: """ Adds the given node at the tail of the list and shifting it to proper position """ previous = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None previous.next = node node.prev = previous self.rear.prev = node node.next = self.rear node.freq += 1 self._position_node(node) def _position_node(self, node: DoubleLinkedListNode[T, U]) -> None: """ Moves node forward to maintain invariant of sort by freq value """ while node.prev is not None and node.prev.freq > node.freq: # swap node with previous node previous_node = node.prev node.prev = previous_node.prev previous_node.next = node.prev node.next = previous_node previous_node.prev = node def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: """ Removes and returns the given node from the list Returns None if node.prev or node.next is None """ if node.prev is None or node.next is None: return None node.prev.next = node.next node.next.prev = node.prev node.prev = None node.next = None return node class LFUCache(Generic[T, U]): """ LFU Cache to store a given capacity of data. Can be used as a stand-alone object or as a function decorator. >>> cache = LFUCache(2) >>> cache.set(1, 1) >>> cache.set(2, 2) >>> cache.get(1) 1 >>> cache.set(3, 3) >>> cache.get(2) is None True >>> cache.set(4, 4) >>> cache.get(1) is None True >>> cache.get(3) 3 >>> cache.get(4) 4 >>> cache CacheInfo(hits=3, misses=2, capacity=2, current_size=2) >>> @LFUCache.decorator(100) ... def fib(num): ... if num in (1, 2): ... return 1 ... return fib(num - 1) + fib(num - 2) >>> for i in range(1, 101): ... res = fib(i) >>> fib.cache_info() CacheInfo(hits=196, misses=100, capacity=100, current_size=100) """ # class variable to map the decorator functions to their respective instance decorator_function_to_instance_map: dict[Callable[[T], U], LFUCache[T, U]] = {} def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() self.capacity = capacity self.num_keys = 0 self.hits = 0 self.miss = 0 self.cache: dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__(self) -> str: """ Return the details for the cache instance [hits, misses, capacity, current_size] """ return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " f"capacity={self.capacity}, current_size={self.num_keys})" ) def __contains__(self, key: T) -> bool: """ >>> cache = LFUCache(1) >>> 1 in cache False >>> cache.set(1, 1) >>> 1 in cache True """ return key in self.cache def get(self, key: T) -> U | None: """ Returns the value for the input key and updates the Double Linked List. Returns Returns None if key is not present in cache """ if key in self.cache: self.hits += 1 value_node: DoubleLinkedListNode[T, U] = self.cache[key] node = self.list.remove(self.cache[key]) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(node) return node.val self.miss += 1 return None def set(self, key: T, value: U) -> None: """ Sets the value for the input key and updates the Double Linked List """ if key not in self.cache: if self.num_keys >= self.capacity: # delete first node when over capacity first_node = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert self.list.remove(first_node) is not None # first_node guaranteed to be in list del self.cache[first_node.key] self.num_keys -= 1 self.cache[key] = DoubleLinkedListNode(key, value) self.list.add(self.cache[key]) self.num_keys += 1 else: node = self.list.remove(self.cache[key]) assert node is not None # node guaranteed to be in list node.val = value self.list.add(node) @classmethod def decorator( cls: type[LFUCache[T, U]], size: int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: """ Decorator version of LFU Cache Decorated function must be function of T -> U """ def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]: def cache_decorator_wrapper(*args: T) -> U: if func not in cls.decorator_function_to_instance_map: cls.decorator_function_to_instance_map[func] = LFUCache(size) result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) cls.decorator_function_to_instance_map[func].set(args[0], result) return result def cache_info() -> LFUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(cache_decorator_wrapper, "cache_info", cache_info) return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations from typing import Callable, Generic, TypeVar T = TypeVar("T") U = TypeVar("U") class DoubleLinkedListNode(Generic[T, U]): """ Double Linked List Node built specifically for LFU Cache >>> node = DoubleLinkedListNode(1,1) >>> node Node: key: 1, val: 1, freq: 0, has next: False, has prev: False """ def __init__(self, key: T | None, val: U | None): self.key = key self.val = val self.freq: int = 0 self.next: DoubleLinkedListNode[T, U] | None = None self.prev: DoubleLinkedListNode[T, U] | None = None def __repr__(self) -> str: return "Node: key: {}, val: {}, freq: {}, has next: {}, has prev: {}".format( self.key, self.val, self.freq, self.next is not None, self.prev is not None ) class DoubleLinkedList(Generic[T, U]): """ Double Linked List built specifically for LFU Cache >>> dll: DoubleLinkedList = DoubleLinkedList() >>> dll DoubleLinkedList, Node: key: None, val: None, freq: 0, has next: True, has prev: False, Node: key: None, val: None, freq: 0, has next: False, has prev: True >>> first_node = DoubleLinkedListNode(1,10) >>> first_node Node: key: 1, val: 10, freq: 0, has next: False, has prev: False >>> dll.add(first_node) >>> dll DoubleLinkedList, Node: key: None, val: None, freq: 0, has next: True, has prev: False, Node: key: 1, val: 10, freq: 1, has next: True, has prev: True, Node: key: None, val: None, freq: 0, has next: False, has prev: True >>> # node is mutated >>> first_node Node: key: 1, val: 10, freq: 1, has next: True, has prev: True >>> second_node = DoubleLinkedListNode(2,20) >>> second_node Node: key: 2, val: 20, freq: 0, has next: False, has prev: False >>> dll.add(second_node) >>> dll DoubleLinkedList, Node: key: None, val: None, freq: 0, has next: True, has prev: False, Node: key: 1, val: 10, freq: 1, has next: True, has prev: True, Node: key: 2, val: 20, freq: 1, has next: True, has prev: True, Node: key: None, val: None, freq: 0, has next: False, has prev: True >>> removed_node = dll.remove(first_node) >>> assert removed_node == first_node >>> dll DoubleLinkedList, Node: key: None, val: None, freq: 0, has next: True, has prev: False, Node: key: 2, val: 20, freq: 1, has next: True, has prev: True, Node: key: None, val: None, freq: 0, has next: False, has prev: True >>> # Attempt to remove node not on list >>> removed_node = dll.remove(first_node) >>> removed_node is None True >>> # Attempt to remove head or rear >>> dll.head Node: key: None, val: None, freq: 0, has next: True, has prev: False >>> dll.remove(dll.head) is None True >>> # Attempt to remove head or rear >>> dll.rear Node: key: None, val: None, freq: 0, has next: False, has prev: True >>> dll.remove(dll.rear) is None True """ def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.head.next, self.rear.prev = self.rear, self.head def __repr__(self) -> str: rep = ["DoubleLinkedList"] node = self.head while node.next is not None: rep.append(str(node)) node = node.next rep.append(str(self.rear)) return ",\n ".join(rep) def add(self, node: DoubleLinkedListNode[T, U]) -> None: """ Adds the given node at the tail of the list and shifting it to proper position """ previous = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None previous.next = node node.prev = previous self.rear.prev = node node.next = self.rear node.freq += 1 self._position_node(node) def _position_node(self, node: DoubleLinkedListNode[T, U]) -> None: """ Moves node forward to maintain invariant of sort by freq value """ while node.prev is not None and node.prev.freq > node.freq: # swap node with previous node previous_node = node.prev node.prev = previous_node.prev previous_node.next = node.prev node.next = previous_node previous_node.prev = node def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: """ Removes and returns the given node from the list Returns None if node.prev or node.next is None """ if node.prev is None or node.next is None: return None node.prev.next = node.next node.next.prev = node.prev node.prev = None node.next = None return node class LFUCache(Generic[T, U]): """ LFU Cache to store a given capacity of data. Can be used as a stand-alone object or as a function decorator. >>> cache = LFUCache(2) >>> cache.set(1, 1) >>> cache.set(2, 2) >>> cache.get(1) 1 >>> cache.set(3, 3) >>> cache.get(2) is None True >>> cache.set(4, 4) >>> cache.get(1) is None True >>> cache.get(3) 3 >>> cache.get(4) 4 >>> cache CacheInfo(hits=3, misses=2, capacity=2, current_size=2) >>> @LFUCache.decorator(100) ... def fib(num): ... if num in (1, 2): ... return 1 ... return fib(num - 1) + fib(num - 2) >>> for i in range(1, 101): ... res = fib(i) >>> fib.cache_info() CacheInfo(hits=196, misses=100, capacity=100, current_size=100) """ # class variable to map the decorator functions to their respective instance decorator_function_to_instance_map: dict[Callable[[T], U], LFUCache[T, U]] = {} def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() self.capacity = capacity self.num_keys = 0 self.hits = 0 self.miss = 0 self.cache: dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__(self) -> str: """ Return the details for the cache instance [hits, misses, capacity, current_size] """ return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " f"capacity={self.capacity}, current_size={self.num_keys})" ) def __contains__(self, key: T) -> bool: """ >>> cache = LFUCache(1) >>> 1 in cache False >>> cache.set(1, 1) >>> 1 in cache True """ return key in self.cache def get(self, key: T) -> U | None: """ Returns the value for the input key and updates the Double Linked List. Returns Returns None if key is not present in cache """ if key in self.cache: self.hits += 1 value_node: DoubleLinkedListNode[T, U] = self.cache[key] node = self.list.remove(self.cache[key]) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(node) return node.val self.miss += 1 return None def set(self, key: T, value: U) -> None: """ Sets the value for the input key and updates the Double Linked List """ if key not in self.cache: if self.num_keys >= self.capacity: # delete first node when over capacity first_node = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert self.list.remove(first_node) is not None # first_node guaranteed to be in list del self.cache[first_node.key] self.num_keys -= 1 self.cache[key] = DoubleLinkedListNode(key, value) self.list.add(self.cache[key]) self.num_keys += 1 else: node = self.list.remove(self.cache[key]) assert node is not None # node guaranteed to be in list node.val = value self.list.add(node) @classmethod def decorator( cls: type[LFUCache[T, U]], size: int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: """ Decorator version of LFU Cache Decorated function must be function of T -> U """ def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]: def cache_decorator_wrapper(*args: T) -> U: if func not in cls.decorator_function_to_instance_map: cls.decorator_function_to_instance_map[func] = LFUCache(size) result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) cls.decorator_function_to_instance_map[func].set(args[0], result) return result def cache_info() -> LFUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(cache_decorator_wrapper, "cache_info", cache_info) return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from typing import Iterable class Heap: """A Max Heap Implementation >>> unsorted = [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5] >>> h = Heap() >>> h.build_max_heap(unsorted) >>> print(h) [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5] >>> >>> h.extract_max() 209 >>> print(h) [201, 107, 25, 103, 11, 15, 1, 9, 7, 5] >>> >>> h.insert(100) >>> print(h) [201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11] >>> >>> h.heap_sort() >>> print(h) [1, 5, 7, 9, 11, 15, 25, 100, 103, 107, 201] """ def __init__(self) -> None: self.h: list[float] = [] self.heap_size: int = 0 def __repr__(self) -> str: return str(self.h) def parent_index(self, child_idx: int) -> int | None: """return the parent index of given child""" if child_idx > 0: return (child_idx - 1) // 2 return None def left_child_idx(self, parent_idx: int) -> int | None: """ return the left child index if the left child exists. if not, return None. """ left_child_index = 2 * parent_idx + 1 if left_child_index < self.heap_size: return left_child_index return None def right_child_idx(self, parent_idx: int) -> int | None: """ return the right child index if the right child exists. if not, return None. """ right_child_index = 2 * parent_idx + 2 if right_child_index < self.heap_size: return right_child_index return None def max_heapify(self, index: int) -> None: """ correct a single violation of the heap property in a subtree's root. """ if index < self.heap_size: violation: int = index left_child = self.left_child_idx(index) right_child = self.right_child_idx(index) # check which child is larger than its parent if left_child is not None and self.h[left_child] > self.h[violation]: violation = left_child if right_child is not None and self.h[right_child] > self.h[violation]: violation = right_child # if violation indeed exists if violation != index: # swap to fix the violation self.h[violation], self.h[index] = self.h[index], self.h[violation] # fix the subsequent violation recursively if any self.max_heapify(violation) def build_max_heap(self, collection: Iterable[float]) -> None: """build max heap from an unsorted array""" self.h = list(collection) self.heap_size = len(self.h) if self.heap_size > 1: # max_heapify from right to left but exclude leaves (last level) for i in range(self.heap_size // 2 - 1, -1, -1): self.max_heapify(i) def max(self) -> float: """return the max in the heap""" if self.heap_size >= 1: return self.h[0] else: raise Exception("Empty heap") def extract_max(self) -> float: """get and remove max from heap""" if self.heap_size >= 2: me = self.h[0] self.h[0] = self.h.pop(-1) self.heap_size -= 1 self.max_heapify(0) return me elif self.heap_size == 1: self.heap_size -= 1 return self.h.pop(-1) else: raise Exception("Empty heap") def insert(self, value: float) -> None: """insert a new value into the max heap""" self.h.append(value) idx = (self.heap_size - 1) // 2 self.heap_size += 1 while idx >= 0: self.max_heapify(idx) idx = (idx - 1) // 2 def heap_sort(self) -> None: size = self.heap_size for j in range(size - 1, 0, -1): self.h[0], self.h[j] = self.h[j], self.h[0] self.heap_size -= 1 self.max_heapify(0) self.heap_size = size if __name__ == "__main__": import doctest # run doc test doctest.testmod() # demo for unsorted in [ [0], [2], [3, 5], [5, 3], [5, 5], [0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 3, 5], [0, 2, 2, 3, 5], [2, 5, 3, 0, 2, 3, 0, 3], [6, 1, 2, 7, 9, 3, 4, 5, 10, 8], [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5], [-45, -2, -5], ]: print(f"unsorted array: {unsorted}") heap = Heap() heap.build_max_heap(unsorted) print(f"after build heap: {heap}") print(f"max value: {heap.extract_max()}") print(f"after max value removed: {heap}") heap.insert(100) print(f"after new value 100 inserted: {heap}") heap.heap_sort() print(f"heap-sorted array: {heap}\n")
from __future__ import annotations from typing import Iterable class Heap: """A Max Heap Implementation >>> unsorted = [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5] >>> h = Heap() >>> h.build_max_heap(unsorted) >>> print(h) [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5] >>> >>> h.extract_max() 209 >>> print(h) [201, 107, 25, 103, 11, 15, 1, 9, 7, 5] >>> >>> h.insert(100) >>> print(h) [201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11] >>> >>> h.heap_sort() >>> print(h) [1, 5, 7, 9, 11, 15, 25, 100, 103, 107, 201] """ def __init__(self) -> None: self.h: list[float] = [] self.heap_size: int = 0 def __repr__(self) -> str: return str(self.h) def parent_index(self, child_idx: int) -> int | None: """return the parent index of given child""" if child_idx > 0: return (child_idx - 1) // 2 return None def left_child_idx(self, parent_idx: int) -> int | None: """ return the left child index if the left child exists. if not, return None. """ left_child_index = 2 * parent_idx + 1 if left_child_index < self.heap_size: return left_child_index return None def right_child_idx(self, parent_idx: int) -> int | None: """ return the right child index if the right child exists. if not, return None. """ right_child_index = 2 * parent_idx + 2 if right_child_index < self.heap_size: return right_child_index return None def max_heapify(self, index: int) -> None: """ correct a single violation of the heap property in a subtree's root. """ if index < self.heap_size: violation: int = index left_child = self.left_child_idx(index) right_child = self.right_child_idx(index) # check which child is larger than its parent if left_child is not None and self.h[left_child] > self.h[violation]: violation = left_child if right_child is not None and self.h[right_child] > self.h[violation]: violation = right_child # if violation indeed exists if violation != index: # swap to fix the violation self.h[violation], self.h[index] = self.h[index], self.h[violation] # fix the subsequent violation recursively if any self.max_heapify(violation) def build_max_heap(self, collection: Iterable[float]) -> None: """build max heap from an unsorted array""" self.h = list(collection) self.heap_size = len(self.h) if self.heap_size > 1: # max_heapify from right to left but exclude leaves (last level) for i in range(self.heap_size // 2 - 1, -1, -1): self.max_heapify(i) def max(self) -> float: """return the max in the heap""" if self.heap_size >= 1: return self.h[0] else: raise Exception("Empty heap") def extract_max(self) -> float: """get and remove max from heap""" if self.heap_size >= 2: me = self.h[0] self.h[0] = self.h.pop(-1) self.heap_size -= 1 self.max_heapify(0) return me elif self.heap_size == 1: self.heap_size -= 1 return self.h.pop(-1) else: raise Exception("Empty heap") def insert(self, value: float) -> None: """insert a new value into the max heap""" self.h.append(value) idx = (self.heap_size - 1) // 2 self.heap_size += 1 while idx >= 0: self.max_heapify(idx) idx = (idx - 1) // 2 def heap_sort(self) -> None: size = self.heap_size for j in range(size - 1, 0, -1): self.h[0], self.h[j] = self.h[j], self.h[0] self.heap_size -= 1 self.max_heapify(0) self.heap_size = size if __name__ == "__main__": import doctest # run doc test doctest.testmod() # demo for unsorted in [ [0], [2], [3, 5], [5, 3], [5, 5], [0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 3, 5], [0, 2, 2, 3, 5], [2, 5, 3, 0, 2, 3, 0, 3], [6, 1, 2, 7, 9, 3, 4, 5, 10, 8], [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5], [-45, -2, -5], ]: print(f"unsorted array: {unsorted}") heap = Heap() heap.build_max_heap(unsorted) print(f"after build heap: {heap}") print(f"max value: {heap.extract_max()}") print(f"after max value removed: {heap}") heap.insert(100) print(f"after new value 100 inserted: {heap}") heap.heap_sort() print(f"heap-sorted array: {heap}\n")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Output: Enter a Postfix Equation (space separated) = 5 6 9 * + Symbol | Action | Stack ----------------------------------- 5 | push(5) | 5 6 | push(6) | 5,6 9 | push(9) | 5,6,9 | pop(9) | 5,6 | pop(6) | 5 * | push(6*9) | 5,54 | pop(54) | 5 | pop(5) | + | push(5+54) | 59 Result = 59 """ import operator as op def Solve(Postfix): Stack = [] Div = lambda x, y: int(x / y) # noqa: E731 integer division operation Opr = { "^": op.pow, "*": op.mul, "/": Div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8), "Action".center(12), "Stack", sep=" | ") print("-" * (30 + len(Postfix))) for x in Postfix: if x.isdigit(): # if x in digit Stack.append(x) # append x to stack # output in tabular format print(x.rjust(8), ("push(" + x + ")").ljust(12), ",".join(Stack), sep=" | ") else: B = Stack.pop() # pop stack # output in tabular format print("".rjust(8), ("pop(" + B + ")").ljust(12), ",".join(Stack), sep=" | ") A = Stack.pop() # pop stack # output in tabular format print("".rjust(8), ("pop(" + A + ")").ljust(12), ",".join(Stack), sep=" | ") Stack.append( str(Opr[x](int(A), int(B))) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8), ("push(" + A + x + B + ")").ljust(12), ",".join(Stack), sep=" | ", ) return int(Stack[0]) if __name__ == "__main__": Postfix = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", Solve(Postfix))
""" Output: Enter a Postfix Equation (space separated) = 5 6 9 * + Symbol | Action | Stack ----------------------------------- 5 | push(5) | 5 6 | push(6) | 5,6 9 | push(9) | 5,6,9 | pop(9) | 5,6 | pop(6) | 5 * | push(6*9) | 5,54 | pop(54) | 5 | pop(5) | + | push(5+54) | 59 Result = 59 """ import operator as op def Solve(Postfix): Stack = [] Div = lambda x, y: int(x / y) # noqa: E731 integer division operation Opr = { "^": op.pow, "*": op.mul, "/": Div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8), "Action".center(12), "Stack", sep=" | ") print("-" * (30 + len(Postfix))) for x in Postfix: if x.isdigit(): # if x in digit Stack.append(x) # append x to stack # output in tabular format print(x.rjust(8), ("push(" + x + ")").ljust(12), ",".join(Stack), sep=" | ") else: B = Stack.pop() # pop stack # output in tabular format print("".rjust(8), ("pop(" + B + ")").ljust(12), ",".join(Stack), sep=" | ") A = Stack.pop() # pop stack # output in tabular format print("".rjust(8), ("pop(" + A + ")").ljust(12), ",".join(Stack), sep=" | ") Stack.append( str(Opr[x](int(A), int(B))) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8), ("push(" + A + x + B + ")").ljust(12), ",".join(Stack), sep=" | ", ) return int(Stack[0]) if __name__ == "__main__": Postfix = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", Solve(Postfix))
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def decrypt(message: str) -> None: """ >>> decrypt('TMDETUX PMDVU') Decryption using Key #0: TMDETUX PMDVU Decryption using Key #1: SLCDSTW OLCUT Decryption using Key #2: RKBCRSV NKBTS Decryption using Key #3: QJABQRU MJASR Decryption using Key #4: PIZAPQT LIZRQ Decryption using Key #5: OHYZOPS KHYQP Decryption using Key #6: NGXYNOR JGXPO Decryption using Key #7: MFWXMNQ IFWON Decryption using Key #8: LEVWLMP HEVNM Decryption using Key #9: KDUVKLO GDUML Decryption using Key #10: JCTUJKN FCTLK Decryption using Key #11: IBSTIJM EBSKJ Decryption using Key #12: HARSHIL DARJI Decryption using Key #13: GZQRGHK CZQIH Decryption using Key #14: FYPQFGJ BYPHG Decryption using Key #15: EXOPEFI AXOGF Decryption using Key #16: DWNODEH ZWNFE Decryption using Key #17: CVMNCDG YVMED Decryption using Key #18: BULMBCF XULDC Decryption using Key #19: ATKLABE WTKCB Decryption using Key #20: ZSJKZAD VSJBA Decryption using Key #21: YRIJYZC URIAZ Decryption using Key #22: XQHIXYB TQHZY Decryption using Key #23: WPGHWXA SPGYX Decryption using Key #24: VOFGVWZ ROFXW Decryption using Key #25: UNEFUVY QNEWV """ LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for key in range(len(LETTERS)): translated = "" for symbol in message: if symbol in LETTERS: num = LETTERS.find(symbol) num = num - key if num < 0: num = num + len(LETTERS) translated = translated + LETTERS[num] else: translated = translated + symbol print(f"Decryption using Key #{key}: {translated}") def main() -> None: message = input("Encrypted message: ") message = message.upper() decrypt(message) if __name__ == "__main__": import doctest doctest.testmod() main()
def decrypt(message: str) -> None: """ >>> decrypt('TMDETUX PMDVU') Decryption using Key #0: TMDETUX PMDVU Decryption using Key #1: SLCDSTW OLCUT Decryption using Key #2: RKBCRSV NKBTS Decryption using Key #3: QJABQRU MJASR Decryption using Key #4: PIZAPQT LIZRQ Decryption using Key #5: OHYZOPS KHYQP Decryption using Key #6: NGXYNOR JGXPO Decryption using Key #7: MFWXMNQ IFWON Decryption using Key #8: LEVWLMP HEVNM Decryption using Key #9: KDUVKLO GDUML Decryption using Key #10: JCTUJKN FCTLK Decryption using Key #11: IBSTIJM EBSKJ Decryption using Key #12: HARSHIL DARJI Decryption using Key #13: GZQRGHK CZQIH Decryption using Key #14: FYPQFGJ BYPHG Decryption using Key #15: EXOPEFI AXOGF Decryption using Key #16: DWNODEH ZWNFE Decryption using Key #17: CVMNCDG YVMED Decryption using Key #18: BULMBCF XULDC Decryption using Key #19: ATKLABE WTKCB Decryption using Key #20: ZSJKZAD VSJBA Decryption using Key #21: YRIJYZC URIAZ Decryption using Key #22: XQHIXYB TQHZY Decryption using Key #23: WPGHWXA SPGYX Decryption using Key #24: VOFGVWZ ROFXW Decryption using Key #25: UNEFUVY QNEWV """ LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for key in range(len(LETTERS)): translated = "" for symbol in message: if symbol in LETTERS: num = LETTERS.find(symbol) num = num - key if num < 0: num = num + len(LETTERS) translated = translated + LETTERS[num] else: translated = translated + symbol print(f"Decryption using Key #{key}: {translated}") def main() -> None: message = input("Encrypted message: ") message = message.upper() decrypt(message) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A recursive implementation of the insertion sort algorithm """ from __future__ import annotations def rec_insertion_sort(collection: list, n: int): """ Given a collection of numbers and its length, sorts the collections in ascending order :param collection: A mutable collection of comparable elements :param n: The length of collections >>> col = [1, 2, 1] >>> rec_insertion_sort(col, len(col)) >>> print(col) [1, 1, 2] >>> col = [2, 1, 0, -1, -2] >>> rec_insertion_sort(col, len(col)) >>> print(col) [-2, -1, 0, 1, 2] >>> col = [1] >>> rec_insertion_sort(col, len(col)) >>> print(col) [1] """ # Checks if the entire collection has been sorted if len(collection) <= 1 or n <= 1: return insert_next(collection, n - 1) rec_insertion_sort(collection, n - 1) def insert_next(collection: list, index: int): """ Inserts the '(index-1)th' element into place >>> col = [3, 2, 4, 2] >>> insert_next(col, 1) >>> print(col) [2, 3, 4, 2] >>> col = [3, 2, 3] >>> insert_next(col, 2) >>> print(col) [3, 2, 3] >>> col = [] >>> insert_next(col, 1) >>> print(col) [] """ # Checks order between adjacent elements if index >= len(collection) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order collection[index - 1], collection[index] = ( collection[index], collection[index - 1], ) insert_next(collection, index + 1) if __name__ == "__main__": numbers = input("Enter integers separated by spaces: ") number_list: list[int] = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
""" A recursive implementation of the insertion sort algorithm """ from __future__ import annotations def rec_insertion_sort(collection: list, n: int): """ Given a collection of numbers and its length, sorts the collections in ascending order :param collection: A mutable collection of comparable elements :param n: The length of collections >>> col = [1, 2, 1] >>> rec_insertion_sort(col, len(col)) >>> print(col) [1, 1, 2] >>> col = [2, 1, 0, -1, -2] >>> rec_insertion_sort(col, len(col)) >>> print(col) [-2, -1, 0, 1, 2] >>> col = [1] >>> rec_insertion_sort(col, len(col)) >>> print(col) [1] """ # Checks if the entire collection has been sorted if len(collection) <= 1 or n <= 1: return insert_next(collection, n - 1) rec_insertion_sort(collection, n - 1) def insert_next(collection: list, index: int): """ Inserts the '(index-1)th' element into place >>> col = [3, 2, 4, 2] >>> insert_next(col, 1) >>> print(col) [2, 3, 4, 2] >>> col = [3, 2, 3] >>> insert_next(col, 2) >>> print(col) [3, 2, 3] >>> col = [] >>> insert_next(col, 1) >>> print(col) [] """ # Checks order between adjacent elements if index >= len(collection) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order collection[index - 1], collection[index] = ( collection[index], collection[index - 1], ) insert_next(collection, index + 1) if __name__ == "__main__": numbers = input("Enter integers separated by spaces: ") number_list: list[int] = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def remove_duplicates(sentence: str) -> str: """ Remove duplicates from sentence >>> remove_duplicates("Python is great and Java is also great") 'Java Python also and great is' >>> remove_duplicates("Python is great and Java is also great") 'Java Python also and great is' """ return " ".join(sorted(set(sentence.split()))) if __name__ == "__main__": import doctest doctest.testmod()
def remove_duplicates(sentence: str) -> str: """ Remove duplicates from sentence >>> remove_duplicates("Python is great and Java is also great") 'Java Python also and great is' >>> remove_duplicates("Python is great and Java is also great") 'Java Python also and great is' """ return " ".join(sorted(set(sentence.split()))) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 91: https://projecteuler.net/problem=91 The points P (x1, y1) and Q (x2, y2) are plotted at integer coordinates and are joined to the origin, O(0,0), to form ΔOPQ.  There are exactly fourteen triangles containing a right angle that can be formed when each coordinate lies between 0 and 2 inclusive; that is, 0 ≤ x1, y1, x2, y2 ≤ 2.  Given that 0 ≤ x1, y1, x2, y2 ≤ 50, how many right triangles can be formed? """ from itertools import combinations, product def is_right(x1: int, y1: int, x2: int, y2: int) -> bool: """ Check if the triangle described by P(x1,y1), Q(x2,y2) and O(0,0) is right-angled. Note: this doesn't check if P and Q are equal, but that's handled by the use of itertools.combinations in the solution function. >>> is_right(0, 1, 2, 0) True >>> is_right(1, 0, 2, 2) False """ if x1 == y1 == 0 or x2 == y2 == 0: return False a_square = x1 * x1 + y1 * y1 b_square = x2 * x2 + y2 * y2 c_square = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) return ( a_square + b_square == c_square or a_square + c_square == b_square or b_square + c_square == a_square ) def solution(limit: int = 50) -> int: """ Return the number of right triangles OPQ that can be formed by two points P, Q which have both x- and y- coordinates between 0 and limit inclusive. >>> solution(2) 14 >>> solution(10) 448 """ return sum( 1 for pt1, pt2 in combinations(product(range(limit + 1), repeat=2), 2) if is_right(*pt1, *pt2) ) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 91: https://projecteuler.net/problem=91 The points P (x1, y1) and Q (x2, y2) are plotted at integer coordinates and are joined to the origin, O(0,0), to form ΔOPQ.  There are exactly fourteen triangles containing a right angle that can be formed when each coordinate lies between 0 and 2 inclusive; that is, 0 ≤ x1, y1, x2, y2 ≤ 2.  Given that 0 ≤ x1, y1, x2, y2 ≤ 50, how many right triangles can be formed? """ from itertools import combinations, product def is_right(x1: int, y1: int, x2: int, y2: int) -> bool: """ Check if the triangle described by P(x1,y1), Q(x2,y2) and O(0,0) is right-angled. Note: this doesn't check if P and Q are equal, but that's handled by the use of itertools.combinations in the solution function. >>> is_right(0, 1, 2, 0) True >>> is_right(1, 0, 2, 2) False """ if x1 == y1 == 0 or x2 == y2 == 0: return False a_square = x1 * x1 + y1 * y1 b_square = x2 * x2 + y2 * y2 c_square = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) return ( a_square + b_square == c_square or a_square + c_square == b_square or b_square + c_square == a_square ) def solution(limit: int = 50) -> int: """ Return the number of right triangles OPQ that can be formed by two points P, Q which have both x- and y- coordinates between 0 and limit inclusive. >>> solution(2) 14 >>> solution(10) 448 """ return sum( 1 for pt1, pt2 in combinations(product(range(limit + 1), repeat=2), 2) if is_right(*pt1, *pt2) ) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Normalization Wikipedia: https://en.wikipedia.org/wiki/Normalization Normalization is the process of converting numerical data to a standard range of values. This range is typically between [0, 1] or [-1, 1]. The equation for normalization is x_norm = (x - x_min)/(x_max - x_min) where x_norm is the normalized value, x is the value, x_min is the minimum value within the column or list of data, and x_max is the maximum value within the column or list of data. Normalization is used to speed up the training of data and put all of the data on a similar scale. This is useful because variance in the range of values of a dataset can heavily impact optimization (particularly Gradient Descent). Standardization Wikipedia: https://en.wikipedia.org/wiki/Standardization Standardization is the process of converting numerical data to a normally distributed range of values. This range will have a mean of 0 and standard deviation of 1. This is also known as z-score normalization. The equation for standardization is x_std = (x - mu)/(sigma) where mu is the mean of the column or list of values and sigma is the standard deviation of the column or list of values. Choosing between Normalization & Standardization is more of an art of a science, but it is often recommended to run experiments with both to see which performs better. Additionally, a few rules of thumb are: 1. gaussian (normal) distributions work better with standardization 2. non-gaussian (non-normal) distributions work better with normalization 3. If a column or list of values has extreme values / outliers, use standardization """ from statistics import mean, stdev def normalization(data: list, ndigits: int = 3) -> list: """ Returns a normalized list of values @params: data, a list of values to normalize @returns: a list of normalized values (rounded to ndigits decimal places) @examples: >>> normalization([2, 7, 10, 20, 30, 50]) [0.0, 0.104, 0.167, 0.375, 0.583, 1.0] >>> normalization([5, 10, 15, 20, 25]) [0.0, 0.25, 0.5, 0.75, 1.0] """ # variables for calculation x_min = min(data) x_max = max(data) # normalize data return [round((x - x_min) / (x_max - x_min), ndigits) for x in data] def standardization(data: list, ndigits: int = 3) -> list: """ Returns a standardized list of values @params: data, a list of values to standardize @returns: a list of standardized values (rounded to ndigits decimal places) @examples: >>> standardization([2, 7, 10, 20, 30, 50]) [-0.999, -0.719, -0.551, 0.009, 0.57, 1.69] >>> standardization([5, 10, 15, 20, 25]) [-1.265, -0.632, 0.0, 0.632, 1.265] """ # variables for calculation mu = mean(data) sigma = stdev(data) # standardize data return [round((x - mu) / (sigma), ndigits) for x in data]
""" Normalization Wikipedia: https://en.wikipedia.org/wiki/Normalization Normalization is the process of converting numerical data to a standard range of values. This range is typically between [0, 1] or [-1, 1]. The equation for normalization is x_norm = (x - x_min)/(x_max - x_min) where x_norm is the normalized value, x is the value, x_min is the minimum value within the column or list of data, and x_max is the maximum value within the column or list of data. Normalization is used to speed up the training of data and put all of the data on a similar scale. This is useful because variance in the range of values of a dataset can heavily impact optimization (particularly Gradient Descent). Standardization Wikipedia: https://en.wikipedia.org/wiki/Standardization Standardization is the process of converting numerical data to a normally distributed range of values. This range will have a mean of 0 and standard deviation of 1. This is also known as z-score normalization. The equation for standardization is x_std = (x - mu)/(sigma) where mu is the mean of the column or list of values and sigma is the standard deviation of the column or list of values. Choosing between Normalization & Standardization is more of an art of a science, but it is often recommended to run experiments with both to see which performs better. Additionally, a few rules of thumb are: 1. gaussian (normal) distributions work better with standardization 2. non-gaussian (non-normal) distributions work better with normalization 3. If a column or list of values has extreme values / outliers, use standardization """ from statistics import mean, stdev def normalization(data: list, ndigits: int = 3) -> list: """ Returns a normalized list of values @params: data, a list of values to normalize @returns: a list of normalized values (rounded to ndigits decimal places) @examples: >>> normalization([2, 7, 10, 20, 30, 50]) [0.0, 0.104, 0.167, 0.375, 0.583, 1.0] >>> normalization([5, 10, 15, 20, 25]) [0.0, 0.25, 0.5, 0.75, 1.0] """ # variables for calculation x_min = min(data) x_max = max(data) # normalize data return [round((x - x_min) / (x_max - x_min), ndigits) for x in data] def standardization(data: list, ndigits: int = 3) -> list: """ Returns a standardized list of values @params: data, a list of values to standardize @returns: a list of standardized values (rounded to ndigits decimal places) @examples: >>> standardization([2, 7, 10, 20, 30, 50]) [-0.999, -0.719, -0.551, 0.009, 0.57, 1.69] >>> standardization([5, 10, 15, 20, 25]) [-1.265, -0.632, 0.0, 0.632, 1.265] """ # variables for calculation mu = mean(data) sigma = stdev(data) # standardize data return [round((x - mu) / (sigma), ndigits) for x in data]
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 27 https://projecteuler.net/problem=27 Problem Statement: Euler discovered the remarkable quadratic formula: n2 + n + 41 It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 412 + 41 + 41 is clearly divisible by 41. The incredible formula n2 − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479. Considering quadratics of the form: n² + an + b, where |a| &lt; 1000 and |b| &lt; 1000 where |n| is the modulus/absolute value of ne.g. |11| = 11 and |−4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. """ import math def is_prime(k: int) -> bool: """ Determine if a number is prime >>> is_prime(10) False >>> is_prime(11) True """ if k < 2 or k % 2 == 0: return False elif k == 2: return True else: for x in range(3, int(math.sqrt(k) + 1), 2): if k % x == 0: return False return True def solution(a_limit: int = 1000, b_limit: int = 1000) -> int: """ >>> solution(1000, 1000) -59231 >>> solution(200, 1000) -59231 >>> solution(200, 200) -4925 >>> solution(-1000, 1000) 0 >>> solution(-1000, -1000) 0 """ longest = [0, 0, 0] # length, a, b for a in range((a_limit * -1) + 1, a_limit): for b in range(2, b_limit): if is_prime(b): count = 0 n = 0 while is_prime((n**2) + (a * n) + b): count += 1 n += 1 if count > longest[0]: longest = [count, a, b] ans = longest[1] * longest[2] return ans if __name__ == "__main__": print(solution(1000, 1000))
""" Project Euler Problem 27 https://projecteuler.net/problem=27 Problem Statement: Euler discovered the remarkable quadratic formula: n2 + n + 41 It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 412 + 41 + 41 is clearly divisible by 41. The incredible formula n2 − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479. Considering quadratics of the form: n² + an + b, where |a| &lt; 1000 and |b| &lt; 1000 where |n| is the modulus/absolute value of ne.g. |11| = 11 and |−4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. """ import math def is_prime(k: int) -> bool: """ Determine if a number is prime >>> is_prime(10) False >>> is_prime(11) True """ if k < 2 or k % 2 == 0: return False elif k == 2: return True else: for x in range(3, int(math.sqrt(k) + 1), 2): if k % x == 0: return False return True def solution(a_limit: int = 1000, b_limit: int = 1000) -> int: """ >>> solution(1000, 1000) -59231 >>> solution(200, 1000) -59231 >>> solution(200, 200) -4925 >>> solution(-1000, 1000) 0 >>> solution(-1000, -1000) 0 """ longest = [0, 0, 0] # length, a, b for a in range((a_limit * -1) + 1, a_limit): for b in range(2, b_limit): if is_prime(b): count = 0 n = 0 while is_prime((n**2) + (a * n) + b): count += 1 n += 1 if count > longest[0]: longest = [count, a, b] ans = longest[1] * longest[2] return ans if __name__ == "__main__": print(solution(1000, 1000))
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Infix_notation https://en.wikipedia.org/wiki/Reverse_Polish_notation https://en.wikipedia.org/wiki/Shunting-yard_algorithm """ from .balanced_parentheses import balanced_parentheses from .stack import Stack def precedence(char: str) -> int: """ Return integer value representing an operator's precedence, or order of operation. https://en.wikipedia.org/wiki/Order_of_operations """ return {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}.get(char, -1) def infix_to_postfix(expression_str: str) -> str: """ >>> infix_to_postfix("(1*(2+3)+4))") Traceback (most recent call last): ... ValueError: Mismatched parentheses >>> infix_to_postfix("") '' >>> infix_to_postfix("3+2") '3 2 +' >>> infix_to_postfix("(3+4)*5-6") '3 4 + 5 * 6 -' >>> infix_to_postfix("(1+2)*3/4-5") '1 2 + 3 * 4 / 5 -' >>> infix_to_postfix("a+b*c+(d*e+f)*g") 'a b c * + d e * f + g * +' >>> infix_to_postfix("x^y/(5*z)+2") 'x y ^ 5 z * / 2 +' """ if not balanced_parentheses(expression_str): raise ValueError("Mismatched parentheses") stack: Stack[str] = Stack() postfix = [] for char in expression_str: if char.isalpha() or char.isdigit(): postfix.append(char) elif char == "(": stack.push(char) elif char == ")": while not stack.is_empty() and stack.peek() != "(": postfix.append(stack.pop()) stack.pop() else: while not stack.is_empty() and precedence(char) <= precedence(stack.peek()): postfix.append(stack.pop()) stack.push(char) while not stack.is_empty(): postfix.append(stack.pop()) return " ".join(postfix) if __name__ == "__main__": from doctest import testmod testmod() expression = "a+b*(c^d-e)^(f+g*h)-i" print("Infix to Postfix Notation demonstration:\n") print("Infix notation: " + expression) print("Postfix notation: " + infix_to_postfix(expression))
""" https://en.wikipedia.org/wiki/Infix_notation https://en.wikipedia.org/wiki/Reverse_Polish_notation https://en.wikipedia.org/wiki/Shunting-yard_algorithm """ from .balanced_parentheses import balanced_parentheses from .stack import Stack def precedence(char: str) -> int: """ Return integer value representing an operator's precedence, or order of operation. https://en.wikipedia.org/wiki/Order_of_operations """ return {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}.get(char, -1) def infix_to_postfix(expression_str: str) -> str: """ >>> infix_to_postfix("(1*(2+3)+4))") Traceback (most recent call last): ... ValueError: Mismatched parentheses >>> infix_to_postfix("") '' >>> infix_to_postfix("3+2") '3 2 +' >>> infix_to_postfix("(3+4)*5-6") '3 4 + 5 * 6 -' >>> infix_to_postfix("(1+2)*3/4-5") '1 2 + 3 * 4 / 5 -' >>> infix_to_postfix("a+b*c+(d*e+f)*g") 'a b c * + d e * f + g * +' >>> infix_to_postfix("x^y/(5*z)+2") 'x y ^ 5 z * / 2 +' """ if not balanced_parentheses(expression_str): raise ValueError("Mismatched parentheses") stack: Stack[str] = Stack() postfix = [] for char in expression_str: if char.isalpha() or char.isdigit(): postfix.append(char) elif char == "(": stack.push(char) elif char == ")": while not stack.is_empty() and stack.peek() != "(": postfix.append(stack.pop()) stack.pop() else: while not stack.is_empty() and precedence(char) <= precedence(stack.peek()): postfix.append(stack.pop()) stack.push(char) while not stack.is_empty(): postfix.append(stack.pop()) return " ".join(postfix) if __name__ == "__main__": from doctest import testmod testmod() expression = "a+b*(c^d-e)^(f+g*h)-i" print("Infix to Postfix Notation demonstration:\n") print("Infix notation: " + expression) print("Postfix notation: " + infix_to_postfix(expression))
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Created by sarathkaul on 12/11/19 import requests def send_slack_message(message_body: str, slack_url: str) -> None: headers = {"Content-Type": "application/json"} response = requests.post(slack_url, json={"text": message_body}, headers=headers) if response.status_code != 200: raise ValueError( f"Request to slack returned an error {response.status_code}, " f"the response is:\n{response.text}" ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
# Created by sarathkaul on 12/11/19 import requests def send_slack_message(message_body: str, slack_url: str) -> None: headers = {"Content-Type": "application/json"} response = requests.post(slack_url, json={"text": message_body}, headers=headers) if response.status_code != 200: raise ValueError( f"Request to slack returned an error {response.status_code}, " f"the response is:\n{response.text}" ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def find_max(nums: list[int | float]) -> int | float: """ >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max(nums) == max(nums) True True True True >>> find_max([2, 4, 9, 7, 19, 94, 5]) 94 >>> find_max([]) Traceback (most recent call last): ... ValueError: find_max() arg is an empty sequence """ if len(nums) == 0: raise ValueError("find_max() arg is an empty sequence") max_num = nums[0] for x in nums: if x > max_num: max_num = x return max_num if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
from __future__ import annotations def find_max(nums: list[int | float]) -> int | float: """ >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max(nums) == max(nums) True True True True >>> find_max([2, 4, 9, 7, 19, 94, 5]) 94 >>> find_max([]) Traceback (most recent call last): ... ValueError: find_max() arg is an empty sequence """ if len(nums) == 0: raise ValueError("find_max() arg is an empty sequence") max_num = nums[0] for x in nums: if x > max_num: max_num = x return max_num if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Segment_tree creates a segment tree with a given array and function, allowing queries to be done later in log(N) time function takes 2 values and returns a same type value """ from collections.abc import Sequence from queue import Queue class SegmentTreeNode: def __init__(self, start, end, val, left=None, right=None): self.start = start self.end = end self.val = val self.mid = (start + end) // 2 self.left = left self.right = right def __str__(self): return f"val: {self.val}, start: {self.start}, end: {self.end}" class SegmentTree: """ >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> for node in num_arr.traverse(): ... print(node) ... val: 15, start: 0, end: 4 val: 8, start: 0, end: 2 val: 7, start: 3, end: 4 val: 3, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 1, start: 1, end: 1 >>> >>> num_arr.update(1, 5) >>> for node in num_arr.traverse(): ... print(node) ... val: 19, start: 0, end: 4 val: 12, start: 0, end: 2 val: 7, start: 3, end: 4 val: 7, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 5, start: 1, end: 1 >>> >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> >>> max_arr = SegmentTree([2, 1, 5, 3, 4], max) >>> for node in max_arr.traverse(): ... print(node) ... val: 5, start: 0, end: 4 val: 5, start: 0, end: 2 val: 4, start: 3, end: 4 val: 2, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 1, start: 1, end: 1 >>> >>> max_arr.update(1, 5) >>> for node in max_arr.traverse(): ... print(node) ... val: 5, start: 0, end: 4 val: 5, start: 0, end: 2 val: 4, start: 3, end: 4 val: 5, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 5, start: 1, end: 1 >>> >>> max_arr.query_range(3, 4) 4 >>> max_arr.query_range(2, 2) 5 >>> max_arr.query_range(1, 3) 5 >>> >>> min_arr = SegmentTree([2, 1, 5, 3, 4], min) >>> for node in min_arr.traverse(): ... print(node) ... val: 1, start: 0, end: 4 val: 1, start: 0, end: 2 val: 3, start: 3, end: 4 val: 1, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 1, start: 1, end: 1 >>> >>> min_arr.update(1, 5) >>> for node in min_arr.traverse(): ... print(node) ... val: 2, start: 0, end: 4 val: 2, start: 0, end: 2 val: 3, start: 3, end: 4 val: 2, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 5, start: 1, end: 1 >>> >>> min_arr.query_range(3, 4) 3 >>> min_arr.query_range(2, 2) 5 >>> min_arr.query_range(1, 3) 3 >>> """ def __init__(self, collection: Sequence, function): self.collection = collection self.fn = function if self.collection: self.root = self._build_tree(0, len(collection) - 1) def update(self, i, val): """ Update an element in log(N) time :param i: position to be update :param val: new value >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(1, 3) 13 """ self._update_tree(self.root, i, val) def query_range(self, i, j): """ Get range query value in log(N) time :param i: left element index :param j: right element index :return: element combined in the range [i, j] >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> """ return self._query_range(self.root, i, j) def _build_tree(self, start, end): if start == end: return SegmentTreeNode(start, end, self.collection[start]) mid = (start + end) // 2 left = self._build_tree(start, mid) right = self._build_tree(mid + 1, end) return SegmentTreeNode(start, end, self.fn(left.val, right.val), left, right) def _update_tree(self, node, i, val): if node.start == i and node.end == i: node.val = val return if i <= node.mid: self._update_tree(node.left, i, val) else: self._update_tree(node.right, i, val) node.val = self.fn(node.left.val, node.right.val) def _query_range(self, node, i, j): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left, i, j) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left, i, node.mid), self._query_range(node.right, node.mid + 1, j), ) else: # range in right child tree return self._query_range(node.right, i, j) def traverse(self): if self.root is not None: queue = Queue() queue.put(self.root) while not queue.empty(): node = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 50) arr = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
""" Segment_tree creates a segment tree with a given array and function, allowing queries to be done later in log(N) time function takes 2 values and returns a same type value """ from collections.abc import Sequence from queue import Queue class SegmentTreeNode: def __init__(self, start, end, val, left=None, right=None): self.start = start self.end = end self.val = val self.mid = (start + end) // 2 self.left = left self.right = right def __str__(self): return f"val: {self.val}, start: {self.start}, end: {self.end}" class SegmentTree: """ >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> for node in num_arr.traverse(): ... print(node) ... val: 15, start: 0, end: 4 val: 8, start: 0, end: 2 val: 7, start: 3, end: 4 val: 3, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 1, start: 1, end: 1 >>> >>> num_arr.update(1, 5) >>> for node in num_arr.traverse(): ... print(node) ... val: 19, start: 0, end: 4 val: 12, start: 0, end: 2 val: 7, start: 3, end: 4 val: 7, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 5, start: 1, end: 1 >>> >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> >>> max_arr = SegmentTree([2, 1, 5, 3, 4], max) >>> for node in max_arr.traverse(): ... print(node) ... val: 5, start: 0, end: 4 val: 5, start: 0, end: 2 val: 4, start: 3, end: 4 val: 2, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 1, start: 1, end: 1 >>> >>> max_arr.update(1, 5) >>> for node in max_arr.traverse(): ... print(node) ... val: 5, start: 0, end: 4 val: 5, start: 0, end: 2 val: 4, start: 3, end: 4 val: 5, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 5, start: 1, end: 1 >>> >>> max_arr.query_range(3, 4) 4 >>> max_arr.query_range(2, 2) 5 >>> max_arr.query_range(1, 3) 5 >>> >>> min_arr = SegmentTree([2, 1, 5, 3, 4], min) >>> for node in min_arr.traverse(): ... print(node) ... val: 1, start: 0, end: 4 val: 1, start: 0, end: 2 val: 3, start: 3, end: 4 val: 1, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 1, start: 1, end: 1 >>> >>> min_arr.update(1, 5) >>> for node in min_arr.traverse(): ... print(node) ... val: 2, start: 0, end: 4 val: 2, start: 0, end: 2 val: 3, start: 3, end: 4 val: 2, start: 0, end: 1 val: 5, start: 2, end: 2 val: 3, start: 3, end: 3 val: 4, start: 4, end: 4 val: 2, start: 0, end: 0 val: 5, start: 1, end: 1 >>> >>> min_arr.query_range(3, 4) 3 >>> min_arr.query_range(2, 2) 5 >>> min_arr.query_range(1, 3) 3 >>> """ def __init__(self, collection: Sequence, function): self.collection = collection self.fn = function if self.collection: self.root = self._build_tree(0, len(collection) - 1) def update(self, i, val): """ Update an element in log(N) time :param i: position to be update :param val: new value >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(1, 3) 13 """ self._update_tree(self.root, i, val) def query_range(self, i, j): """ Get range query value in log(N) time :param i: left element index :param j: right element index :return: element combined in the range [i, j] >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> """ return self._query_range(self.root, i, j) def _build_tree(self, start, end): if start == end: return SegmentTreeNode(start, end, self.collection[start]) mid = (start + end) // 2 left = self._build_tree(start, mid) right = self._build_tree(mid + 1, end) return SegmentTreeNode(start, end, self.fn(left.val, right.val), left, right) def _update_tree(self, node, i, val): if node.start == i and node.end == i: node.val = val return if i <= node.mid: self._update_tree(node.left, i, val) else: self._update_tree(node.right, i, val) node.val = self.fn(node.left.val, node.right.val) def _query_range(self, node, i, j): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left, i, j) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left, i, node.mid), self._query_range(node.right, node.mid + 1, j), ) else: # range in right child tree return self._query_range(node.right, i, j) def traverse(self): if self.root is not None: queue = Queue() queue.put(self.root) while not queue.empty(): node = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 50) arr = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Convert a positive Decimal Number to Any Other Representation""" def decimal_to_any(num: int, base: int) -> str: """ Convert a positive integer to another base as str. >>> decimal_to_any(0, 2) '0' >>> decimal_to_any(5, 4) '11' >>> decimal_to_any(20, 3) '202' >>> decimal_to_any(58, 16) '3A' >>> decimal_to_any(243, 17) 'E5' >>> decimal_to_any(34923, 36) 'QY3' >>> decimal_to_any(10, 11) 'A' >>> decimal_to_any(16, 16) '10' >>> decimal_to_any(36, 36) '10' >>> # negatives will error >>> decimal_to_any(-45, 8) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: parameter must be positive int >>> # floats will error >>> decimal_to_any(34.4, 6) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: int() can't convert non-string with explicit base >>> # a float base will error >>> decimal_to_any(5, 2.5) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # a str base will error >>> decimal_to_any(10, '16') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer >>> # a base less than 2 will error >>> decimal_to_any(7, 0) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be >= 2 >>> # a base greater than 36 will error >>> decimal_to_any(34, 37) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be <= 36 """ if isinstance(num, float): raise TypeError("int() can't convert non-string with explicit base") if num < 0: raise ValueError("parameter must be positive int") if isinstance(base, str): raise TypeError("'str' object cannot be interpreted as an integer") if isinstance(base, float): raise TypeError("'float' object cannot be interpreted as an integer") if base in (0, 1): raise ValueError("base must be >= 2") if base > 36: raise ValueError("base must be <= 36") # fmt: off ALPHABET_VALUES = {'10': 'A', '11': 'B', '12': 'C', '13': 'D', '14': 'E', '15': 'F', '16': 'G', '17': 'H', '18': 'I', '19': 'J', '20': 'K', '21': 'L', '22': 'M', '23': 'N', '24': 'O', '25': 'P', '26': 'Q', '27': 'R', '28': 'S', '29': 'T', '30': 'U', '31': 'V', '32': 'W', '33': 'X', '34': 'Y', '35': 'Z'} # fmt: on new_value = "" mod = 0 div = 0 while div != 1: div, mod = divmod(num, base) if base >= 11 and 9 < mod < 36: actual_value = ALPHABET_VALUES[str(mod)] mod = actual_value new_value += str(mod) div = num // base num = div if div == 0: return str(new_value[::-1]) elif div == 1: new_value += str(div) return str(new_value[::-1]) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
"""Convert a positive Decimal Number to Any Other Representation""" def decimal_to_any(num: int, base: int) -> str: """ Convert a positive integer to another base as str. >>> decimal_to_any(0, 2) '0' >>> decimal_to_any(5, 4) '11' >>> decimal_to_any(20, 3) '202' >>> decimal_to_any(58, 16) '3A' >>> decimal_to_any(243, 17) 'E5' >>> decimal_to_any(34923, 36) 'QY3' >>> decimal_to_any(10, 11) 'A' >>> decimal_to_any(16, 16) '10' >>> decimal_to_any(36, 36) '10' >>> # negatives will error >>> decimal_to_any(-45, 8) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: parameter must be positive int >>> # floats will error >>> decimal_to_any(34.4, 6) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: int() can't convert non-string with explicit base >>> # a float base will error >>> decimal_to_any(5, 2.5) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # a str base will error >>> decimal_to_any(10, '16') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer >>> # a base less than 2 will error >>> decimal_to_any(7, 0) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be >= 2 >>> # a base greater than 36 will error >>> decimal_to_any(34, 37) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be <= 36 """ if isinstance(num, float): raise TypeError("int() can't convert non-string with explicit base") if num < 0: raise ValueError("parameter must be positive int") if isinstance(base, str): raise TypeError("'str' object cannot be interpreted as an integer") if isinstance(base, float): raise TypeError("'float' object cannot be interpreted as an integer") if base in (0, 1): raise ValueError("base must be >= 2") if base > 36: raise ValueError("base must be <= 36") # fmt: off ALPHABET_VALUES = {'10': 'A', '11': 'B', '12': 'C', '13': 'D', '14': 'E', '15': 'F', '16': 'G', '17': 'H', '18': 'I', '19': 'J', '20': 'K', '21': 'L', '22': 'M', '23': 'N', '24': 'O', '25': 'P', '26': 'Q', '27': 'R', '28': 'S', '29': 'T', '30': 'U', '31': 'V', '32': 'W', '33': 'X', '34': 'Y', '35': 'Z'} # fmt: on new_value = "" mod = 0 div = 0 while div != 1: div, mod = divmod(num, base) if base >= 11 and 9 < mod < 36: actual_value = ALPHABET_VALUES[str(mod)] mod = actual_value new_value += str(mod) div = num // base num = div if div == 0: return str(new_value[::-1]) elif div == 1: new_value += str(div) return str(new_value[::-1]) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def bin_to_hexadecimal(binary_str: str) -> str: """ Converting a binary string into hexadecimal using Grouping Method >>> bin_to_hexadecimal('101011111') '0x15f' >>> bin_to_hexadecimal(' 1010 ') '0x0a' >>> bin_to_hexadecimal('-11101') '-0x1d' >>> bin_to_hexadecimal('a') Traceback (most recent call last): ... ValueError: Non-binary value was passed to the function >>> bin_to_hexadecimal('') Traceback (most recent call last): ... ValueError: Empty string was passed to the function """ BITS_TO_HEX = { "0000": "0", "0001": "1", "0010": "2", "0011": "3", "0100": "4", "0101": "5", "0110": "6", "0111": "7", "1000": "8", "1001": "9", "1010": "a", "1011": "b", "1100": "c", "1101": "d", "1110": "e", "1111": "f", } # Sanitising parameter binary_str = str(binary_str).strip() # Exceptions if not binary_str: raise ValueError("Empty string was passed to the function") is_negative = binary_str[0] == "-" binary_str = binary_str[1:] if is_negative else binary_str if not all(char in "01" for char in binary_str): raise ValueError("Non-binary value was passed to the function") binary_str = ( "0" * (4 * (divmod(len(binary_str), 4)[0] + 1) - len(binary_str)) + binary_str ) hexadecimal = [] for x in range(0, len(binary_str), 4): hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]]) hexadecimal_str = "0x" + "".join(hexadecimal) return "-" + hexadecimal_str if is_negative else hexadecimal_str if __name__ == "__main__": from doctest import testmod testmod()
def bin_to_hexadecimal(binary_str: str) -> str: """ Converting a binary string into hexadecimal using Grouping Method >>> bin_to_hexadecimal('101011111') '0x15f' >>> bin_to_hexadecimal(' 1010 ') '0x0a' >>> bin_to_hexadecimal('-11101') '-0x1d' >>> bin_to_hexadecimal('a') Traceback (most recent call last): ... ValueError: Non-binary value was passed to the function >>> bin_to_hexadecimal('') Traceback (most recent call last): ... ValueError: Empty string was passed to the function """ BITS_TO_HEX = { "0000": "0", "0001": "1", "0010": "2", "0011": "3", "0100": "4", "0101": "5", "0110": "6", "0111": "7", "1000": "8", "1001": "9", "1010": "a", "1011": "b", "1100": "c", "1101": "d", "1110": "e", "1111": "f", } # Sanitising parameter binary_str = str(binary_str).strip() # Exceptions if not binary_str: raise ValueError("Empty string was passed to the function") is_negative = binary_str[0] == "-" binary_str = binary_str[1:] if is_negative else binary_str if not all(char in "01" for char in binary_str): raise ValueError("Non-binary value was passed to the function") binary_str = ( "0" * (4 * (divmod(len(binary_str), 4)[0] + 1) - len(binary_str)) + binary_str ) hexadecimal = [] for x in range(0, len(binary_str), 4): hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]]) hexadecimal_str = "0x" + "".join(hexadecimal) return "-" + hexadecimal_str if is_negative else hexadecimal_str if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" 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,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This module provides two implementations for the rod-cutting problem: 1. A naive recursive implementation which has an exponential runtime 2. Two dynamic programming implementations which have quadratic runtime The rod-cutting problem is the problem of finding the maximum possible revenue obtainable from a rod of length ``n`` given a list of prices for each integral piece of the rod. The maximum revenue can thus be obtained by cutting the rod and selling the pieces separately or not cutting it at all if the price of it is the maximum obtainable. """ def naive_cut_rod_recursive(n: int, prices: list): """ Solves the rod-cutting problem via naively without using the benefit of dynamic programming. The results is the same sub-problems are solved several times leading to an exponential runtime Runtime: O(2^n) Arguments ------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples -------- >>> naive_cut_rod_recursive(4, [1, 5, 8, 9]) 10 >>> naive_cut_rod_recursive(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) if n == 0: return 0 max_revue = float("-inf") for i in range(1, n + 1): max_revue = max( max_revue, prices[i - 1] + naive_cut_rod_recursive(n - i, prices) ) return max_revue def top_down_cut_rod(n: int, prices: list): """ Constructs a top-down dynamic programming solution for the rod-cutting problem via memoization. This function serves as a wrapper for _top_down_cut_rod_recursive Runtime: O(n^2) Arguments -------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Note ---- For convenience and because Python's lists using 0-indexing, length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of length 0. Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples ------- >>> top_down_cut_rod(4, [1, 5, 8, 9]) 10 >>> top_down_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) max_rev = [float("-inf") for _ in range(n + 1)] return _top_down_cut_rod_recursive(n, prices, max_rev) def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list): """ Constructs a top-down dynamic programming solution for the rod-cutting problem via memoization. Runtime: O(n^2) Arguments -------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` max_rev: list, the computed maximum revenue for a piece of rod. ``max_rev[i]`` is the maximum revenue obtainable for a rod of length ``i`` Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. """ if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: max_revenue = float("-inf") for i in range(1, n + 1): max_revenue = max( max_revenue, prices[i - 1] + _top_down_cut_rod_recursive(n - i, prices, max_rev), ) max_rev[n] = max_revenue return max_rev[n] def bottom_up_cut_rod(n: int, prices: list): """ Constructs a bottom-up dynamic programming solution for the rod-cutting problem Runtime: O(n^2) Arguments ---------- n: int, the maximum length of the rod. prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Returns ------- The maximum revenue obtainable from cutting a rod of length n given the prices for each piece of rod p. Examples ------- >>> bottom_up_cut_rod(4, [1, 5, 8, 9]) 10 >>> bottom_up_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. max_rev = [float("-inf") for _ in range(n + 1)] max_rev[0] = 0 for i in range(1, n + 1): max_revenue_i = max_rev[i] for j in range(1, i + 1): max_revenue_i = max(max_revenue_i, prices[j - 1] + max_rev[i - j]) max_rev[i] = max_revenue_i return max_rev[n] def _enforce_args(n: int, prices: list): """ Basic checks on the arguments to the rod-cutting algorithms n: int, the length of the rod prices: list, the price list for each piece of rod. Throws ValueError: if n is negative or there are fewer items in the price list than the length of the rod """ if n < 0: raise ValueError(f"n must be greater than or equal to 0. Got n = {n}") if n > len(prices): raise ValueError( "Each integral piece of rod must have a corresponding " f"price. Got n = {n} but length of prices = {len(prices)}" ) def main(): prices = [6, 10, 12, 15, 20, 23] n = len(prices) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. expected_max_revenue = 36 max_rev_top_down = top_down_cut_rod(n, prices) max_rev_bottom_up = bottom_up_cut_rod(n, prices) max_rev_naive = naive_cut_rod_recursive(n, prices) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
""" This module provides two implementations for the rod-cutting problem: 1. A naive recursive implementation which has an exponential runtime 2. Two dynamic programming implementations which have quadratic runtime The rod-cutting problem is the problem of finding the maximum possible revenue obtainable from a rod of length ``n`` given a list of prices for each integral piece of the rod. The maximum revenue can thus be obtained by cutting the rod and selling the pieces separately or not cutting it at all if the price of it is the maximum obtainable. """ def naive_cut_rod_recursive(n: int, prices: list): """ Solves the rod-cutting problem via naively without using the benefit of dynamic programming. The results is the same sub-problems are solved several times leading to an exponential runtime Runtime: O(2^n) Arguments ------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples -------- >>> naive_cut_rod_recursive(4, [1, 5, 8, 9]) 10 >>> naive_cut_rod_recursive(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) if n == 0: return 0 max_revue = float("-inf") for i in range(1, n + 1): max_revue = max( max_revue, prices[i - 1] + naive_cut_rod_recursive(n - i, prices) ) return max_revue def top_down_cut_rod(n: int, prices: list): """ Constructs a top-down dynamic programming solution for the rod-cutting problem via memoization. This function serves as a wrapper for _top_down_cut_rod_recursive Runtime: O(n^2) Arguments -------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Note ---- For convenience and because Python's lists using 0-indexing, length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of length 0. Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples ------- >>> top_down_cut_rod(4, [1, 5, 8, 9]) 10 >>> top_down_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) max_rev = [float("-inf") for _ in range(n + 1)] return _top_down_cut_rod_recursive(n, prices, max_rev) def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list): """ Constructs a top-down dynamic programming solution for the rod-cutting problem via memoization. Runtime: O(n^2) Arguments -------- n: int, the length of the rod prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` max_rev: list, the computed maximum revenue for a piece of rod. ``max_rev[i]`` is the maximum revenue obtainable for a rod of length ``i`` Returns ------- The maximum revenue obtainable for a rod of length n given the list of prices for each piece. """ if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: max_revenue = float("-inf") for i in range(1, n + 1): max_revenue = max( max_revenue, prices[i - 1] + _top_down_cut_rod_recursive(n - i, prices, max_rev), ) max_rev[n] = max_revenue return max_rev[n] def bottom_up_cut_rod(n: int, prices: list): """ Constructs a bottom-up dynamic programming solution for the rod-cutting problem Runtime: O(n^2) Arguments ---------- n: int, the maximum length of the rod. prices: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i`` Returns ------- The maximum revenue obtainable from cutting a rod of length n given the prices for each piece of rod p. Examples ------- >>> bottom_up_cut_rod(4, [1, 5, 8, 9]) 10 >>> bottom_up_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) 30 """ _enforce_args(n, prices) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. max_rev = [float("-inf") for _ in range(n + 1)] max_rev[0] = 0 for i in range(1, n + 1): max_revenue_i = max_rev[i] for j in range(1, i + 1): max_revenue_i = max(max_revenue_i, prices[j - 1] + max_rev[i - j]) max_rev[i] = max_revenue_i return max_rev[n] def _enforce_args(n: int, prices: list): """ Basic checks on the arguments to the rod-cutting algorithms n: int, the length of the rod prices: list, the price list for each piece of rod. Throws ValueError: if n is negative or there are fewer items in the price list than the length of the rod """ if n < 0: raise ValueError(f"n must be greater than or equal to 0. Got n = {n}") if n > len(prices): raise ValueError( "Each integral piece of rod must have a corresponding " f"price. Got n = {n} but length of prices = {len(prices)}" ) def main(): prices = [6, 10, 12, 15, 20, 23] n = len(prices) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. expected_max_revenue = 36 max_rev_top_down = top_down_cut_rod(n, prices) max_rev_bottom_up = bottom_up_cut_rod(n, prices) max_rev_naive = naive_cut_rod_recursive(n, prices) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Based on "Skip Lists: A Probabilistic Alternative to Balanced Trees" by William Pugh https://epaperpress.com/sortsearch/download/skiplist.pdf """ from __future__ import annotations from random import random from typing import Generic, TypeVar KT = TypeVar("KT") VT = TypeVar("VT") class Node(Generic[KT, VT]): def __init__(self, key: KT | str = "root", value: VT | None = None): self.key = key self.value = value self.forward: list[Node[KT, VT]] = [] def __repr__(self) -> str: """ :return: Visual representation of Node >>> node = Node("Key", 2) >>> repr(node) 'Node(Key: 2)' """ return f"Node({self.key}: {self.value})" @property def level(self) -> int: """ :return: Number of forward references >>> node = Node("Key", 2) >>> node.level 0 >>> node.forward.append(Node("Key2", 4)) >>> node.level 1 >>> node.forward.append(Node("Key3", 6)) >>> node.level 2 """ return len(self.forward) class SkipList(Generic[KT, VT]): def __init__(self, p: float = 0.5, max_level: int = 16): self.head: Node[KT, VT] = Node[KT, VT]() self.level = 0 self.p = p self.max_level = max_level def __str__(self) -> str: """ :return: Visual representation of SkipList >>> skip_list = SkipList() >>> print(skip_list) SkipList(level=0) >>> skip_list.insert("Key1", "Value") >>> print(skip_list) # doctest: +ELLIPSIS SkipList(level=... [root]--... [Key1]--Key1... None *... >>> skip_list.insert("Key2", "OtherValue") >>> print(skip_list) # doctest: +ELLIPSIS SkipList(level=... [root]--... [Key1]--Key1... [Key2]--Key2... None *... """ items = list(self) if len(items) == 0: return f"SkipList(level={self.level})" label_size = max((len(str(item)) for item in items), default=4) label_size = max(label_size, 4) + 4 node = self.head lines = [] forwards = node.forward.copy() lines.append(f"[{node.key}]".ljust(label_size, "-") + "* " * len(forwards)) lines.append(" " * label_size + "| " * len(forwards)) while len(node.forward) != 0: node = node.forward[0] lines.append( f"[{node.key}]".ljust(label_size, "-") + " ".join(str(n.key) if n.key == node.key else "|" for n in forwards) ) lines.append(" " * label_size + "| " * len(forwards)) forwards[: node.level] = node.forward lines.append("None".ljust(label_size) + "* " * len(forwards)) return f"SkipList(level={self.level})\n" + "\n".join(lines) def __iter__(self): node = self.head while len(node.forward) != 0: yield node.forward[0].key node = node.forward[0] def random_level(self) -> int: """ :return: Random level from [1, self.max_level] interval. Higher values are less likely. """ level = 1 while random() < self.p and level < self.max_level: level += 1 return level def _locate_node(self, key) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: """ :param key: Searched key, :return: Tuple with searched node (or None if given key is not present) and list of nodes that refer (if key is present) of should refer to given node. """ # Nodes with refer or should refer to output node update_vector = [] node = self.head for i in reversed(range(self.level)): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: node = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(node) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def delete(self, key: KT): """ :param key: Key to remove from list. >>> skip_list = SkipList() >>> skip_list.insert(2, "Two") >>> skip_list.insert(1, "One") >>> skip_list.insert(3, "Three") >>> list(skip_list) [1, 2, 3] >>> skip_list.delete(2) >>> list(skip_list) [1, 3] """ node, update_vector = self._locate_node(key) if node is not None: for i, update_node in enumerate(update_vector): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: update_node.forward[i] = node.forward[i] else: update_node.forward = update_node.forward[:i] def insert(self, key: KT, value: VT): """ :param key: Key to insert. :param value: Value associated with given key. >>> skip_list = SkipList() >>> skip_list.insert(2, "Two") >>> skip_list.find(2) 'Two' >>> list(skip_list) [2] """ node, update_vector = self._locate_node(key) if node is not None: node.value = value else: level = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for i in range(self.level - 1, level): update_vector.append(self.head) self.level = level new_node = Node(key, value) for i, update_node in enumerate(update_vector[:level]): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i]) if update_node.level < i + 1: update_node.forward.append(new_node) else: update_node.forward[i] = new_node def find(self, key: VT) -> VT | None: """ :param key: Search key. :return: Value associated with given key or None if given key is not present. >>> skip_list = SkipList() >>> skip_list.find(2) >>> skip_list.insert(2, "Two") >>> skip_list.find(2) 'Two' >>> skip_list.insert(2, "Three") >>> skip_list.find(2) 'Three' """ node, _ = self._locate_node(key) if node is not None: return node.value return None def test_insert(): skip_list = SkipList() skip_list.insert("Key1", 3) skip_list.insert("Key2", 12) skip_list.insert("Key3", 41) skip_list.insert("Key4", -19) node = skip_list.head all_values = {} while node.level != 0: node = node.forward[0] all_values[node.key] = node.value assert len(all_values) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def test_insert_overrides_existing_value(): skip_list = SkipList() skip_list.insert("Key1", 10) skip_list.insert("Key1", 12) skip_list.insert("Key5", 7) skip_list.insert("Key7", 10) skip_list.insert("Key10", 5) skip_list.insert("Key7", 7) skip_list.insert("Key5", 5) skip_list.insert("Key10", 10) node = skip_list.head all_values = {} while node.level != 0: node = node.forward[0] all_values[node.key] = node.value if len(all_values) != 4: print() assert len(all_values) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def test_searching_empty_list_returns_none(): skip_list = SkipList() assert skip_list.find("Some key") is None def test_search(): skip_list = SkipList() skip_list.insert("Key2", 20) assert skip_list.find("Key2") == 20 skip_list.insert("Some Key", 10) skip_list.insert("Key2", 8) skip_list.insert("V", 13) assert skip_list.find("Y") is None assert skip_list.find("Key2") == 8 assert skip_list.find("Some Key") == 10 assert skip_list.find("V") == 13 def test_deleting_item_from_empty_list_do_nothing(): skip_list = SkipList() skip_list.delete("Some key") assert len(skip_list.head.forward) == 0 def test_deleted_items_are_not_founded_by_find_method(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 14) skip_list.insert("Key2", 15) skip_list.delete("V") skip_list.delete("Key2") assert skip_list.find("V") is None assert skip_list.find("Key2") is None def test_delete_removes_only_given_key(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 14) skip_list.insert("Key2", 15) skip_list.delete("V") assert skip_list.find("V") is None assert skip_list.find("X") == 14 assert skip_list.find("Key1") == 12 assert skip_list.find("Key2") == 15 skip_list.delete("X") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") == 12 assert skip_list.find("Key2") == 15 skip_list.delete("Key1") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") is None assert skip_list.find("Key2") == 15 skip_list.delete("Key2") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") is None assert skip_list.find("Key2") is None def test_delete_doesnt_leave_dead_nodes(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 142) skip_list.insert("Key2", 15) skip_list.delete("X") def traverse_keys(node): yield node.key for forward_node in node.forward: yield from traverse_keys(forward_node) assert len(set(traverse_keys(skip_list.head))) == 4 def test_iter_always_yields_sorted_values(): def is_sorted(lst): for item, next_item in zip(lst, lst[1:]): if next_item < item: return False return True skip_list = SkipList() for i in range(10): skip_list.insert(i, i) assert is_sorted(list(skip_list)) skip_list.delete(5) skip_list.delete(8) skip_list.delete(2) assert is_sorted(list(skip_list)) skip_list.insert(-12, -12) skip_list.insert(77, 77) assert is_sorted(list(skip_list)) def pytests(): for i in range(100): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def main(): """ >>> pytests() """ skip_list = SkipList() skip_list.insert(2, "2") skip_list.insert(4, "4") skip_list.insert(6, "4") skip_list.insert(4, "5") skip_list.insert(8, "4") skip_list.insert(9, "4") skip_list.delete(4) print(skip_list) if __name__ == "__main__": main()
""" Based on "Skip Lists: A Probabilistic Alternative to Balanced Trees" by William Pugh https://epaperpress.com/sortsearch/download/skiplist.pdf """ from __future__ import annotations from random import random from typing import Generic, TypeVar KT = TypeVar("KT") VT = TypeVar("VT") class Node(Generic[KT, VT]): def __init__(self, key: KT | str = "root", value: VT | None = None): self.key = key self.value = value self.forward: list[Node[KT, VT]] = [] def __repr__(self) -> str: """ :return: Visual representation of Node >>> node = Node("Key", 2) >>> repr(node) 'Node(Key: 2)' """ return f"Node({self.key}: {self.value})" @property def level(self) -> int: """ :return: Number of forward references >>> node = Node("Key", 2) >>> node.level 0 >>> node.forward.append(Node("Key2", 4)) >>> node.level 1 >>> node.forward.append(Node("Key3", 6)) >>> node.level 2 """ return len(self.forward) class SkipList(Generic[KT, VT]): def __init__(self, p: float = 0.5, max_level: int = 16): self.head: Node[KT, VT] = Node[KT, VT]() self.level = 0 self.p = p self.max_level = max_level def __str__(self) -> str: """ :return: Visual representation of SkipList >>> skip_list = SkipList() >>> print(skip_list) SkipList(level=0) >>> skip_list.insert("Key1", "Value") >>> print(skip_list) # doctest: +ELLIPSIS SkipList(level=... [root]--... [Key1]--Key1... None *... >>> skip_list.insert("Key2", "OtherValue") >>> print(skip_list) # doctest: +ELLIPSIS SkipList(level=... [root]--... [Key1]--Key1... [Key2]--Key2... None *... """ items = list(self) if len(items) == 0: return f"SkipList(level={self.level})" label_size = max((len(str(item)) for item in items), default=4) label_size = max(label_size, 4) + 4 node = self.head lines = [] forwards = node.forward.copy() lines.append(f"[{node.key}]".ljust(label_size, "-") + "* " * len(forwards)) lines.append(" " * label_size + "| " * len(forwards)) while len(node.forward) != 0: node = node.forward[0] lines.append( f"[{node.key}]".ljust(label_size, "-") + " ".join(str(n.key) if n.key == node.key else "|" for n in forwards) ) lines.append(" " * label_size + "| " * len(forwards)) forwards[: node.level] = node.forward lines.append("None".ljust(label_size) + "* " * len(forwards)) return f"SkipList(level={self.level})\n" + "\n".join(lines) def __iter__(self): node = self.head while len(node.forward) != 0: yield node.forward[0].key node = node.forward[0] def random_level(self) -> int: """ :return: Random level from [1, self.max_level] interval. Higher values are less likely. """ level = 1 while random() < self.p and level < self.max_level: level += 1 return level def _locate_node(self, key) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: """ :param key: Searched key, :return: Tuple with searched node (or None if given key is not present) and list of nodes that refer (if key is present) of should refer to given node. """ # Nodes with refer or should refer to output node update_vector = [] node = self.head for i in reversed(range(self.level)): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: node = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(node) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def delete(self, key: KT): """ :param key: Key to remove from list. >>> skip_list = SkipList() >>> skip_list.insert(2, "Two") >>> skip_list.insert(1, "One") >>> skip_list.insert(3, "Three") >>> list(skip_list) [1, 2, 3] >>> skip_list.delete(2) >>> list(skip_list) [1, 3] """ node, update_vector = self._locate_node(key) if node is not None: for i, update_node in enumerate(update_vector): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: update_node.forward[i] = node.forward[i] else: update_node.forward = update_node.forward[:i] def insert(self, key: KT, value: VT): """ :param key: Key to insert. :param value: Value associated with given key. >>> skip_list = SkipList() >>> skip_list.insert(2, "Two") >>> skip_list.find(2) 'Two' >>> list(skip_list) [2] """ node, update_vector = self._locate_node(key) if node is not None: node.value = value else: level = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for i in range(self.level - 1, level): update_vector.append(self.head) self.level = level new_node = Node(key, value) for i, update_node in enumerate(update_vector[:level]): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i]) if update_node.level < i + 1: update_node.forward.append(new_node) else: update_node.forward[i] = new_node def find(self, key: VT) -> VT | None: """ :param key: Search key. :return: Value associated with given key or None if given key is not present. >>> skip_list = SkipList() >>> skip_list.find(2) >>> skip_list.insert(2, "Two") >>> skip_list.find(2) 'Two' >>> skip_list.insert(2, "Three") >>> skip_list.find(2) 'Three' """ node, _ = self._locate_node(key) if node is not None: return node.value return None def test_insert(): skip_list = SkipList() skip_list.insert("Key1", 3) skip_list.insert("Key2", 12) skip_list.insert("Key3", 41) skip_list.insert("Key4", -19) node = skip_list.head all_values = {} while node.level != 0: node = node.forward[0] all_values[node.key] = node.value assert len(all_values) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def test_insert_overrides_existing_value(): skip_list = SkipList() skip_list.insert("Key1", 10) skip_list.insert("Key1", 12) skip_list.insert("Key5", 7) skip_list.insert("Key7", 10) skip_list.insert("Key10", 5) skip_list.insert("Key7", 7) skip_list.insert("Key5", 5) skip_list.insert("Key10", 10) node = skip_list.head all_values = {} while node.level != 0: node = node.forward[0] all_values[node.key] = node.value if len(all_values) != 4: print() assert len(all_values) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def test_searching_empty_list_returns_none(): skip_list = SkipList() assert skip_list.find("Some key") is None def test_search(): skip_list = SkipList() skip_list.insert("Key2", 20) assert skip_list.find("Key2") == 20 skip_list.insert("Some Key", 10) skip_list.insert("Key2", 8) skip_list.insert("V", 13) assert skip_list.find("Y") is None assert skip_list.find("Key2") == 8 assert skip_list.find("Some Key") == 10 assert skip_list.find("V") == 13 def test_deleting_item_from_empty_list_do_nothing(): skip_list = SkipList() skip_list.delete("Some key") assert len(skip_list.head.forward) == 0 def test_deleted_items_are_not_founded_by_find_method(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 14) skip_list.insert("Key2", 15) skip_list.delete("V") skip_list.delete("Key2") assert skip_list.find("V") is None assert skip_list.find("Key2") is None def test_delete_removes_only_given_key(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 14) skip_list.insert("Key2", 15) skip_list.delete("V") assert skip_list.find("V") is None assert skip_list.find("X") == 14 assert skip_list.find("Key1") == 12 assert skip_list.find("Key2") == 15 skip_list.delete("X") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") == 12 assert skip_list.find("Key2") == 15 skip_list.delete("Key1") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") is None assert skip_list.find("Key2") == 15 skip_list.delete("Key2") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") is None assert skip_list.find("Key2") is None def test_delete_doesnt_leave_dead_nodes(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 142) skip_list.insert("Key2", 15) skip_list.delete("X") def traverse_keys(node): yield node.key for forward_node in node.forward: yield from traverse_keys(forward_node) assert len(set(traverse_keys(skip_list.head))) == 4 def test_iter_always_yields_sorted_values(): def is_sorted(lst): for item, next_item in zip(lst, lst[1:]): if next_item < item: return False return True skip_list = SkipList() for i in range(10): skip_list.insert(i, i) assert is_sorted(list(skip_list)) skip_list.delete(5) skip_list.delete(8) skip_list.delete(2) assert is_sorted(list(skip_list)) skip_list.insert(-12, -12) skip_list.insert(77, 77) assert is_sorted(list(skip_list)) def pytests(): for i in range(100): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def main(): """ >>> pytests() """ skip_list = SkipList() skip_list.insert(2, "2") skip_list.insert(4, "4") skip_list.insert(6, "4") skip_list.insert(4, "5") skip_list.insert(8, "4") skip_list.insert(9, "4") skip_list.delete(4) print(skip_list) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def min_path_sum(grid: list) -> int: """ Find the path from top left to bottom right of array of numbers with the lowest possible sum and return the sum along this path. >>> min_path_sum([ ... [1, 3, 1], ... [1, 5, 1], ... [4, 2, 1], ... ]) 7 >>> min_path_sum([ ... [1, 0, 5, 6, 7], ... [8, 9, 0, 4, 2], ... [4, 4, 4, 5, 1], ... [9, 6, 3, 1, 0], ... [8, 4, 3, 2, 7], ... ]) 20 >>> min_path_sum(None) Traceback (most recent call last): ... TypeError: The grid does not contain the appropriate information >>> min_path_sum([[]]) Traceback (most recent call last): ... TypeError: The grid does not contain the appropriate information """ if not grid or not grid[0]: raise TypeError("The grid does not contain the appropriate information") for cell_n in range(1, len(grid[0])): grid[0][cell_n] += grid[0][cell_n - 1] row_above = grid[0] for row_n in range(1, len(grid)): current_row = grid[row_n] grid[row_n] = fill_row(current_row, row_above) row_above = grid[row_n] return grid[-1][-1] def fill_row(current_row: list, row_above: list) -> list: """ >>> fill_row([2, 2, 2], [1, 2, 3]) [3, 4, 5] """ current_row[0] += row_above[0] for cell_n in range(1, len(current_row)): current_row[cell_n] += min(current_row[cell_n - 1], row_above[cell_n]) return current_row if __name__ == "__main__": import doctest doctest.testmod()
def min_path_sum(grid: list) -> int: """ Find the path from top left to bottom right of array of numbers with the lowest possible sum and return the sum along this path. >>> min_path_sum([ ... [1, 3, 1], ... [1, 5, 1], ... [4, 2, 1], ... ]) 7 >>> min_path_sum([ ... [1, 0, 5, 6, 7], ... [8, 9, 0, 4, 2], ... [4, 4, 4, 5, 1], ... [9, 6, 3, 1, 0], ... [8, 4, 3, 2, 7], ... ]) 20 >>> min_path_sum(None) Traceback (most recent call last): ... TypeError: The grid does not contain the appropriate information >>> min_path_sum([[]]) Traceback (most recent call last): ... TypeError: The grid does not contain the appropriate information """ if not grid or not grid[0]: raise TypeError("The grid does not contain the appropriate information") for cell_n in range(1, len(grid[0])): grid[0][cell_n] += grid[0][cell_n - 1] row_above = grid[0] for row_n in range(1, len(grid)): current_row = grid[row_n] grid[row_n] = fill_row(current_row, row_above) row_above = grid[row_n] return grid[-1][-1] def fill_row(current_row: list, row_above: list) -> list: """ >>> fill_row([2, 2, 2], [1, 2, 3]) [3, 4, 5] """ current_row[0] += row_above[0] for cell_n in range(1, len(current_row)): current_row[cell_n] += min(current_row[cell_n - 1], row_above[cell_n]) return current_row if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 89: https://projecteuler.net/problem=89 For a number written in Roman numerals to be considered valid there are basic rules which must be followed. Even though the rules allow some numbers to be expressed in more than one way there is always a "best" way of writing a particular number. For example, it would appear that there are at least six ways of writing the number sixteen: IIIIIIIIIIIIIIII VIIIIIIIIIII VVIIIIII XIIIIII VVVI XVI However, according to the rules only XIIIIII and XVI are valid, and the last example is considered to be the most efficient, as it uses the least number of numerals. The 11K text file, roman.txt (right click and 'Save Link/Target As...'), contains one thousand numbers written in valid, but not necessarily minimal, Roman numerals; see About... Roman Numerals for the definitive rules for this problem. Find the number of characters saved by writing each of these in their minimal form. Note: You can assume that all the Roman numerals in the file contain no more than four consecutive identical units. """ import os SYMBOLS = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def parse_roman_numerals(numerals: str) -> int: """ Converts a string of roman numerals to an integer. e.g. >>> parse_roman_numerals("LXXXIX") 89 >>> parse_roman_numerals("IIII") 4 """ total_value = 0 index = 0 while index < len(numerals) - 1: current_value = SYMBOLS[numerals[index]] next_value = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def generate_roman_numerals(num: int) -> str: """ Generates a string of roman numerals for a given integer. e.g. >>> generate_roman_numerals(89) 'LXXXIX' >>> generate_roman_numerals(4) 'IV' """ numerals = "" m_count = num // 1000 numerals += m_count * "M" num %= 1000 c_count = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 x_count = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int: """ Calculates and returns the answer to project euler problem 89. >>> solution("/numeralcleanup_test.txt") 16 """ savings = 0 file1 = open(os.path.dirname(__file__) + roman_numerals_filename) lines = file1.readlines() for line in lines: original = line.strip() num = parse_roman_numerals(original) shortened = generate_roman_numerals(num) savings += len(original) - len(shortened) return savings if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 89: https://projecteuler.net/problem=89 For a number written in Roman numerals to be considered valid there are basic rules which must be followed. Even though the rules allow some numbers to be expressed in more than one way there is always a "best" way of writing a particular number. For example, it would appear that there are at least six ways of writing the number sixteen: IIIIIIIIIIIIIIII VIIIIIIIIIII VVIIIIII XIIIIII VVVI XVI However, according to the rules only XIIIIII and XVI are valid, and the last example is considered to be the most efficient, as it uses the least number of numerals. The 11K text file, roman.txt (right click and 'Save Link/Target As...'), contains one thousand numbers written in valid, but not necessarily minimal, Roman numerals; see About... Roman Numerals for the definitive rules for this problem. Find the number of characters saved by writing each of these in their minimal form. Note: You can assume that all the Roman numerals in the file contain no more than four consecutive identical units. """ import os SYMBOLS = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def parse_roman_numerals(numerals: str) -> int: """ Converts a string of roman numerals to an integer. e.g. >>> parse_roman_numerals("LXXXIX") 89 >>> parse_roman_numerals("IIII") 4 """ total_value = 0 index = 0 while index < len(numerals) - 1: current_value = SYMBOLS[numerals[index]] next_value = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def generate_roman_numerals(num: int) -> str: """ Generates a string of roman numerals for a given integer. e.g. >>> generate_roman_numerals(89) 'LXXXIX' >>> generate_roman_numerals(4) 'IV' """ numerals = "" m_count = num // 1000 numerals += m_count * "M" num %= 1000 c_count = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 x_count = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int: """ Calculates and returns the answer to project euler problem 89. >>> solution("/numeralcleanup_test.txt") 16 """ savings = 0 file1 = open(os.path.dirname(__file__) + roman_numerals_filename) lines = file1.readlines() for line in lines: original = line.strip() num = parse_roman_numerals(original) shortened = generate_roman_numerals(num) savings += len(original) - len(shortened) return savings if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 205: https://projecteuler.net/problem=205 Peter has nine four-sided (pyramidal) dice, each with faces numbered 1, 2, 3, 4. Colin has six six-sided (cubic) dice, each with faces numbered 1, 2, 3, 4, 5, 6. Peter and Colin roll their dice and compare totals: the highest total wins. The result is a draw if the totals are equal. What is the probability that Pyramidal Peter beats Cubic Colin? Give your answer rounded to seven decimal places in the form 0.abcdefg """ from itertools import product def total_frequency_distribution(sides_number: int, dice_number: int) -> list[int]: """ Returns frequency distribution of total >>> total_frequency_distribution(sides_number=6, dice_number=1) [0, 1, 1, 1, 1, 1, 1] >>> total_frequency_distribution(sides_number=4, dice_number=2) [0, 0, 1, 2, 3, 4, 3, 2, 1] """ max_face_number = sides_number max_total = max_face_number * dice_number totals_frequencies = [0] * (max_total + 1) min_face_number = 1 faces_numbers = range(min_face_number, max_face_number + 1) for dice_numbers in product(faces_numbers, repeat=dice_number): total = sum(dice_numbers) totals_frequencies[total] += 1 return totals_frequencies def solution() -> float: """ Returns probability that Pyramidal Peter beats Cubic Colin rounded to seven decimal places in the form 0.abcdefg >>> solution() 0.5731441 """ peter_totals_frequencies = total_frequency_distribution( sides_number=4, dice_number=9 ) colin_totals_frequencies = total_frequency_distribution( sides_number=6, dice_number=6 ) peter_wins_count = 0 min_peter_total = 9 max_peter_total = 4 * 9 min_colin_total = 6 for peter_total in range(min_peter_total, max_peter_total + 1): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) total_games_number = (4**9) * (6**6) peter_win_probability = peter_wins_count / total_games_number rounded_peter_win_probability = round(peter_win_probability, ndigits=7) return rounded_peter_win_probability if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 205: https://projecteuler.net/problem=205 Peter has nine four-sided (pyramidal) dice, each with faces numbered 1, 2, 3, 4. Colin has six six-sided (cubic) dice, each with faces numbered 1, 2, 3, 4, 5, 6. Peter and Colin roll their dice and compare totals: the highest total wins. The result is a draw if the totals are equal. What is the probability that Pyramidal Peter beats Cubic Colin? Give your answer rounded to seven decimal places in the form 0.abcdefg """ from itertools import product def total_frequency_distribution(sides_number: int, dice_number: int) -> list[int]: """ Returns frequency distribution of total >>> total_frequency_distribution(sides_number=6, dice_number=1) [0, 1, 1, 1, 1, 1, 1] >>> total_frequency_distribution(sides_number=4, dice_number=2) [0, 0, 1, 2, 3, 4, 3, 2, 1] """ max_face_number = sides_number max_total = max_face_number * dice_number totals_frequencies = [0] * (max_total + 1) min_face_number = 1 faces_numbers = range(min_face_number, max_face_number + 1) for dice_numbers in product(faces_numbers, repeat=dice_number): total = sum(dice_numbers) totals_frequencies[total] += 1 return totals_frequencies def solution() -> float: """ Returns probability that Pyramidal Peter beats Cubic Colin rounded to seven decimal places in the form 0.abcdefg >>> solution() 0.5731441 """ peter_totals_frequencies = total_frequency_distribution( sides_number=4, dice_number=9 ) colin_totals_frequencies = total_frequency_distribution( sides_number=6, dice_number=6 ) peter_wins_count = 0 min_peter_total = 9 max_peter_total = 4 * 9 min_colin_total = 6 for peter_total in range(min_peter_total, max_peter_total + 1): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) total_games_number = (4**9) * (6**6) peter_win_probability = peter_wins_count / total_games_number rounded_peter_win_probability = round(peter_win_probability, ndigits=7) return rounded_peter_win_probability if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Slowsort is a sorting algorithm. It is of humorous nature and not useful. It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer. It was published in 1986 by Andrei Broder and Jorge Stolfi in their paper Pessimal Algorithms and Simplexity Analysis (a parody of optimal algorithms and complexity analysis). Source: https://en.wikipedia.org/wiki/Slowsort """ from __future__ import annotations def slowsort(sequence: list, start: int | None = None, end: int | None = None) -> None: """ Sorts sequence[start..end] (both inclusive) in-place. start defaults to 0 if not given. end defaults to len(sequence) - 1 if not given. It returns None. >>> seq = [1, 6, 2, 5, 3, 4, 4, 5]; slowsort(seq); seq [1, 2, 3, 4, 4, 5, 5, 6] >>> seq = []; slowsort(seq); seq [] >>> seq = [2]; slowsort(seq); seq [2] >>> seq = [1, 2, 3, 4]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [4, 3, 2, 1]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, 2, 7); seq [9, 8, 2, 3, 4, 5, 6, 7, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, end = 4); seq [5, 6, 7, 8, 9, 4, 3, 2, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, start = 5); seq [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] """ if start is None: start = 0 if end is None: end = len(sequence) - 1 if start >= end: return mid = (start + end) // 2 slowsort(sequence, start, mid) slowsort(sequence, mid + 1, end) if sequence[end] < sequence[mid]: sequence[end], sequence[mid] = sequence[mid], sequence[end] slowsort(sequence, start, end - 1) if __name__ == "__main__": from doctest import testmod testmod()
""" Slowsort is a sorting algorithm. It is of humorous nature and not useful. It's based on the principle of multiply and surrender, a tongue-in-cheek joke of divide and conquer. It was published in 1986 by Andrei Broder and Jorge Stolfi in their paper Pessimal Algorithms and Simplexity Analysis (a parody of optimal algorithms and complexity analysis). Source: https://en.wikipedia.org/wiki/Slowsort """ from __future__ import annotations def slowsort(sequence: list, start: int | None = None, end: int | None = None) -> None: """ Sorts sequence[start..end] (both inclusive) in-place. start defaults to 0 if not given. end defaults to len(sequence) - 1 if not given. It returns None. >>> seq = [1, 6, 2, 5, 3, 4, 4, 5]; slowsort(seq); seq [1, 2, 3, 4, 4, 5, 5, 6] >>> seq = []; slowsort(seq); seq [] >>> seq = [2]; slowsort(seq); seq [2] >>> seq = [1, 2, 3, 4]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [4, 3, 2, 1]; slowsort(seq); seq [1, 2, 3, 4] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, 2, 7); seq [9, 8, 2, 3, 4, 5, 6, 7, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, end = 4); seq [5, 6, 7, 8, 9, 4, 3, 2, 1, 0] >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, start = 5); seq [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] """ if start is None: start = 0 if end is None: end = len(sequence) - 1 if start >= end: return mid = (start + end) // 2 slowsort(sequence, start, mid) slowsort(sequence, mid + 1, end) if sequence[end] < sequence[mid]: sequence[end], sequence[mid] = sequence[mid], sequence[end] slowsort(sequence, start, end - 1) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def is_palindrome(head): if not head: return True # split the list to two parts fast, slow = head.next, head while fast and fast.next: fast = fast.next.next slow = slow.next second = slow.next slow.next = None # Don't forget here! But forget still works! # reverse the second part node = None while second: nxt = second.next second.next = node node = second second = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False node = node.next head = head.next return True def is_palindrome_stack(head): if not head or not head.next: return True # 1. Get the midpoint (slow) slow = fast = cur = head while fast and fast.next: fast, slow = fast.next.next, slow.next # 2. Push the second half into the stack stack = [slow.val] while slow.next: slow = slow.next stack.append(slow.val) # 3. Comparison while stack: if stack.pop() != cur.val: return False cur = cur.next return True def is_palindrome_dict(head): if not head or not head.next: return True d = {} pos = 0 while head: if head.val in d.keys(): d[head.val].append(pos) else: d[head.val] = [pos] head = head.next pos += 1 checksum = pos - 1 middle = 0 for v in d.values(): if len(v) % 2 != 0: middle += 1 else: step = 0 for i in range(0, len(v)): if v[i] + v[len(v) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
def is_palindrome(head): if not head: return True # split the list to two parts fast, slow = head.next, head while fast and fast.next: fast = fast.next.next slow = slow.next second = slow.next slow.next = None # Don't forget here! But forget still works! # reverse the second part node = None while second: nxt = second.next second.next = node node = second second = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False node = node.next head = head.next return True def is_palindrome_stack(head): if not head or not head.next: return True # 1. Get the midpoint (slow) slow = fast = cur = head while fast and fast.next: fast, slow = fast.next.next, slow.next # 2. Push the second half into the stack stack = [slow.val] while slow.next: slow = slow.next stack.append(slow.val) # 3. Comparison while stack: if stack.pop() != cur.val: return False cur = cur.next return True def is_palindrome_dict(head): if not head or not head.next: return True d = {} pos = 0 while head: if head.val in d.keys(): d[head.val].append(pos) else: d[head.val] = [pos] head = head.next pos += 1 checksum = pos - 1 middle = 0 for v in d.values(): if len(v) % 2 != 0: middle += 1 else: step = 0 for i in range(0, len(v)): if v[i] + v[len(v) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def split(string: str, separator: str = " ") -> list: """ Will split the string up into all the values separated by the separator (defaults to spaces) >>> split("apple#banana#cherry#orange",separator='#') ['apple', 'banana', 'cherry', 'orange'] >>> split("Hello there") ['Hello', 'there'] >>> split("11/22/63",separator = '/') ['11', '22', '63'] >>> split("12:43:39",separator = ":") ['12', '43', '39'] """ split_words = [] last_index = 0 for index, char in enumerate(string): if char == separator: split_words.append(string[last_index:index]) last_index = index + 1 elif index + 1 == len(string): split_words.append(string[last_index : index + 1]) return split_words if __name__ == "__main__": from doctest import testmod testmod()
def split(string: str, separator: str = " ") -> list: """ Will split the string up into all the values separated by the separator (defaults to spaces) >>> split("apple#banana#cherry#orange",separator='#') ['apple', 'banana', 'cherry', 'orange'] >>> split("Hello there") ['Hello', 'there'] >>> split("11/22/63",separator = '/') ['11', '22', '63'] >>> split("12:43:39",separator = ":") ['12', '43', '39'] """ split_words = [] last_index = 0 for index, char in enumerate(string): if char == separator: split_words.append(string[last_index:index]) last_index = index + 1 elif index + 1 == len(string): split_words.append(string[last_index : index + 1]) return split_words if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a pure Python implementation of the merge-insertion sort algorithm Source: https://en.wikipedia.org/wiki/Graham_scan For doctests run following command: python3 -m doctest -v graham_scan.py """ from __future__ import annotations from collections import deque from enum import Enum from math import atan2, degrees from sys import maxsize def graham_scan(points: list[tuple[int, int]]) -> list[tuple[int, int]]: """Pure implementation of graham scan algorithm in Python :param points: The unique points on coordinates. :return: The points on convex hell. Examples: >>> graham_scan([(9, 6), (3, 1), (0, 0), (5, 5), (5, 2), (7, 0), (3, 3), (1, 4)]) [(0, 0), (7, 0), (9, 6), (5, 5), (1, 4)] >>> graham_scan([(0, 0), (1, 0), (1, 1), (0, 1)]) [(0, 0), (1, 0), (1, 1), (0, 1)] >>> graham_scan([(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)]) [(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)] >>> graham_scan([(-100, 20), (99, 3), (1, 10000001), (5133186, -25), (-66, -4)]) [(5133186, -25), (1, 10000001), (-100, 20), (-66, -4)] """ if len(points) <= 2: # There is no convex hull raise ValueError("graham_scan: argument must contain more than 3 points.") if len(points) == 3: return points # find the lowest and the most left point minidx = 0 miny, minx = maxsize, maxsize for i, point in enumerate(points): x = point[0] y = point[1] if y < miny: miny = y minx = x minidx = i if y == miny: if x < minx: minx = x minidx = i # remove the lowest and the most left point from points for preparing for sort points.pop(minidx) def angle_comparer(point: tuple[int, int], minx: int, miny: int) -> float: """Return the angle toward to point from (minx, miny) :param point: The target point minx: The starting point's x miny: The starting point's y :return: the angle Examples: >>> angle_comparer((1,1), 0, 0) 45.0 >>> angle_comparer((100,1), 10, 10) -5.710593137499642 >>> angle_comparer((5,5), 2, 3) 33.690067525979785 """ # sort the points accorgind to the angle from the lowest and the most left point x = point[0] y = point[1] angle = degrees(atan2(y - miny, x - minx)) return angle sorted_points = sorted(points, key=lambda point: angle_comparer(point, minx, miny)) # This insert actually costs complexity, # and you should instead add (minx, miny) into stack later. # I'm using insert just for easy understanding. sorted_points.insert(0, (minx, miny)) # traversal from the lowest and the most left point in anti-clockwise direction # if direction gets right, the previous point is not the convex hull. class Direction(Enum): left = 1 straight = 2 right = 3 def check_direction( starting: tuple[int, int], via: tuple[int, int], target: tuple[int, int] ) -> Direction: """Return the direction toward to the line from via to target from starting :param starting: The starting point via: The via point target: The target point :return: the Direction Examples: >>> check_direction((1,1), (2,2), (3,3)) Direction.straight >>> check_direction((60,1), (-50,199), (30,2)) Direction.left >>> check_direction((0,0), (5,5), (10,0)) Direction.right """ x0, y0 = starting x1, y1 = via x2, y2 = target via_angle = degrees(atan2(y1 - y0, x1 - x0)) if via_angle < 0: via_angle += 360 target_angle = degrees(atan2(y2 - y0, x2 - x0)) if target_angle < 0: target_angle += 360 # t- # \ \ # \ v # \| # s # via_angle is always lower than target_angle, if direction is left. # If they are same, it means they are on a same line of convex hull. if target_angle > via_angle: return Direction.left elif target_angle == via_angle: return Direction.straight else: return Direction.right stack: deque[tuple[int, int]] = deque() stack.append(sorted_points[0]) stack.append(sorted_points[1]) stack.append(sorted_points[2]) # In any ways, the first 3 points line are towards left. # Because we sort them the angle from minx, miny. current_direction = Direction.left for i in range(3, len(sorted_points)): while True: starting = stack[-2] via = stack[-1] target = sorted_points[i] next_direction = check_direction(starting, via, target) if next_direction == Direction.left: current_direction = Direction.left break if next_direction == Direction.straight: if current_direction == Direction.left: # We keep current_direction as left. # Because if the straight line keeps as straight, # we want to know if this straight line is towards left. break elif current_direction == Direction.right: # If the straight line is towards right, # every previous points on those straigh line is not convex hull. stack.pop() if next_direction == Direction.right: stack.pop() stack.append(sorted_points[i]) return list(stack)
""" This is a pure Python implementation of the merge-insertion sort algorithm Source: https://en.wikipedia.org/wiki/Graham_scan For doctests run following command: python3 -m doctest -v graham_scan.py """ from __future__ import annotations from collections import deque from enum import Enum from math import atan2, degrees from sys import maxsize def graham_scan(points: list[tuple[int, int]]) -> list[tuple[int, int]]: """Pure implementation of graham scan algorithm in Python :param points: The unique points on coordinates. :return: The points on convex hell. Examples: >>> graham_scan([(9, 6), (3, 1), (0, 0), (5, 5), (5, 2), (7, 0), (3, 3), (1, 4)]) [(0, 0), (7, 0), (9, 6), (5, 5), (1, 4)] >>> graham_scan([(0, 0), (1, 0), (1, 1), (0, 1)]) [(0, 0), (1, 0), (1, 1), (0, 1)] >>> graham_scan([(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)]) [(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)] >>> graham_scan([(-100, 20), (99, 3), (1, 10000001), (5133186, -25), (-66, -4)]) [(5133186, -25), (1, 10000001), (-100, 20), (-66, -4)] """ if len(points) <= 2: # There is no convex hull raise ValueError("graham_scan: argument must contain more than 3 points.") if len(points) == 3: return points # find the lowest and the most left point minidx = 0 miny, minx = maxsize, maxsize for i, point in enumerate(points): x = point[0] y = point[1] if y < miny: miny = y minx = x minidx = i if y == miny: if x < minx: minx = x minidx = i # remove the lowest and the most left point from points for preparing for sort points.pop(minidx) def angle_comparer(point: tuple[int, int], minx: int, miny: int) -> float: """Return the angle toward to point from (minx, miny) :param point: The target point minx: The starting point's x miny: The starting point's y :return: the angle Examples: >>> angle_comparer((1,1), 0, 0) 45.0 >>> angle_comparer((100,1), 10, 10) -5.710593137499642 >>> angle_comparer((5,5), 2, 3) 33.690067525979785 """ # sort the points accorgind to the angle from the lowest and the most left point x = point[0] y = point[1] angle = degrees(atan2(y - miny, x - minx)) return angle sorted_points = sorted(points, key=lambda point: angle_comparer(point, minx, miny)) # This insert actually costs complexity, # and you should instead add (minx, miny) into stack later. # I'm using insert just for easy understanding. sorted_points.insert(0, (minx, miny)) # traversal from the lowest and the most left point in anti-clockwise direction # if direction gets right, the previous point is not the convex hull. class Direction(Enum): left = 1 straight = 2 right = 3 def check_direction( starting: tuple[int, int], via: tuple[int, int], target: tuple[int, int] ) -> Direction: """Return the direction toward to the line from via to target from starting :param starting: The starting point via: The via point target: The target point :return: the Direction Examples: >>> check_direction((1,1), (2,2), (3,3)) Direction.straight >>> check_direction((60,1), (-50,199), (30,2)) Direction.left >>> check_direction((0,0), (5,5), (10,0)) Direction.right """ x0, y0 = starting x1, y1 = via x2, y2 = target via_angle = degrees(atan2(y1 - y0, x1 - x0)) if via_angle < 0: via_angle += 360 target_angle = degrees(atan2(y2 - y0, x2 - x0)) if target_angle < 0: target_angle += 360 # t- # \ \ # \ v # \| # s # via_angle is always lower than target_angle, if direction is left. # If they are same, it means they are on a same line of convex hull. if target_angle > via_angle: return Direction.left elif target_angle == via_angle: return Direction.straight else: return Direction.right stack: deque[tuple[int, int]] = deque() stack.append(sorted_points[0]) stack.append(sorted_points[1]) stack.append(sorted_points[2]) # In any ways, the first 3 points line are towards left. # Because we sort them the angle from minx, miny. current_direction = Direction.left for i in range(3, len(sorted_points)): while True: starting = stack[-2] via = stack[-1] target = sorted_points[i] next_direction = check_direction(starting, via, target) if next_direction == Direction.left: current_direction = Direction.left break if next_direction == Direction.straight: if current_direction == Direction.left: # We keep current_direction as left. # Because if the straight line keeps as straight, # we want to know if this straight line is towards left. break elif current_direction == Direction.right: # If the straight line is towards right, # every previous points on those straigh line is not convex hull. stack.pop() if next_direction == Direction.right: stack.pop() stack.append(sorted_points[i]) return list(stack)
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 5: https://projecteuler.net/problem=5 Smallest multiple 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is _evenly divisible_ by all of the numbers from 1 to 20? References: - https://en.wiktionary.org/wiki/evenly_divisible """ def solution(n: int = 20) -> int: """ Returns the smallest positive number that is evenly divisible (divisible with no remainder) by all of the numbers from 1 to n. >>> solution(10) 2520 >>> solution(15) 360360 >>> solution(22) 232792560 >>> solution(3.4) 6 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") i = 0 while 1: i += n * (n - 1) nfound = 0 for j in range(2, n): if i % j != 0: nfound = 1 break if nfound == 0: if i == 0: i = 1 return i if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 5: https://projecteuler.net/problem=5 Smallest multiple 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is _evenly divisible_ by all of the numbers from 1 to 20? References: - https://en.wiktionary.org/wiki/evenly_divisible """ def solution(n: int = 20) -> int: """ Returns the smallest positive number that is evenly divisible (divisible with no remainder) by all of the numbers from 1 to n. >>> solution(10) 2520 >>> solution(15) 360360 >>> solution(22) 232792560 >>> solution(3.4) 6 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") i = 0 while 1: i += n * (n - 1) nfound = 0 for j in range(2, n): if i % j != 0: nfound = 1 break if nfound == 0: if i == 0: i = 1 return i if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Pure Python implementations of a Fixed Priority Queue and an Element Priority Queue using Python lists. """ class OverFlowError(Exception): pass class UnderFlowError(Exception): pass class FixedPriorityQueue: """ Tasks can be added to a Priority Queue at any time and in any order but when Tasks are removed then the Task with the highest priority is removed in FIFO order. In code we will use three levels of priority with priority zero Tasks being the most urgent (high priority) and priority 2 tasks being the least urgent. Examples >>> fpq = FixedPriorityQueue() >>> fpq.enqueue(0, 10) >>> fpq.enqueue(1, 70) >>> fpq.enqueue(0, 100) >>> fpq.enqueue(2, 1) >>> fpq.enqueue(2, 5) >>> fpq.enqueue(1, 7) >>> fpq.enqueue(2, 4) >>> fpq.enqueue(1, 64) >>> fpq.enqueue(0, 128) >>> print(fpq) Priority 0: [10, 100, 128] Priority 1: [70, 7, 64] Priority 2: [1, 5, 4] >>> fpq.dequeue() 10 >>> fpq.dequeue() 100 >>> fpq.dequeue() 128 >>> fpq.dequeue() 70 >>> fpq.dequeue() 7 >>> print(fpq) Priority 0: [] Priority 1: [64] Priority 2: [1, 5, 4] >>> fpq.dequeue() 64 >>> fpq.dequeue() 1 >>> fpq.dequeue() 5 >>> fpq.dequeue() 4 >>> fpq.dequeue() Traceback (most recent call last): ... data_structures.queue.priority_queue_using_list.UnderFlowError: All queues are empty >>> print(fpq) Priority 0: [] Priority 1: [] Priority 2: [] """ def __init__(self): self.queues = [ [], [], [], ] def enqueue(self, priority: int, data: int) -> None: """ Add an element to a queue based on its priority. If the priority is invalid ValueError is raised. If the queue is full an OverFlowError is raised. """ try: if len(self.queues[priority]) >= 100: raise OverflowError("Maximum queue size is 100") self.queues[priority].append(data) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2") def dequeue(self) -> int: """ Return the highest priority element in FIFO order. If the queue is empty then an under flow exception is raised. """ for queue in self.queues: if queue: return queue.pop(0) raise UnderFlowError("All queues are empty") def __str__(self) -> str: return "\n".join(f"Priority {i}: {q}" for i, q in enumerate(self.queues)) class ElementPriorityQueue: """ Element Priority Queue is the same as Fixed Priority Queue except that the value of the element itself is the priority. The rules for priorities are the same the as Fixed Priority Queue. >>> epq = ElementPriorityQueue() >>> epq.enqueue(10) >>> epq.enqueue(70) >>> epq.enqueue(4) >>> epq.enqueue(1) >>> epq.enqueue(5) >>> epq.enqueue(7) >>> epq.enqueue(4) >>> epq.enqueue(64) >>> epq.enqueue(128) >>> print(epq) [10, 70, 4, 1, 5, 7, 4, 64, 128] >>> epq.dequeue() 1 >>> epq.dequeue() 4 >>> epq.dequeue() 4 >>> epq.dequeue() 5 >>> epq.dequeue() 7 >>> epq.dequeue() 10 >>> print(epq) [70, 64, 128] >>> epq.dequeue() 64 >>> epq.dequeue() 70 >>> epq.dequeue() 128 >>> epq.dequeue() Traceback (most recent call last): ... data_structures.queue.priority_queue_using_list.UnderFlowError: The queue is empty >>> print(epq) [] """ def __init__(self): self.queue = [] def enqueue(self, data: int) -> None: """ This function enters the element into the queue If the queue is full an Exception is raised saying Over Flow! """ if len(self.queue) == 100: raise OverFlowError("Maximum queue size is 100") self.queue.append(data) def dequeue(self) -> int: """ Return the highest priority element in FIFO order. If the queue is empty then an under flow exception is raised. """ if not self.queue: raise UnderFlowError("The queue is empty") else: data = min(self.queue) self.queue.remove(data) return data def __str__(self) -> str: """ Prints all the elements within the Element Priority Queue """ return str(self.queue) def fixed_priority_queue(): fpq = FixedPriorityQueue() fpq.enqueue(0, 10) fpq.enqueue(1, 70) fpq.enqueue(0, 100) fpq.enqueue(2, 1) fpq.enqueue(2, 5) fpq.enqueue(1, 7) fpq.enqueue(2, 4) fpq.enqueue(1, 64) fpq.enqueue(0, 128) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) def element_priority_queue(): epq = ElementPriorityQueue() epq.enqueue(10) epq.enqueue(70) epq.enqueue(100) epq.enqueue(1) epq.enqueue(5) epq.enqueue(7) epq.enqueue(4) epq.enqueue(64) epq.enqueue(128) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
""" Pure Python implementations of a Fixed Priority Queue and an Element Priority Queue using Python lists. """ class OverFlowError(Exception): pass class UnderFlowError(Exception): pass class FixedPriorityQueue: """ Tasks can be added to a Priority Queue at any time and in any order but when Tasks are removed then the Task with the highest priority is removed in FIFO order. In code we will use three levels of priority with priority zero Tasks being the most urgent (high priority) and priority 2 tasks being the least urgent. Examples >>> fpq = FixedPriorityQueue() >>> fpq.enqueue(0, 10) >>> fpq.enqueue(1, 70) >>> fpq.enqueue(0, 100) >>> fpq.enqueue(2, 1) >>> fpq.enqueue(2, 5) >>> fpq.enqueue(1, 7) >>> fpq.enqueue(2, 4) >>> fpq.enqueue(1, 64) >>> fpq.enqueue(0, 128) >>> print(fpq) Priority 0: [10, 100, 128] Priority 1: [70, 7, 64] Priority 2: [1, 5, 4] >>> fpq.dequeue() 10 >>> fpq.dequeue() 100 >>> fpq.dequeue() 128 >>> fpq.dequeue() 70 >>> fpq.dequeue() 7 >>> print(fpq) Priority 0: [] Priority 1: [64] Priority 2: [1, 5, 4] >>> fpq.dequeue() 64 >>> fpq.dequeue() 1 >>> fpq.dequeue() 5 >>> fpq.dequeue() 4 >>> fpq.dequeue() Traceback (most recent call last): ... data_structures.queue.priority_queue_using_list.UnderFlowError: All queues are empty >>> print(fpq) Priority 0: [] Priority 1: [] Priority 2: [] """ def __init__(self): self.queues = [ [], [], [], ] def enqueue(self, priority: int, data: int) -> None: """ Add an element to a queue based on its priority. If the priority is invalid ValueError is raised. If the queue is full an OverFlowError is raised. """ try: if len(self.queues[priority]) >= 100: raise OverflowError("Maximum queue size is 100") self.queues[priority].append(data) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2") def dequeue(self) -> int: """ Return the highest priority element in FIFO order. If the queue is empty then an under flow exception is raised. """ for queue in self.queues: if queue: return queue.pop(0) raise UnderFlowError("All queues are empty") def __str__(self) -> str: return "\n".join(f"Priority {i}: {q}" for i, q in enumerate(self.queues)) class ElementPriorityQueue: """ Element Priority Queue is the same as Fixed Priority Queue except that the value of the element itself is the priority. The rules for priorities are the same the as Fixed Priority Queue. >>> epq = ElementPriorityQueue() >>> epq.enqueue(10) >>> epq.enqueue(70) >>> epq.enqueue(4) >>> epq.enqueue(1) >>> epq.enqueue(5) >>> epq.enqueue(7) >>> epq.enqueue(4) >>> epq.enqueue(64) >>> epq.enqueue(128) >>> print(epq) [10, 70, 4, 1, 5, 7, 4, 64, 128] >>> epq.dequeue() 1 >>> epq.dequeue() 4 >>> epq.dequeue() 4 >>> epq.dequeue() 5 >>> epq.dequeue() 7 >>> epq.dequeue() 10 >>> print(epq) [70, 64, 128] >>> epq.dequeue() 64 >>> epq.dequeue() 70 >>> epq.dequeue() 128 >>> epq.dequeue() Traceback (most recent call last): ... data_structures.queue.priority_queue_using_list.UnderFlowError: The queue is empty >>> print(epq) [] """ def __init__(self): self.queue = [] def enqueue(self, data: int) -> None: """ This function enters the element into the queue If the queue is full an Exception is raised saying Over Flow! """ if len(self.queue) == 100: raise OverFlowError("Maximum queue size is 100") self.queue.append(data) def dequeue(self) -> int: """ Return the highest priority element in FIFO order. If the queue is empty then an under flow exception is raised. """ if not self.queue: raise UnderFlowError("The queue is empty") else: data = min(self.queue) self.queue.remove(data) return data def __str__(self) -> str: """ Prints all the elements within the Element Priority Queue """ return str(self.queue) def fixed_priority_queue(): fpq = FixedPriorityQueue() fpq.enqueue(0, 10) fpq.enqueue(1, 70) fpq.enqueue(0, 100) fpq.enqueue(2, 1) fpq.enqueue(2, 5) fpq.enqueue(1, 7) fpq.enqueue(2, 4) fpq.enqueue(1, 64) fpq.enqueue(0, 128) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) def element_priority_queue(): epq = ElementPriorityQueue() epq.enqueue(10) epq.enqueue(70) epq.enqueue(100) epq.enqueue(1) epq.enqueue(5) epq.enqueue(7) epq.enqueue(4) epq.enqueue(64) epq.enqueue(128) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Non-preemptive Shortest Job First Shortest execution time process is chosen for the next execution. https://www.guru99.com/shortest-job-first-sjf-scheduling.html https://en.wikipedia.org/wiki/Shortest_job_next """ from __future__ import annotations from statistics import mean def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: """ Calculate the waiting time of each processes Return: The waiting time for each process. >>> calculate_waitingtime([0,1,2], [10, 5, 8], 3) [0, 9, 13] >>> calculate_waitingtime([1,2,2,4], [4, 6, 3, 1], 4) [0, 7, 4, 1] >>> calculate_waitingtime([0,0,0], [12, 2, 10],3) [12, 0, 2] """ waiting_time = [0] * no_of_processes remaining_time = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(no_of_processes): remaining_time[i] = burst_time[i] ready_process: list[int] = [] completed = 0 total_time = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: ready_process = [] target_process = -1 for i in range(no_of_processes): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(i) if len(ready_process) > 0: target_process = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: target_process = i total_time += burst_time[target_process] completed += 1 remaining_time[target_process] = 0 waiting_time[target_process] = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: """ Calculate the turnaround time of each process. Return: The turnaround time for each process. >>> calculate_turnaroundtime([0,1,2], 3, [0, 10, 15]) [0, 11, 17] >>> calculate_turnaroundtime([1,2,2,4], 4, [1, 8, 5, 4]) [2, 10, 7, 8] >>> calculate_turnaroundtime([0,0,0], 3, [12, 0, 2]) [12, 0, 2] """ turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") no_of_processes = 4 burst_time = [2, 5, 3, 7] arrival_time = [0, 0, 0, 0] waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) turn_around_time = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_ID in enumerate(list(range(1, 5))): print( f"{process_ID}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t" f"{waiting_time[i]}\t\t\t\t{turn_around_time[i]}" ) print(f"\nAverage waiting time = {mean(waiting_time):.5f}") print(f"Average turnaround time = {mean(turn_around_time):.5f}")
""" Non-preemptive Shortest Job First Shortest execution time process is chosen for the next execution. https://www.guru99.com/shortest-job-first-sjf-scheduling.html https://en.wikipedia.org/wiki/Shortest_job_next """ from __future__ import annotations from statistics import mean def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: """ Calculate the waiting time of each processes Return: The waiting time for each process. >>> calculate_waitingtime([0,1,2], [10, 5, 8], 3) [0, 9, 13] >>> calculate_waitingtime([1,2,2,4], [4, 6, 3, 1], 4) [0, 7, 4, 1] >>> calculate_waitingtime([0,0,0], [12, 2, 10],3) [12, 0, 2] """ waiting_time = [0] * no_of_processes remaining_time = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(no_of_processes): remaining_time[i] = burst_time[i] ready_process: list[int] = [] completed = 0 total_time = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: ready_process = [] target_process = -1 for i in range(no_of_processes): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(i) if len(ready_process) > 0: target_process = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: target_process = i total_time += burst_time[target_process] completed += 1 remaining_time[target_process] = 0 waiting_time[target_process] = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: """ Calculate the turnaround time of each process. Return: The turnaround time for each process. >>> calculate_turnaroundtime([0,1,2], 3, [0, 10, 15]) [0, 11, 17] >>> calculate_turnaroundtime([1,2,2,4], 4, [1, 8, 5, 4]) [2, 10, 7, 8] >>> calculate_turnaroundtime([0,0,0], 3, [12, 0, 2]) [12, 0, 2] """ turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") no_of_processes = 4 burst_time = [2, 5, 3, 7] arrival_time = [0, 0, 0, 0] waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) turn_around_time = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_ID in enumerate(list(range(1, 5))): print( f"{process_ID}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t" f"{waiting_time[i]}\t\t\t\t{turn_around_time[i]}" ) print(f"\nAverage waiting time = {mean(waiting_time):.5f}") print(f"Average turnaround time = {mean(turn_around_time):.5f}")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 301: https://projecteuler.net/problem=301 Problem Statement: Nim is a game played with heaps of stones, where two players take it in turn to remove any number of stones from any heap until no stones remain. We'll consider the three-heap normal-play version of Nim, which works as follows: - At the start of the game there are three heaps of stones. - On each player's turn, the player may remove any positive number of stones from any single heap. - The first player unable to move (because no stones remain) loses. If (n1, n2, n3) indicates a Nim position consisting of heaps of size n1, n2, and n3, then there is a simple function, which you may look up or attempt to deduce for yourself, X(n1, n2, n3) that returns: - zero if, with perfect strategy, the player about to move will eventually lose; or - non-zero if, with perfect strategy, the player about to move will eventually win. For example X(1,2,3) = 0 because, no matter what the current player does, the opponent can respond with a move that leaves two heaps of equal size, at which point every move by the current player can be mirrored by the opponent until no stones remain; so the current player loses. To illustrate: - current player moves to (1,2,1) - opponent moves to (1,0,1) - current player moves to (0,0,1) - opponent moves to (0,0,0), and so wins. For how many positive integers n <= 2^30 does X(n,2n,3n) = 0? """ def solution(exponent: int = 30) -> int: """ For any given exponent x >= 0, 1 <= n <= 2^x. This function returns how many Nim games are lost given that each Nim game has three heaps of the form (n, 2*n, 3*n). >>> solution(0) 1 >>> solution(2) 3 >>> solution(10) 144 """ # To find how many total games were lost for a given exponent x, # we need to find the Fibonacci number F(x+2). fibonacci_index = exponent + 2 phi = (1 + 5**0.5) / 2 fibonacci = (phi**fibonacci_index - (phi - 1) ** fibonacci_index) / 5**0.5 return int(fibonacci) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 301: https://projecteuler.net/problem=301 Problem Statement: Nim is a game played with heaps of stones, where two players take it in turn to remove any number of stones from any heap until no stones remain. We'll consider the three-heap normal-play version of Nim, which works as follows: - At the start of the game there are three heaps of stones. - On each player's turn, the player may remove any positive number of stones from any single heap. - The first player unable to move (because no stones remain) loses. If (n1, n2, n3) indicates a Nim position consisting of heaps of size n1, n2, and n3, then there is a simple function, which you may look up or attempt to deduce for yourself, X(n1, n2, n3) that returns: - zero if, with perfect strategy, the player about to move will eventually lose; or - non-zero if, with perfect strategy, the player about to move will eventually win. For example X(1,2,3) = 0 because, no matter what the current player does, the opponent can respond with a move that leaves two heaps of equal size, at which point every move by the current player can be mirrored by the opponent until no stones remain; so the current player loses. To illustrate: - current player moves to (1,2,1) - opponent moves to (1,0,1) - current player moves to (0,0,1) - opponent moves to (0,0,0), and so wins. For how many positive integers n <= 2^30 does X(n,2n,3n) = 0? """ def solution(exponent: int = 30) -> int: """ For any given exponent x >= 0, 1 <= n <= 2^x. This function returns how many Nim games are lost given that each Nim game has three heaps of the form (n, 2*n, 3*n). >>> solution(0) 1 >>> solution(2) 3 >>> solution(10) 144 """ # To find how many total games were lost for a given exponent x, # we need to find the Fibonacci number F(x+2). fibonacci_index = exponent + 2 phi = (1 + 5**0.5) / 2 fibonacci = (phi**fibonacci_index - (phi - 1) ** fibonacci_index) / 5**0.5 return int(fibonacci) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations class Node: """ A Node has data variable and pointers to Nodes to its left and right. """ def __init__(self, data: int) -> None: self.data = data self.left: Node | None = None self.right: Node | None = None def display(tree: Node | None) -> None: # In Order traversal of the tree """ >>> root = Node(1) >>> root.left = Node(0) >>> root.right = Node(2) >>> display(root) 0 1 2 >>> display(root.right) 2 """ if tree: display(tree.left) print(tree.data) display(tree.right) def depth_of_tree(tree: Node | None) -> int: """ Recursive function that returns the depth of a binary tree. >>> root = Node(0) >>> depth_of_tree(root) 1 >>> root.left = Node(0) >>> depth_of_tree(root) 2 >>> root.right = Node(0) >>> depth_of_tree(root) 2 >>> root.left.right = Node(0) >>> depth_of_tree(root) 3 >>> depth_of_tree(root.left) 2 """ return 1 + max(depth_of_tree(tree.left), depth_of_tree(tree.right)) if tree else 0 def is_full_binary_tree(tree: Node) -> bool: """ Returns True if this is a full binary tree >>> root = Node(0) >>> is_full_binary_tree(root) True >>> root.left = Node(0) >>> is_full_binary_tree(root) False >>> root.right = Node(0) >>> is_full_binary_tree(root) True >>> root.left.left = Node(0) >>> is_full_binary_tree(root) False >>> root.right.right = Node(0) >>> is_full_binary_tree(root) False """ if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left) and is_full_binary_tree(tree.right) else: return not tree.left and not tree.right def main() -> None: # Main function for testing. tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) tree.left.right.left = Node(6) tree.right.left = Node(7) tree.right.left.left = Node(8) tree.right.left.left.right = Node(9) print(is_full_binary_tree(tree)) print(depth_of_tree(tree)) print("Tree is: ") display(tree) if __name__ == "__main__": main()
from __future__ import annotations class Node: """ A Node has data variable and pointers to Nodes to its left and right. """ def __init__(self, data: int) -> None: self.data = data self.left: Node | None = None self.right: Node | None = None def display(tree: Node | None) -> None: # In Order traversal of the tree """ >>> root = Node(1) >>> root.left = Node(0) >>> root.right = Node(2) >>> display(root) 0 1 2 >>> display(root.right) 2 """ if tree: display(tree.left) print(tree.data) display(tree.right) def depth_of_tree(tree: Node | None) -> int: """ Recursive function that returns the depth of a binary tree. >>> root = Node(0) >>> depth_of_tree(root) 1 >>> root.left = Node(0) >>> depth_of_tree(root) 2 >>> root.right = Node(0) >>> depth_of_tree(root) 2 >>> root.left.right = Node(0) >>> depth_of_tree(root) 3 >>> depth_of_tree(root.left) 2 """ return 1 + max(depth_of_tree(tree.left), depth_of_tree(tree.right)) if tree else 0 def is_full_binary_tree(tree: Node) -> bool: """ Returns True if this is a full binary tree >>> root = Node(0) >>> is_full_binary_tree(root) True >>> root.left = Node(0) >>> is_full_binary_tree(root) False >>> root.right = Node(0) >>> is_full_binary_tree(root) True >>> root.left.left = Node(0) >>> is_full_binary_tree(root) False >>> root.right.right = Node(0) >>> is_full_binary_tree(root) False """ if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left) and is_full_binary_tree(tree.right) else: return not tree.left and not tree.right def main() -> None: # Main function for testing. tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) tree.left.right.left = Node(6) tree.right.left = Node(7) tree.right.left.left = Node(8) tree.right.left.left.right = Node(9) print(is_full_binary_tree(tree)) print(depth_of_tree(tree)) print("Tree is: ") display(tree) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from collections import Counter def sock_merchant(colors: list[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([1, 1, 3, 3]) 2 """ return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values()) if __name__ == "__main__": import doctest doctest.testmod() colors = [int(x) for x in input("Enter socks by color :").rstrip().split()] print(f"sock_merchant({colors}) = {sock_merchant(colors)}")
from collections import Counter def sock_merchant(colors: list[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([1, 1, 3, 3]) 2 """ return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values()) if __name__ == "__main__": import doctest doctest.testmod() colors = [int(x) for x in input("Enter socks by color :").rstrip().split()] print(f"sock_merchant({colors}) = {sock_merchant(colors)}")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_xor(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary xor operation on the integers provided. >>> binary_xor(25, 32) '0b111001' >>> binary_xor(37, 50) '0b010111' >>> binary_xor(21, 30) '0b01011' >>> binary_xor(58, 73) '0b1110011' >>> binary_xor(0, 255) '0b11111111' >>> binary_xor(256, 256) '0b000000000' >>> binary_xor(0, -1) Traceback (most recent call last): ... ValueError: the value of both inputs must be positive >>> binary_xor(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_xor("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] # remove the leading "0b" max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int(char_a != char_b)) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_xor(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary xor operation on the integers provided. >>> binary_xor(25, 32) '0b111001' >>> binary_xor(37, 50) '0b010111' >>> binary_xor(21, 30) '0b01011' >>> binary_xor(58, 73) '0b1110011' >>> binary_xor(0, 255) '0b11111111' >>> binary_xor(256, 256) '0b000000000' >>> binary_xor(0, -1) Traceback (most recent call last): ... ValueError: the value of both inputs must be positive >>> binary_xor(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_xor("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] # remove the leading "0b" max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int(char_a != char_b)) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stock's price for all n days. The span Si of the stock's price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day. """ def calculateSpan(price, S): n = len(price) # Create a stack and push index of fist element to it st = [] st.append(0) # Span value of first element is always 1 S[0] = 1 # Calculate span values for rest of the elements for i in range(1, n): # Pop elements from stack while stack is not # empty and top of stack is smaller than price[i] while len(st) > 0 and price[st[0]] <= price[i]: st.pop() # If stack becomes empty, then price[i] is greater # than all elements on left of it, i.e. price[0], # price[1], ..price[i-1]. Else the price[i] is # greater than elements after top of stack S[i] = i + 1 if len(st) <= 0 else (i - st[0]) # Push this element to stack st.append(i) # A utility function to print elements of array def printArray(arr, n): for i in range(0, n): print(arr[i], end=" ") # Driver program to test above function price = [10, 4, 5, 90, 120, 80] S = [0 for i in range(len(price) + 1)] # Fill the span values in array S[] calculateSpan(price, S) # Print the calculated span values printArray(S, len(price))
""" The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stock's price for all n days. The span Si of the stock's price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day. """ def calculateSpan(price, S): n = len(price) # Create a stack and push index of fist element to it st = [] st.append(0) # Span value of first element is always 1 S[0] = 1 # Calculate span values for rest of the elements for i in range(1, n): # Pop elements from stack while stack is not # empty and top of stack is smaller than price[i] while len(st) > 0 and price[st[0]] <= price[i]: st.pop() # If stack becomes empty, then price[i] is greater # than all elements on left of it, i.e. price[0], # price[1], ..price[i-1]. Else the price[i] is # greater than elements after top of stack S[i] = i + 1 if len(st) <= 0 else (i - st[0]) # Push this element to stack st.append(i) # A utility function to print elements of array def printArray(arr, n): for i in range(0, n): print(arr[i], end=" ") # Driver program to test above function price = [10, 4, 5, 90, 120, 80] S = [0 for i in range(len(price) + 1)] # Fill the span values in array S[] calculateSpan(price, S) # Print the calculated span values printArray(S, len(price))
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from collections import deque class Automaton: def __init__(self, keywords: list[str]): self.adlist: list[dict] = list() self.adlist.append( {"value": "", "next_states": [], "fail_state": 0, "output": []} ) for keyword in keywords: self.add_keyword(keyword) self.set_fail_transitions() def find_next_state(self, current_state: int, char: str) -> int | None: for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def add_keyword(self, keyword: str) -> None: current_state = 0 for character in keyword: next_state = self.find_next_state(current_state, character) if next_state is None: self.adlist.append( { "value": character, "next_states": [], "fail_state": 0, "output": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist) - 1) current_state = len(self.adlist) - 1 else: current_state = next_state self.adlist[current_state]["output"].append(keyword) def set_fail_transitions(self) -> None: q: deque = deque() for node in self.adlist[0]["next_states"]: q.append(node) self.adlist[node]["fail_state"] = 0 while q: r = q.popleft() for child in self.adlist[r]["next_states"]: q.append(child) state = self.adlist[r]["fail_state"] while ( self.find_next_state(state, self.adlist[child]["value"]) is None and state != 0 ): state = self.adlist[state]["fail_state"] self.adlist[child]["fail_state"] = self.find_next_state( state, self.adlist[child]["value"] ) if self.adlist[child]["fail_state"] is None: self.adlist[child]["fail_state"] = 0 self.adlist[child]["output"] = ( self.adlist[child]["output"] + self.adlist[self.adlist[child]["fail_state"]]["output"] ) def search_in(self, string: str) -> dict[str, list[int]]: """ >>> A = Automaton(["what", "hat", "ver", "er"]) >>> A.search_in("whatever, err ... , wherever") {'what': [0], 'hat': [1], 'ver': [5, 25], 'er': [6, 10, 22, 26]} """ result: dict = ( dict() ) # returns a dict with keywords and list of its occurrences current_state = 0 for i in range(len(string)): while ( self.find_next_state(current_state, string[i]) is None and current_state != 0 ): current_state = self.adlist[current_state]["fail_state"] next_state = self.find_next_state(current_state, string[i]) if next_state is None: current_state = 0 else: current_state = next_state for key in self.adlist[current_state]["output"]: if not (key in result): result[key] = [] result[key].append(i - len(key) + 1) return result if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations from collections import deque class Automaton: def __init__(self, keywords: list[str]): self.adlist: list[dict] = list() self.adlist.append( {"value": "", "next_states": [], "fail_state": 0, "output": []} ) for keyword in keywords: self.add_keyword(keyword) self.set_fail_transitions() def find_next_state(self, current_state: int, char: str) -> int | None: for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def add_keyword(self, keyword: str) -> None: current_state = 0 for character in keyword: next_state = self.find_next_state(current_state, character) if next_state is None: self.adlist.append( { "value": character, "next_states": [], "fail_state": 0, "output": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist) - 1) current_state = len(self.adlist) - 1 else: current_state = next_state self.adlist[current_state]["output"].append(keyword) def set_fail_transitions(self) -> None: q: deque = deque() for node in self.adlist[0]["next_states"]: q.append(node) self.adlist[node]["fail_state"] = 0 while q: r = q.popleft() for child in self.adlist[r]["next_states"]: q.append(child) state = self.adlist[r]["fail_state"] while ( self.find_next_state(state, self.adlist[child]["value"]) is None and state != 0 ): state = self.adlist[state]["fail_state"] self.adlist[child]["fail_state"] = self.find_next_state( state, self.adlist[child]["value"] ) if self.adlist[child]["fail_state"] is None: self.adlist[child]["fail_state"] = 0 self.adlist[child]["output"] = ( self.adlist[child]["output"] + self.adlist[self.adlist[child]["fail_state"]]["output"] ) def search_in(self, string: str) -> dict[str, list[int]]: """ >>> A = Automaton(["what", "hat", "ver", "er"]) >>> A.search_in("whatever, err ... , wherever") {'what': [0], 'hat': [1], 'ver': [5, 25], 'er': [6, 10, 22, 26]} """ result: dict = ( dict() ) # returns a dict with keywords and list of its occurrences current_state = 0 for i in range(len(string)): while ( self.find_next_state(current_state, string[i]) is None and current_state != 0 ): current_state = self.adlist[current_state]["fail_state"] next_state = self.find_next_state(current_state, string[i]) if next_state is None: current_state = 0 else: current_state = next_state for key in self.adlist[current_state]["output"]: if not (key in result): result[key] = [] result[key].append(i - len(key) + 1) return result if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The 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 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 """ f1, f2 = 1, 1 index = 2 while True: i = 0 f = f1 + f2 f1, f2 = f2, f index += 1 for j in str(f): i += 1 if i == n: break return index 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 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 """ f1, f2 = 1, 1 index = 2 while True: i = 0 f = f1 + f2 f1, f2 = f2, f index += 1 for j in str(f): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import operator def strand_sort(arr: list, reverse: bool = False, solution: list = None) -> list: """ Strand sort implementation source: https://en.wikipedia.org/wiki/Strand_sort :param arr: Unordered input list :param reverse: Descent ordering flag :param solution: Ordered items container Examples: >>> strand_sort([4, 2, 5, 3, 0, 1]) [0, 1, 2, 3, 4, 5] >>> strand_sort([4, 2, 5, 3, 0, 1], reverse=True) [5, 4, 3, 2, 1, 0] """ _operator = operator.lt if reverse else operator.gt solution = solution or [] if not arr: return solution sublist = [arr.pop(0)] for i, item in enumerate(arr): if _operator(item, sublist[-1]): sublist.append(item) arr.pop(i) # merging sublist into solution list if not solution: solution.extend(sublist) else: while sublist: item = sublist.pop(0) for i, xx in enumerate(solution): if not _operator(item, xx): solution.insert(i, item) break else: solution.append(item) strand_sort(arr, reverse, solution) return solution if __name__ == "__main__": assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5] assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]
import operator def strand_sort(arr: list, reverse: bool = False, solution: list = None) -> list: """ Strand sort implementation source: https://en.wikipedia.org/wiki/Strand_sort :param arr: Unordered input list :param reverse: Descent ordering flag :param solution: Ordered items container Examples: >>> strand_sort([4, 2, 5, 3, 0, 1]) [0, 1, 2, 3, 4, 5] >>> strand_sort([4, 2, 5, 3, 0, 1], reverse=True) [5, 4, 3, 2, 1, 0] """ _operator = operator.lt if reverse else operator.gt solution = solution or [] if not arr: return solution sublist = [arr.pop(0)] for i, item in enumerate(arr): if _operator(item, sublist[-1]): sublist.append(item) arr.pop(i) # merging sublist into solution list if not solution: solution.extend(sublist) else: while sublist: item = sublist.pop(0) for i, xx in enumerate(solution): if not _operator(item, xx): solution.insert(i, item) break else: solution.append(item) strand_sort(arr, reverse, solution) return solution if __name__ == "__main__": assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5] assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" python/black : true flake8 : passed """ from __future__ import annotations from typing import Iterator class RedBlackTree: """ A Red-Black tree, which is a self-balancing BST (binary search tree). This tree has similar performance to AVL trees, but the balancing is less strict, so it will perform faster for writing/deleting nodes and slower for reading in the average case, though, because they're both balanced binary search trees, both will get the same asymptotic performance. To read more about them, https://en.wikipedia.org/wiki/Red–black_tree Unless otherwise specified, all asymptotic runtimes are specified in terms of the size of the tree. """ def __init__( self, label: int | None = None, color: int = 0, parent: RedBlackTree | None = None, left: RedBlackTree | None = None, right: RedBlackTree | None = None, ) -> None: """Initialize a new Red-Black Tree node with the given values: label: The value associated with this node color: 0 if black, 1 if red parent: The parent to this node left: This node's left child right: This node's right child """ self.label = label self.parent = parent self.left = left self.right = right self.color = color # Here are functions which are specific to red-black trees def rotate_left(self) -> RedBlackTree: """Rotate the subtree rooted at this node to the left and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent right = self.right if right is None: return self self.right = right.left if self.right: self.right.parent = self self.parent = right right.left = self if parent is not None: if parent.left == self: parent.left = right else: parent.right = right right.parent = parent return right def rotate_right(self) -> RedBlackTree: """Rotate the subtree rooted at this node to the right and returns the new root to this subtree. Performing one rotation can be done in O(1). """ if self.left is None: return self parent = self.parent left = self.left self.left = left.right if self.left: self.left.parent = self self.parent = left left.right = self if parent is not None: if parent.right is self: parent.right = left else: parent.left = left left.parent = parent return left def insert(self, label: int) -> RedBlackTree: """Inserts label into the subtree rooted at self, performs any rotations necessary to maintain balance, and then returns the new root to this subtree (likely self). This is guaranteed to run in O(log(n)) time. """ if self.label is None: # Only possible with an empty tree self.label = label return self if self.label == label: return self elif self.label > label: if self.left: self.left.insert(label) else: self.left = RedBlackTree(label, 1, self) self.left._insert_repair() else: if self.right: self.right.insert(label) else: self.right = RedBlackTree(label, 1, self) self.right._insert_repair() return self.parent or self def _insert_repair(self) -> None: """Repair the coloring from inserting into a tree.""" if self.parent is None: # This node is the root, so it just needs to be black self.color = 0 elif color(self.parent) == 0: # If the parent is black, then it just needs to be red self.color = 1 else: uncle = self.parent.sibling if color(uncle) == 0: if self.is_left() and self.parent.is_right(): self.parent.rotate_right() if self.right: self.right._insert_repair() elif self.is_right() and self.parent.is_left(): self.parent.rotate_left() if self.left: self.left._insert_repair() elif self.is_left(): if self.grandparent: self.grandparent.rotate_right() self.parent.color = 0 if self.parent.right: self.parent.right.color = 1 else: if self.grandparent: self.grandparent.rotate_left() self.parent.color = 0 if self.parent.left: self.parent.left.color = 1 else: self.parent.color = 0 if uncle and self.grandparent: uncle.color = 0 self.grandparent.color = 1 self.grandparent._insert_repair() def remove(self, label: int) -> RedBlackTree: """Remove label from this tree.""" if self.label == label: if self.left and self.right: # It's easier to balance a node with at most one child, # so we replace this node with the greatest one less than # it and remove that. value = self.left.get_max() if value is not None: self.label = value self.left.remove(value) else: # This node has at most one non-None child, so we don't # need to replace child = self.left or self.right if self.color == 1: # This node is red, and its child is black # The only way this happens to a node with one child # is if both children are None leaves. # We can just remove this node and call it a day. if self.parent: if self.is_left(): self.parent.left = None else: self.parent.right = None else: # The node is black if child is None: # This node and its child are black if self.parent is None: # The tree is now empty return RedBlackTree(None) else: self._remove_repair() if self.is_left(): self.parent.left = None else: self.parent.right = None self.parent = None else: # This node is black and its child is red # Move the child node here and make it black self.label = child.label self.left = child.left self.right = child.right if self.left: self.left.parent = self if self.right: self.right.parent = self elif self.label is not None and self.label > label: if self.left: self.left.remove(label) else: if self.right: self.right.remove(label) return self.parent or self def _remove_repair(self) -> None: """Repair the coloring of the tree that may have been messed up.""" if ( self.parent is None or self.sibling is None or self.parent.sibling is None or self.grandparent is None ): return if color(self.sibling) == 1: self.sibling.color = 0 self.parent.color = 1 if self.is_left(): self.parent.rotate_left() else: self.parent.rotate_right() if ( color(self.parent) == 0 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent._remove_repair() return if ( color(self.parent) == 1 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent.color = 0 return if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 0 and color(self.sibling.left) == 1 ): self.sibling.rotate_right() self.sibling.color = 0 if self.sibling.right: self.sibling.right.color = 1 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.right) == 1 and color(self.sibling.left) == 0 ): self.sibling.rotate_left() self.sibling.color = 0 if self.sibling.left: self.sibling.left.color = 1 if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 1 ): self.parent.rotate_left() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.left) == 1 ): self.parent.rotate_right() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 def check_color_properties(self) -> bool: """Check the coloring of the tree, and return True iff the tree is colored in a way which matches these five properties: (wording stolen from wikipedia article) 1. Each node is either red or black. 2. The root node is black. 3. All leaves are black. 4. If a node is red, then both its children are black. 5. Every path from any node to all of its descendent NIL nodes has the same number of black nodes. This function runs in O(n) time, because properties 4 and 5 take that long to check. """ # I assume property 1 to hold because there is nothing that can # make the color be anything other than 0 or 1. # Property 2 if self.color: # The root was red print("Property 2") return False # Property 3 does not need to be checked, because None is assumed # to be black and is all the leaves. # Property 4 if not self.check_coloring(): print("Property 4") return False # Property 5 if self.black_height() is None: print("Property 5") return False # All properties were met return True def check_coloring(self) -> bool: """A helper function to recursively check Property 4 of a Red-Black Tree. See check_color_properties for more info. """ if self.color == 1: if color(self.left) == 1 or color(self.right) == 1: return False if self.left and not self.left.check_coloring(): return False if self.right and not self.right.check_coloring(): return False return True def black_height(self) -> int | None: """Returns the number of black nodes from this node to the leaves of the tree, or None if there isn't one such value (the tree is color incorrectly). """ if self is None or self.left is None or self.right is None: # If we're already at a leaf, there is no path return 1 left = RedBlackTree.black_height(self.left) right = RedBlackTree.black_height(self.right) if left is None or right is None: # There are issues with coloring below children nodes return None if left != right: # The two children have unequal depths return None # Return the black depth of children, plus one if this node is # black return left + (1 - self.color) # Here are functions which are general to all binary search trees def __contains__(self, label: int) -> bool: """Search through the tree for label, returning True iff it is found somewhere in the tree. Guaranteed to run in O(log(n)) time. """ return self.search(label) is not None def search(self, label: int) -> RedBlackTree | None: """Search through the tree for label, returning its node if it's found, and None otherwise. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self elif self.label is not None and label > self.label: if self.right is None: return None else: return self.right.search(label) else: if self.left is None: return None else: return self.left.search(label) def floor(self, label: int) -> int | None: """Returns the largest element in this tree which is at most label. This method is guaranteed to run in O(log(n)) time.""" if self.label == label: return self.label elif self.label is not None and self.label > label: if self.left: return self.left.floor(label) else: return None else: if self.right: attempt = self.right.floor(label) if attempt is not None: return attempt return self.label def ceil(self, label: int) -> int | None: """Returns the smallest element in this tree which is at least label. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self.label elif self.label is not None and self.label < label: if self.right: return self.right.ceil(label) else: return None else: if self.left: attempt = self.left.ceil(label) if attempt is not None: return attempt return self.label def get_max(self) -> int | None: """Returns the largest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.right: # Go as far right as possible return self.right.get_max() else: return self.label def get_min(self) -> int | None: """Returns the smallest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.left: # Go as far left as possible return self.left.get_min() else: return self.label @property def grandparent(self) -> RedBlackTree | None: """Get the current node's grandparent, or None if it doesn't exist.""" if self.parent is None: return None else: return self.parent.parent @property def sibling(self) -> RedBlackTree | None: """Get the current node's sibling, or None if it doesn't exist.""" if self.parent is None: return None elif self.parent.left is self: return self.parent.right else: return self.parent.left def is_left(self) -> bool: """Returns true iff this node is the left child of its parent.""" if self.parent is None: return False return self.parent.left is self.parent.left is self def is_right(self) -> bool: """Returns true iff this node is the right child of its parent.""" if self.parent is None: return False return self.parent.right is self def __bool__(self) -> bool: return True def __len__(self) -> int: """ Return the number of nodes in this tree. """ ln = 1 if self.left: ln += len(self.left) if self.right: ln += len(self.right) return ln def preorder_traverse(self) -> Iterator[int | None]: yield self.label if self.left: yield from self.left.preorder_traverse() if self.right: yield from self.right.preorder_traverse() def inorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.inorder_traverse() yield self.label if self.right: yield from self.right.inorder_traverse() def postorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.postorder_traverse() if self.right: yield from self.right.postorder_traverse() yield self.label def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.label} {(self.color and 'red') or 'blk'}'" return pformat( { f"{self.label} {(self.color and 'red') or 'blk'}": ( self.left, self.right, ) }, indent=1, ) def __eq__(self, other: object) -> bool: """Test if two trees are equal.""" if not isinstance(other, RedBlackTree): return NotImplemented if self.label == other.label: return self.left == other.left and self.right == other.right else: return False def color(node: RedBlackTree | None) -> int: """Returns the color of a node, allowing for None leaves.""" if node is None: return 0 else: return node.color """ Code for testing the various functions of the red-black tree. """ def test_rotations() -> bool: """Test that the rotate_left and rotate_right functions work.""" # Make a tree to test on tree = RedBlackTree(0) tree.left = RedBlackTree(-10, parent=tree) tree.right = RedBlackTree(10, parent=tree) tree.left.left = RedBlackTree(-20, parent=tree.left) tree.left.right = RedBlackTree(-5, parent=tree.left) tree.right.left = RedBlackTree(5, parent=tree.right) tree.right.right = RedBlackTree(20, parent=tree.right) # Make the right rotation left_rot = RedBlackTree(10) left_rot.left = RedBlackTree(0, parent=left_rot) left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) left_rot.left.right = RedBlackTree(5, parent=left_rot.left) left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) left_rot.right = RedBlackTree(20, parent=left_rot) tree = tree.rotate_left() if tree != left_rot: return False tree = tree.rotate_right() tree = tree.rotate_right() # Make the left rotation right_rot = RedBlackTree(-10) right_rot.left = RedBlackTree(-20, parent=right_rot) right_rot.right = RedBlackTree(0, parent=right_rot) right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) right_rot.right.right = RedBlackTree(10, parent=right_rot.right) right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) if tree != right_rot: return False return True def test_insertion_speed() -> bool: """Test that the tree balances inserts to O(log(n)) by doing a lot of them. """ tree = RedBlackTree(-1) for i in range(300000): tree = tree.insert(i) return True def test_insert() -> bool: """Test the insert() method of the tree correctly balances, colors, and inserts. """ tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) ans = RedBlackTree(0, 0) ans.left = RedBlackTree(-8, 0, ans) ans.right = RedBlackTree(8, 1, ans) ans.right.left = RedBlackTree(4, 0, ans.right) ans.right.right = RedBlackTree(11, 0, ans.right) ans.right.right.left = RedBlackTree(10, 1, ans.right.right) ans.right.right.right = RedBlackTree(12, 1, ans.right.right) return tree == ans def test_insert_and_search() -> bool: """Tests searching through the tree for values.""" tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) if 5 in tree or -6 in tree or -10 in tree or 13 in tree: # Found something not in there return False if not (11 in tree and 12 in tree and -8 in tree and 0 in tree): # Didn't find something in there return False return True def test_insert_delete() -> bool: """Test the insert() and delete() method of the tree, verifying the insertion and removal of elements, and the balancing of the tree. """ tree = RedBlackTree(0) tree = tree.insert(-12) tree = tree.insert(8) tree = tree.insert(-8) tree = tree.insert(15) tree = tree.insert(4) tree = tree.insert(12) tree = tree.insert(10) tree = tree.insert(9) tree = tree.insert(11) tree = tree.remove(15) tree = tree.remove(-12) tree = tree.remove(9) if not tree.check_color_properties(): return False if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]: return False return True def test_floor_ceil() -> bool: """Tests the floor and ceiling functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] for val, floor, ceil in tuples: if tree.floor(val) != floor or tree.ceil(val) != ceil: return False return True def test_min_max() -> bool: """Tests the min and max functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if tree.get_max() != 22 or tree.get_min() != -16: return False return True def test_tree_traversal() -> bool: """Tests the three different tree traversal functions.""" tree = RedBlackTree(0) tree = tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def test_tree_chaining() -> bool: """Tests the three different tree chaining functions.""" tree = RedBlackTree(0) tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_rotations() assert test_insert() assert test_insert_and_search() assert test_insert_delete() assert test_floor_ceil() assert test_tree_traversal() assert test_tree_chaining() def main() -> None: """ >>> pytests() """ print_results("Rotating right and left", test_rotations()) print_results("Inserting", test_insert()) print_results("Searching", test_insert_and_search()) print_results("Deleting", test_insert_delete()) print_results("Floor and ceil", test_floor_ceil()) print_results("Tree traversal", test_tree_traversal()) print_results("Tree traversal", test_tree_chaining()) print("Testing tree balancing...") print("This should only be a few seconds.") test_insertion_speed() print("Done!") if __name__ == "__main__": main()
""" python/black : true flake8 : passed """ from __future__ import annotations from typing import Iterator class RedBlackTree: """ A Red-Black tree, which is a self-balancing BST (binary search tree). This tree has similar performance to AVL trees, but the balancing is less strict, so it will perform faster for writing/deleting nodes and slower for reading in the average case, though, because they're both balanced binary search trees, both will get the same asymptotic performance. To read more about them, https://en.wikipedia.org/wiki/Red–black_tree Unless otherwise specified, all asymptotic runtimes are specified in terms of the size of the tree. """ def __init__( self, label: int | None = None, color: int = 0, parent: RedBlackTree | None = None, left: RedBlackTree | None = None, right: RedBlackTree | None = None, ) -> None: """Initialize a new Red-Black Tree node with the given values: label: The value associated with this node color: 0 if black, 1 if red parent: The parent to this node left: This node's left child right: This node's right child """ self.label = label self.parent = parent self.left = left self.right = right self.color = color # Here are functions which are specific to red-black trees def rotate_left(self) -> RedBlackTree: """Rotate the subtree rooted at this node to the left and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent right = self.right if right is None: return self self.right = right.left if self.right: self.right.parent = self self.parent = right right.left = self if parent is not None: if parent.left == self: parent.left = right else: parent.right = right right.parent = parent return right def rotate_right(self) -> RedBlackTree: """Rotate the subtree rooted at this node to the right and returns the new root to this subtree. Performing one rotation can be done in O(1). """ if self.left is None: return self parent = self.parent left = self.left self.left = left.right if self.left: self.left.parent = self self.parent = left left.right = self if parent is not None: if parent.right is self: parent.right = left else: parent.left = left left.parent = parent return left def insert(self, label: int) -> RedBlackTree: """Inserts label into the subtree rooted at self, performs any rotations necessary to maintain balance, and then returns the new root to this subtree (likely self). This is guaranteed to run in O(log(n)) time. """ if self.label is None: # Only possible with an empty tree self.label = label return self if self.label == label: return self elif self.label > label: if self.left: self.left.insert(label) else: self.left = RedBlackTree(label, 1, self) self.left._insert_repair() else: if self.right: self.right.insert(label) else: self.right = RedBlackTree(label, 1, self) self.right._insert_repair() return self.parent or self def _insert_repair(self) -> None: """Repair the coloring from inserting into a tree.""" if self.parent is None: # This node is the root, so it just needs to be black self.color = 0 elif color(self.parent) == 0: # If the parent is black, then it just needs to be red self.color = 1 else: uncle = self.parent.sibling if color(uncle) == 0: if self.is_left() and self.parent.is_right(): self.parent.rotate_right() if self.right: self.right._insert_repair() elif self.is_right() and self.parent.is_left(): self.parent.rotate_left() if self.left: self.left._insert_repair() elif self.is_left(): if self.grandparent: self.grandparent.rotate_right() self.parent.color = 0 if self.parent.right: self.parent.right.color = 1 else: if self.grandparent: self.grandparent.rotate_left() self.parent.color = 0 if self.parent.left: self.parent.left.color = 1 else: self.parent.color = 0 if uncle and self.grandparent: uncle.color = 0 self.grandparent.color = 1 self.grandparent._insert_repair() def remove(self, label: int) -> RedBlackTree: """Remove label from this tree.""" if self.label == label: if self.left and self.right: # It's easier to balance a node with at most one child, # so we replace this node with the greatest one less than # it and remove that. value = self.left.get_max() if value is not None: self.label = value self.left.remove(value) else: # This node has at most one non-None child, so we don't # need to replace child = self.left or self.right if self.color == 1: # This node is red, and its child is black # The only way this happens to a node with one child # is if both children are None leaves. # We can just remove this node and call it a day. if self.parent: if self.is_left(): self.parent.left = None else: self.parent.right = None else: # The node is black if child is None: # This node and its child are black if self.parent is None: # The tree is now empty return RedBlackTree(None) else: self._remove_repair() if self.is_left(): self.parent.left = None else: self.parent.right = None self.parent = None else: # This node is black and its child is red # Move the child node here and make it black self.label = child.label self.left = child.left self.right = child.right if self.left: self.left.parent = self if self.right: self.right.parent = self elif self.label is not None and self.label > label: if self.left: self.left.remove(label) else: if self.right: self.right.remove(label) return self.parent or self def _remove_repair(self) -> None: """Repair the coloring of the tree that may have been messed up.""" if ( self.parent is None or self.sibling is None or self.parent.sibling is None or self.grandparent is None ): return if color(self.sibling) == 1: self.sibling.color = 0 self.parent.color = 1 if self.is_left(): self.parent.rotate_left() else: self.parent.rotate_right() if ( color(self.parent) == 0 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent._remove_repair() return if ( color(self.parent) == 1 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent.color = 0 return if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 0 and color(self.sibling.left) == 1 ): self.sibling.rotate_right() self.sibling.color = 0 if self.sibling.right: self.sibling.right.color = 1 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.right) == 1 and color(self.sibling.left) == 0 ): self.sibling.rotate_left() self.sibling.color = 0 if self.sibling.left: self.sibling.left.color = 1 if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 1 ): self.parent.rotate_left() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.left) == 1 ): self.parent.rotate_right() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 def check_color_properties(self) -> bool: """Check the coloring of the tree, and return True iff the tree is colored in a way which matches these five properties: (wording stolen from wikipedia article) 1. Each node is either red or black. 2. The root node is black. 3. All leaves are black. 4. If a node is red, then both its children are black. 5. Every path from any node to all of its descendent NIL nodes has the same number of black nodes. This function runs in O(n) time, because properties 4 and 5 take that long to check. """ # I assume property 1 to hold because there is nothing that can # make the color be anything other than 0 or 1. # Property 2 if self.color: # The root was red print("Property 2") return False # Property 3 does not need to be checked, because None is assumed # to be black and is all the leaves. # Property 4 if not self.check_coloring(): print("Property 4") return False # Property 5 if self.black_height() is None: print("Property 5") return False # All properties were met return True def check_coloring(self) -> bool: """A helper function to recursively check Property 4 of a Red-Black Tree. See check_color_properties for more info. """ if self.color == 1: if color(self.left) == 1 or color(self.right) == 1: return False if self.left and not self.left.check_coloring(): return False if self.right and not self.right.check_coloring(): return False return True def black_height(self) -> int | None: """Returns the number of black nodes from this node to the leaves of the tree, or None if there isn't one such value (the tree is color incorrectly). """ if self is None or self.left is None or self.right is None: # If we're already at a leaf, there is no path return 1 left = RedBlackTree.black_height(self.left) right = RedBlackTree.black_height(self.right) if left is None or right is None: # There are issues with coloring below children nodes return None if left != right: # The two children have unequal depths return None # Return the black depth of children, plus one if this node is # black return left + (1 - self.color) # Here are functions which are general to all binary search trees def __contains__(self, label: int) -> bool: """Search through the tree for label, returning True iff it is found somewhere in the tree. Guaranteed to run in O(log(n)) time. """ return self.search(label) is not None def search(self, label: int) -> RedBlackTree | None: """Search through the tree for label, returning its node if it's found, and None otherwise. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self elif self.label is not None and label > self.label: if self.right is None: return None else: return self.right.search(label) else: if self.left is None: return None else: return self.left.search(label) def floor(self, label: int) -> int | None: """Returns the largest element in this tree which is at most label. This method is guaranteed to run in O(log(n)) time.""" if self.label == label: return self.label elif self.label is not None and self.label > label: if self.left: return self.left.floor(label) else: return None else: if self.right: attempt = self.right.floor(label) if attempt is not None: return attempt return self.label def ceil(self, label: int) -> int | None: """Returns the smallest element in this tree which is at least label. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self.label elif self.label is not None and self.label < label: if self.right: return self.right.ceil(label) else: return None else: if self.left: attempt = self.left.ceil(label) if attempt is not None: return attempt return self.label def get_max(self) -> int | None: """Returns the largest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.right: # Go as far right as possible return self.right.get_max() else: return self.label def get_min(self) -> int | None: """Returns the smallest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.left: # Go as far left as possible return self.left.get_min() else: return self.label @property def grandparent(self) -> RedBlackTree | None: """Get the current node's grandparent, or None if it doesn't exist.""" if self.parent is None: return None else: return self.parent.parent @property def sibling(self) -> RedBlackTree | None: """Get the current node's sibling, or None if it doesn't exist.""" if self.parent is None: return None elif self.parent.left is self: return self.parent.right else: return self.parent.left def is_left(self) -> bool: """Returns true iff this node is the left child of its parent.""" if self.parent is None: return False return self.parent.left is self.parent.left is self def is_right(self) -> bool: """Returns true iff this node is the right child of its parent.""" if self.parent is None: return False return self.parent.right is self def __bool__(self) -> bool: return True def __len__(self) -> int: """ Return the number of nodes in this tree. """ ln = 1 if self.left: ln += len(self.left) if self.right: ln += len(self.right) return ln def preorder_traverse(self) -> Iterator[int | None]: yield self.label if self.left: yield from self.left.preorder_traverse() if self.right: yield from self.right.preorder_traverse() def inorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.inorder_traverse() yield self.label if self.right: yield from self.right.inorder_traverse() def postorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.postorder_traverse() if self.right: yield from self.right.postorder_traverse() yield self.label def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.label} {(self.color and 'red') or 'blk'}'" return pformat( { f"{self.label} {(self.color and 'red') or 'blk'}": ( self.left, self.right, ) }, indent=1, ) def __eq__(self, other: object) -> bool: """Test if two trees are equal.""" if not isinstance(other, RedBlackTree): return NotImplemented if self.label == other.label: return self.left == other.left and self.right == other.right else: return False def color(node: RedBlackTree | None) -> int: """Returns the color of a node, allowing for None leaves.""" if node is None: return 0 else: return node.color """ Code for testing the various functions of the red-black tree. """ def test_rotations() -> bool: """Test that the rotate_left and rotate_right functions work.""" # Make a tree to test on tree = RedBlackTree(0) tree.left = RedBlackTree(-10, parent=tree) tree.right = RedBlackTree(10, parent=tree) tree.left.left = RedBlackTree(-20, parent=tree.left) tree.left.right = RedBlackTree(-5, parent=tree.left) tree.right.left = RedBlackTree(5, parent=tree.right) tree.right.right = RedBlackTree(20, parent=tree.right) # Make the right rotation left_rot = RedBlackTree(10) left_rot.left = RedBlackTree(0, parent=left_rot) left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) left_rot.left.right = RedBlackTree(5, parent=left_rot.left) left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) left_rot.right = RedBlackTree(20, parent=left_rot) tree = tree.rotate_left() if tree != left_rot: return False tree = tree.rotate_right() tree = tree.rotate_right() # Make the left rotation right_rot = RedBlackTree(-10) right_rot.left = RedBlackTree(-20, parent=right_rot) right_rot.right = RedBlackTree(0, parent=right_rot) right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) right_rot.right.right = RedBlackTree(10, parent=right_rot.right) right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) if tree != right_rot: return False return True def test_insertion_speed() -> bool: """Test that the tree balances inserts to O(log(n)) by doing a lot of them. """ tree = RedBlackTree(-1) for i in range(300000): tree = tree.insert(i) return True def test_insert() -> bool: """Test the insert() method of the tree correctly balances, colors, and inserts. """ tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) ans = RedBlackTree(0, 0) ans.left = RedBlackTree(-8, 0, ans) ans.right = RedBlackTree(8, 1, ans) ans.right.left = RedBlackTree(4, 0, ans.right) ans.right.right = RedBlackTree(11, 0, ans.right) ans.right.right.left = RedBlackTree(10, 1, ans.right.right) ans.right.right.right = RedBlackTree(12, 1, ans.right.right) return tree == ans def test_insert_and_search() -> bool: """Tests searching through the tree for values.""" tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) if 5 in tree or -6 in tree or -10 in tree or 13 in tree: # Found something not in there return False if not (11 in tree and 12 in tree and -8 in tree and 0 in tree): # Didn't find something in there return False return True def test_insert_delete() -> bool: """Test the insert() and delete() method of the tree, verifying the insertion and removal of elements, and the balancing of the tree. """ tree = RedBlackTree(0) tree = tree.insert(-12) tree = tree.insert(8) tree = tree.insert(-8) tree = tree.insert(15) tree = tree.insert(4) tree = tree.insert(12) tree = tree.insert(10) tree = tree.insert(9) tree = tree.insert(11) tree = tree.remove(15) tree = tree.remove(-12) tree = tree.remove(9) if not tree.check_color_properties(): return False if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]: return False return True def test_floor_ceil() -> bool: """Tests the floor and ceiling functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] for val, floor, ceil in tuples: if tree.floor(val) != floor or tree.ceil(val) != ceil: return False return True def test_min_max() -> bool: """Tests the min and max functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if tree.get_max() != 22 or tree.get_min() != -16: return False return True def test_tree_traversal() -> bool: """Tests the three different tree traversal functions.""" tree = RedBlackTree(0) tree = tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def test_tree_chaining() -> bool: """Tests the three different tree chaining functions.""" tree = RedBlackTree(0) tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_rotations() assert test_insert() assert test_insert_and_search() assert test_insert_delete() assert test_floor_ceil() assert test_tree_traversal() assert test_tree_chaining() def main() -> None: """ >>> pytests() """ print_results("Rotating right and left", test_rotations()) print_results("Inserting", test_insert()) print_results("Searching", test_insert_and_search()) print_results("Deleting", test_insert_delete()) print_results("Floor and ceil", test_floor_ceil()) print_results("Tree traversal", test_tree_traversal()) print_results("Tree traversal", test_tree_chaining()) print("Testing tree balancing...") print("This should only be a few seconds.") test_insertion_speed() print("Done!") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def topologicalSort(graph): """ Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS """ indegree = [0] * len(graph) queue = [] topo = [] cnt = 0 for key, values in graph.items(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) cnt += 1 topo.append(vertex) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(x) if cnt != len(graph): print("Cycle exists") else: print(topo) # Adjacency List of Graph graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topologicalSort(graph)
def topologicalSort(graph): """ Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS """ indegree = [0] * len(graph) queue = [] topo = [] cnt = 0 for key, values in graph.items(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) cnt += 1 topo.append(vertex) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(x) if cnt != len(graph): print("Cycle exists") else: print(topo) # Adjacency List of Graph graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topologicalSort(graph)
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a*b*c. References: - https://en.wikipedia.org/wiki/Pythagorean_triple """ def solution() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution() 31875000 """ for a in range(300): for b in range(a + 1, 400): for c in range(b + 1, 500): if (a + b + c) == 1000: if (a**2) + (b**2) == (c**2): return a * b * c return -1 def solution_fast() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution_fast() 31875000 """ for a in range(300): for b in range(400): c = 1000 - a - b if a < b < c and (a**2) + (b**2) == (c**2): return a * b * c return -1 def benchmark() -> None: """ Benchmark code comparing two different version function. """ import timeit print( timeit.timeit("solution()", setup="from __main__ import solution", number=1000) ) print( timeit.timeit( "solution_fast()", setup="from __main__ import solution_fast", number=1000 ) ) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a*b*c. References: - https://en.wikipedia.org/wiki/Pythagorean_triple """ def solution() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution() 31875000 """ for a in range(300): for b in range(a + 1, 400): for c in range(b + 1, 500): if (a + b + c) == 1000: if (a**2) + (b**2) == (c**2): return a * b * c return -1 def solution_fast() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution_fast() 31875000 """ for a in range(300): for b in range(400): c = 1000 - a - b if a < b < c and (a**2) + (b**2) == (c**2): return a * b * c return -1 def benchmark() -> None: """ Benchmark code comparing two different version function. """ import timeit print( timeit.timeit("solution()", setup="from __main__ import solution", number=1000) ) print( timeit.timeit( "solution_fast()", setup="from __main__ import solution_fast", number=1000 ) ) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A Python implementation of the quick select algorithm, which is efficient for calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted https://en.wikipedia.org/wiki/Quickselect """ import random def _partition(data: list, pivot) -> tuple: """ Three way partition the data into smaller, equal and greater lists, in relationship to the pivot :param data: The data to be sorted (a list) :param pivot: The value to partition the data on :return: Three list: smaller, equal and greater """ less, equal, greater = [], [], [] for element in data: if element < pivot: less.append(element) elif element > pivot: greater.append(element) else: equal.append(element) return less, equal, greater def quick_select(items: list, index: int): """ >>> quick_select([2, 4, 5, 7, 899, 54, 32], 5) 54 >>> quick_select([2, 4, 5, 7, 899, 54, 32], 1) 4 >>> quick_select([5, 4, 3, 2], 2) 4 >>> quick_select([3, 5, 7, 10, 2, 12], 3) 7 """ # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(items) or index < 0: return None pivot = items[random.randint(0, len(items) - 1)] count = 0 smaller, equal, larger = _partition(items, pivot) count = len(equal) m = len(smaller) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(smaller, index) # must be in larger else: return quick_select(larger, index - (m + count))
""" A Python implementation of the quick select algorithm, which is efficient for calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted https://en.wikipedia.org/wiki/Quickselect """ import random def _partition(data: list, pivot) -> tuple: """ Three way partition the data into smaller, equal and greater lists, in relationship to the pivot :param data: The data to be sorted (a list) :param pivot: The value to partition the data on :return: Three list: smaller, equal and greater """ less, equal, greater = [], [], [] for element in data: if element < pivot: less.append(element) elif element > pivot: greater.append(element) else: equal.append(element) return less, equal, greater def quick_select(items: list, index: int): """ >>> quick_select([2, 4, 5, 7, 899, 54, 32], 5) 54 >>> quick_select([2, 4, 5, 7, 899, 54, 32], 1) 4 >>> quick_select([5, 4, 3, 2], 2) 4 >>> quick_select([3, 5, 7, 10, 2, 12], 3) 7 """ # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(items) or index < 0: return None pivot = items[random.randint(0, len(items) - 1)] count = 0 smaller, equal, larger = _partition(items, pivot) count = len(equal) m = len(smaller) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(smaller, index) # must be in larger else: return quick_select(larger, index - (m + count))
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#
#
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Convert between different units of temperature """ def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> celsius_to_fahrenheit(273.354, 3) 524.037 >>> celsius_to_fahrenheit(273.354, 0) 524.0 >>> celsius_to_fahrenheit(-40.0) -40.0 >>> celsius_to_fahrenheit(-20.0) -4.0 >>> celsius_to_fahrenheit(0) 32.0 >>> celsius_to_fahrenheit(20) 68.0 >>> celsius_to_fahrenheit("40") 104.0 >>> celsius_to_fahrenheit("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 32, ndigits) def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> celsius_to_kelvin(273.354, 3) 546.504 >>> celsius_to_kelvin(273.354, 0) 547.0 >>> celsius_to_kelvin(0) 273.15 >>> celsius_to_kelvin(20.0) 293.15 >>> celsius_to_kelvin("40") 313.15 >>> celsius_to_kelvin("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round(float(celsius) + 273.15, ndigits) def celsius_to_rankine(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> celsius_to_rankine(273.354, 3) 983.707 >>> celsius_to_rankine(273.354, 0) 984.0 >>> celsius_to_rankine(0) 491.67 >>> celsius_to_rankine(20.0) 527.67 >>> celsius_to_rankine("40") 563.67 >>> celsius_to_rankine("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 491.67, ndigits) def fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> fahrenheit_to_celsius(273.354, 3) 134.086 >>> fahrenheit_to_celsius(273.354, 0) 134.0 >>> fahrenheit_to_celsius(0) -17.78 >>> fahrenheit_to_celsius(20.0) -6.67 >>> fahrenheit_to_celsius(40.0) 4.44 >>> fahrenheit_to_celsius(60) 15.56 >>> fahrenheit_to_celsius(80) 26.67 >>> fahrenheit_to_celsius("100") 37.78 >>> fahrenheit_to_celsius("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round((float(fahrenheit) - 32) * 5 / 9, ndigits) def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> fahrenheit_to_kelvin(273.354, 3) 407.236 >>> fahrenheit_to_kelvin(273.354, 0) 407.0 >>> fahrenheit_to_kelvin(0) 255.37 >>> fahrenheit_to_kelvin(20.0) 266.48 >>> fahrenheit_to_kelvin(40.0) 277.59 >>> fahrenheit_to_kelvin(60) 288.71 >>> fahrenheit_to_kelvin(80) 299.82 >>> fahrenheit_to_kelvin("100") 310.93 >>> fahrenheit_to_kelvin("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(((float(fahrenheit) - 32) * 5 / 9) + 273.15, ndigits) def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> fahrenheit_to_rankine(273.354, 3) 733.024 >>> fahrenheit_to_rankine(273.354, 0) 733.0 >>> fahrenheit_to_rankine(0) 459.67 >>> fahrenheit_to_rankine(20.0) 479.67 >>> fahrenheit_to_rankine(40.0) 499.67 >>> fahrenheit_to_rankine(60) 519.67 >>> fahrenheit_to_rankine(80) 539.67 >>> fahrenheit_to_rankine("100") 559.67 >>> fahrenheit_to_rankine("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(float(fahrenheit) + 459.67, ndigits) def kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> kelvin_to_celsius(273.354, 3) 0.204 >>> kelvin_to_celsius(273.354, 0) 0.0 >>> kelvin_to_celsius(273.15) 0.0 >>> kelvin_to_celsius(300) 26.85 >>> kelvin_to_celsius("315.5") 42.35 >>> kelvin_to_celsius("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(float(kelvin) - 273.15, ndigits) def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> kelvin_to_fahrenheit(273.354, 3) 32.367 >>> kelvin_to_fahrenheit(273.354, 0) 32.0 >>> kelvin_to_fahrenheit(273.15) 32.0 >>> kelvin_to_fahrenheit(300) 80.33 >>> kelvin_to_fahrenheit("315.5") 108.23 >>> kelvin_to_fahrenheit("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(((float(kelvin) - 273.15) * 9 / 5) + 32, ndigits) def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> kelvin_to_rankine(273.354, 3) 492.037 >>> kelvin_to_rankine(273.354, 0) 492.0 >>> kelvin_to_rankine(0) 0.0 >>> kelvin_to_rankine(20.0) 36.0 >>> kelvin_to_rankine("40") 72.0 >>> kelvin_to_rankine("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round((float(kelvin) * 9 / 5), ndigits) def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> rankine_to_celsius(273.354, 3) -121.287 >>> rankine_to_celsius(273.354, 0) -121.0 >>> rankine_to_celsius(273.15) -121.4 >>> rankine_to_celsius(300) -106.48 >>> rankine_to_celsius("315.5") -97.87 >>> rankine_to_celsius("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) - 491.67) * 5 / 9, ndigits) def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> rankine_to_fahrenheit(273.15) -186.52 >>> rankine_to_fahrenheit(300) -159.67 >>> rankine_to_fahrenheit("315.5") -144.17 >>> rankine_to_fahrenheit("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round(float(rankine) - 459.67, ndigits) def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> rankine_to_kelvin(0) 0.0 >>> rankine_to_kelvin(20.0) 11.11 >>> rankine_to_kelvin("40") 22.22 >>> rankine_to_kelvin("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) * 5 / 9), ndigits) def reaumur_to_kelvin(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to Kelvin and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_kelvin(0) 273.15 >>> reaumur_to_kelvin(20.0) 298.15 >>> reaumur_to_kelvin(40) 323.15 >>> reaumur_to_kelvin("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25 + 273.15), ndigits) def reaumur_to_fahrenheit(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to fahrenheit and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_fahrenheit(0) 32.0 >>> reaumur_to_fahrenheit(20.0) 77.0 >>> reaumur_to_fahrenheit(40) 122.0 >>> reaumur_to_fahrenheit("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32), ndigits) def reaumur_to_celsius(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to celsius and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_celsius(0) 0.0 >>> reaumur_to_celsius(20.0) 25.0 >>> reaumur_to_celsius(40) 50.0 >>> reaumur_to_celsius("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25), ndigits) def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to rankine and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_rankine(0) 491.67 >>> reaumur_to_rankine(20.0) 536.67 >>> reaumur_to_rankine(40) 581.67 >>> reaumur_to_rankine("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32 + 459.67), ndigits) if __name__ == "__main__": import doctest doctest.testmod()
""" Convert between different units of temperature """ def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> celsius_to_fahrenheit(273.354, 3) 524.037 >>> celsius_to_fahrenheit(273.354, 0) 524.0 >>> celsius_to_fahrenheit(-40.0) -40.0 >>> celsius_to_fahrenheit(-20.0) -4.0 >>> celsius_to_fahrenheit(0) 32.0 >>> celsius_to_fahrenheit(20) 68.0 >>> celsius_to_fahrenheit("40") 104.0 >>> celsius_to_fahrenheit("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 32, ndigits) def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> celsius_to_kelvin(273.354, 3) 546.504 >>> celsius_to_kelvin(273.354, 0) 547.0 >>> celsius_to_kelvin(0) 273.15 >>> celsius_to_kelvin(20.0) 293.15 >>> celsius_to_kelvin("40") 313.15 >>> celsius_to_kelvin("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round(float(celsius) + 273.15, ndigits) def celsius_to_rankine(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> celsius_to_rankine(273.354, 3) 983.707 >>> celsius_to_rankine(273.354, 0) 984.0 >>> celsius_to_rankine(0) 491.67 >>> celsius_to_rankine(20.0) 527.67 >>> celsius_to_rankine("40") 563.67 >>> celsius_to_rankine("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 491.67, ndigits) def fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> fahrenheit_to_celsius(273.354, 3) 134.086 >>> fahrenheit_to_celsius(273.354, 0) 134.0 >>> fahrenheit_to_celsius(0) -17.78 >>> fahrenheit_to_celsius(20.0) -6.67 >>> fahrenheit_to_celsius(40.0) 4.44 >>> fahrenheit_to_celsius(60) 15.56 >>> fahrenheit_to_celsius(80) 26.67 >>> fahrenheit_to_celsius("100") 37.78 >>> fahrenheit_to_celsius("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round((float(fahrenheit) - 32) * 5 / 9, ndigits) def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> fahrenheit_to_kelvin(273.354, 3) 407.236 >>> fahrenheit_to_kelvin(273.354, 0) 407.0 >>> fahrenheit_to_kelvin(0) 255.37 >>> fahrenheit_to_kelvin(20.0) 266.48 >>> fahrenheit_to_kelvin(40.0) 277.59 >>> fahrenheit_to_kelvin(60) 288.71 >>> fahrenheit_to_kelvin(80) 299.82 >>> fahrenheit_to_kelvin("100") 310.93 >>> fahrenheit_to_kelvin("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(((float(fahrenheit) - 32) * 5 / 9) + 273.15, ndigits) def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> fahrenheit_to_rankine(273.354, 3) 733.024 >>> fahrenheit_to_rankine(273.354, 0) 733.0 >>> fahrenheit_to_rankine(0) 459.67 >>> fahrenheit_to_rankine(20.0) 479.67 >>> fahrenheit_to_rankine(40.0) 499.67 >>> fahrenheit_to_rankine(60) 519.67 >>> fahrenheit_to_rankine(80) 539.67 >>> fahrenheit_to_rankine("100") 559.67 >>> fahrenheit_to_rankine("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(float(fahrenheit) + 459.67, ndigits) def kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> kelvin_to_celsius(273.354, 3) 0.204 >>> kelvin_to_celsius(273.354, 0) 0.0 >>> kelvin_to_celsius(273.15) 0.0 >>> kelvin_to_celsius(300) 26.85 >>> kelvin_to_celsius("315.5") 42.35 >>> kelvin_to_celsius("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(float(kelvin) - 273.15, ndigits) def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> kelvin_to_fahrenheit(273.354, 3) 32.367 >>> kelvin_to_fahrenheit(273.354, 0) 32.0 >>> kelvin_to_fahrenheit(273.15) 32.0 >>> kelvin_to_fahrenheit(300) 80.33 >>> kelvin_to_fahrenheit("315.5") 108.23 >>> kelvin_to_fahrenheit("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(((float(kelvin) - 273.15) * 9 / 5) + 32, ndigits) def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> kelvin_to_rankine(273.354, 3) 492.037 >>> kelvin_to_rankine(273.354, 0) 492.0 >>> kelvin_to_rankine(0) 0.0 >>> kelvin_to_rankine(20.0) 36.0 >>> kelvin_to_rankine("40") 72.0 >>> kelvin_to_rankine("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round((float(kelvin) * 9 / 5), ndigits) def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> rankine_to_celsius(273.354, 3) -121.287 >>> rankine_to_celsius(273.354, 0) -121.0 >>> rankine_to_celsius(273.15) -121.4 >>> rankine_to_celsius(300) -106.48 >>> rankine_to_celsius("315.5") -97.87 >>> rankine_to_celsius("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) - 491.67) * 5 / 9, ndigits) def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> rankine_to_fahrenheit(273.15) -186.52 >>> rankine_to_fahrenheit(300) -159.67 >>> rankine_to_fahrenheit("315.5") -144.17 >>> rankine_to_fahrenheit("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round(float(rankine) - 459.67, ndigits) def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> rankine_to_kelvin(0) 0.0 >>> rankine_to_kelvin(20.0) 11.11 >>> rankine_to_kelvin("40") 22.22 >>> rankine_to_kelvin("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) * 5 / 9), ndigits) def reaumur_to_kelvin(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to Kelvin and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_kelvin(0) 273.15 >>> reaumur_to_kelvin(20.0) 298.15 >>> reaumur_to_kelvin(40) 323.15 >>> reaumur_to_kelvin("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25 + 273.15), ndigits) def reaumur_to_fahrenheit(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to fahrenheit and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_fahrenheit(0) 32.0 >>> reaumur_to_fahrenheit(20.0) 77.0 >>> reaumur_to_fahrenheit(40) 122.0 >>> reaumur_to_fahrenheit("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32), ndigits) def reaumur_to_celsius(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to celsius and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_celsius(0) 0.0 >>> reaumur_to_celsius(20.0) 25.0 >>> reaumur_to_celsius(40) 50.0 >>> reaumur_to_celsius("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25), ndigits) def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to rankine and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_rankine(0) 491.67 >>> reaumur_to_rankine(20.0) 536.67 >>> reaumur_to_rankine(40) 581.67 >>> reaumur_to_rankine("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32 + 459.67), ndigits) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str: """ For key:hello H E L O A B C D F G I J K M N P Q R S T U V W X Y Z and map vertically >>> mixed_keyword("college", "UNIVERSITY") # doctest: +NORMALIZE_WHITESPACE {'A': 'C', 'B': 'A', 'C': 'I', 'D': 'P', 'E': 'U', 'F': 'Z', 'G': 'O', 'H': 'B', 'I': 'J', 'J': 'Q', 'K': 'V', 'L': 'L', 'M': 'D', 'N': 'K', 'O': 'R', 'P': 'W', 'Q': 'E', 'R': 'F', 'S': 'M', 'T': 'S', 'U': 'X', 'V': 'G', 'W': 'H', 'X': 'N', 'Y': 'T', 'Z': 'Y'} 'XKJGUFMJST' """ key = key.upper() pt = pt.upper() temp = [] for i in key: if i not in temp: temp.append(i) len_temp = len(temp) # print(temp) alpha = [] modalpha = [] for j in range(65, 91): t = chr(j) alpha.append(t) if t not in temp: temp.append(t) # print(temp) r = int(26 / 4) # print(r) k = 0 for _ in range(r): s = [] for j in range(len_temp): s.append(temp[k]) if not (k < 25): break k += 1 modalpha.append(s) # print(modalpha) d = {} j = 0 k = 0 for j in range(len_temp): for m in modalpha: if not (len(m) - 1 >= j): break d[alpha[k]] = m[j] if not k < 25: break k += 1 print(d) cypher = "" for i in pt: cypher += d[i] return cypher print(mixed_keyword("college", "UNIVERSITY"))
def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str: """ For key:hello H E L O A B C D F G I J K M N P Q R S T U V W X Y Z and map vertically >>> mixed_keyword("college", "UNIVERSITY") # doctest: +NORMALIZE_WHITESPACE {'A': 'C', 'B': 'A', 'C': 'I', 'D': 'P', 'E': 'U', 'F': 'Z', 'G': 'O', 'H': 'B', 'I': 'J', 'J': 'Q', 'K': 'V', 'L': 'L', 'M': 'D', 'N': 'K', 'O': 'R', 'P': 'W', 'Q': 'E', 'R': 'F', 'S': 'M', 'T': 'S', 'U': 'X', 'V': 'G', 'W': 'H', 'X': 'N', 'Y': 'T', 'Z': 'Y'} 'XKJGUFMJST' """ key = key.upper() pt = pt.upper() temp = [] for i in key: if i not in temp: temp.append(i) len_temp = len(temp) # print(temp) alpha = [] modalpha = [] for j in range(65, 91): t = chr(j) alpha.append(t) if t not in temp: temp.append(t) # print(temp) r = int(26 / 4) # print(r) k = 0 for _ in range(r): s = [] for j in range(len_temp): s.append(temp[k]) if not (k < 25): break k += 1 modalpha.append(s) # print(modalpha) d = {} j = 0 k = 0 for j in range(len_temp): for m in modalpha: if not (len(m) - 1 >= j): break d[alpha[k]] = m[j] if not k < 25: break k += 1 print(d) cypher = "" for i in pt: cypher += d[i] return cypher print(mixed_keyword("college", "UNIVERSITY"))
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import glob import os import random from string import ascii_lowercase, digits import cv2 """ Flip image and bounding box for computer vision task https://paperswithcode.com/method/randomhorizontalflip """ # Params LABEL_DIR = "" IMAGE_DIR = "" OUTPUT_DIR = "" FLIP_TYPE = 1 # (0 is vertical, 1 is horizontal) def main() -> None: """ Get images list and annotations list from input dir. Update new images and annotations. Save images and annotations in output dir. >>> pass # A doctest is not possible for this function. """ img_paths, annos = get_dataset(LABEL_DIR, IMAGE_DIR) print("Processing...") new_images, new_annos, paths = update_image_and_anno(img_paths, annos, FLIP_TYPE) for index, image in enumerate(new_images): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' letter_code = random_chars(32) file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0] file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}" cv2.imwrite(f"/{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85]) print(f"Success {index+1}/{len(new_images)} with {file_name}") annos_list = [] for anno in new_annos[index]: obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}" annos_list.append(obj) with open(f"/{file_root}.txt", "w") as outfile: outfile.write("\n".join(line for line in annos_list)) def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: """ - label_dir <type: str>: Path to label include annotation of images - img_dir <type: str>: Path to folder contain images Return <type: list>: List of images path and labels >>> pass # A doctest is not possible for this function. """ img_paths = [] labels = [] for label_file in glob.glob(os.path.join(label_dir, "*.txt")): label_name = label_file.split(os.sep)[-1].rsplit(".", 1)[0] with open(label_file) as in_file: obj_lists = in_file.readlines() img_path = os.path.join(img_dir, f"{label_name}.jpg") boxes = [] for obj_list in obj_lists: obj = obj_list.rstrip("\n").split(" ") boxes.append( [ int(obj[0]), float(obj[1]), float(obj[2]), float(obj[3]), float(obj[4]), ] ) if not boxes: continue img_paths.append(img_path) labels.append(boxes) return img_paths, labels def update_image_and_anno( img_list: list, anno_list: list, flip_type: int = 1 ) -> tuple[list, list, list]: """ - img_list <type: list>: list of all images - anno_list <type: list>: list of all annotations of specific image - flip_type <type: int>: 0 is vertical, 1 is horizontal Return: - new_imgs_list <type: narray>: image after resize - new_annos_lists <type: list>: list of new annotation after scale - path_list <type: list>: list the name of image file >>> pass # A doctest is not possible for this function. """ new_annos_lists = [] path_list = [] new_imgs_list = [] for idx in range(len(img_list)): new_annos = [] path = img_list[idx] path_list.append(path) img_annos = anno_list[idx] img = cv2.imread(path) if flip_type == 1: new_img = cv2.flip(img, flip_type) for bbox in img_annos: x_center_new = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]]) elif flip_type == 0: new_img = cv2.flip(img, flip_type) for bbox in img_annos: y_center_new = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]]) new_annos_lists.append(new_annos) new_imgs_list.append(new_img) return new_imgs_list, new_annos_lists, path_list def random_chars(number_char: int = 32) -> str: """ Automatic generate random 32 characters. Get random string code: '7b7ad245cdff75241935e4dd860f3bad' >>> len(random_chars(32)) 32 """ assert number_char > 1, "The number of character should greater than 1" letter_code = ascii_lowercase + digits return "".join(random.choice(letter_code) for _ in range(number_char)) if __name__ == "__main__": main() print("DONE ✅")
import glob import os import random from string import ascii_lowercase, digits import cv2 """ Flip image and bounding box for computer vision task https://paperswithcode.com/method/randomhorizontalflip """ # Params LABEL_DIR = "" IMAGE_DIR = "" OUTPUT_DIR = "" FLIP_TYPE = 1 # (0 is vertical, 1 is horizontal) def main() -> None: """ Get images list and annotations list from input dir. Update new images and annotations. Save images and annotations in output dir. >>> pass # A doctest is not possible for this function. """ img_paths, annos = get_dataset(LABEL_DIR, IMAGE_DIR) print("Processing...") new_images, new_annos, paths = update_image_and_anno(img_paths, annos, FLIP_TYPE) for index, image in enumerate(new_images): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' letter_code = random_chars(32) file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0] file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}" cv2.imwrite(f"/{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85]) print(f"Success {index+1}/{len(new_images)} with {file_name}") annos_list = [] for anno in new_annos[index]: obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}" annos_list.append(obj) with open(f"/{file_root}.txt", "w") as outfile: outfile.write("\n".join(line for line in annos_list)) def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: """ - label_dir <type: str>: Path to label include annotation of images - img_dir <type: str>: Path to folder contain images Return <type: list>: List of images path and labels >>> pass # A doctest is not possible for this function. """ img_paths = [] labels = [] for label_file in glob.glob(os.path.join(label_dir, "*.txt")): label_name = label_file.split(os.sep)[-1].rsplit(".", 1)[0] with open(label_file) as in_file: obj_lists = in_file.readlines() img_path = os.path.join(img_dir, f"{label_name}.jpg") boxes = [] for obj_list in obj_lists: obj = obj_list.rstrip("\n").split(" ") boxes.append( [ int(obj[0]), float(obj[1]), float(obj[2]), float(obj[3]), float(obj[4]), ] ) if not boxes: continue img_paths.append(img_path) labels.append(boxes) return img_paths, labels def update_image_and_anno( img_list: list, anno_list: list, flip_type: int = 1 ) -> tuple[list, list, list]: """ - img_list <type: list>: list of all images - anno_list <type: list>: list of all annotations of specific image - flip_type <type: int>: 0 is vertical, 1 is horizontal Return: - new_imgs_list <type: narray>: image after resize - new_annos_lists <type: list>: list of new annotation after scale - path_list <type: list>: list the name of image file >>> pass # A doctest is not possible for this function. """ new_annos_lists = [] path_list = [] new_imgs_list = [] for idx in range(len(img_list)): new_annos = [] path = img_list[idx] path_list.append(path) img_annos = anno_list[idx] img = cv2.imread(path) if flip_type == 1: new_img = cv2.flip(img, flip_type) for bbox in img_annos: x_center_new = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]]) elif flip_type == 0: new_img = cv2.flip(img, flip_type) for bbox in img_annos: y_center_new = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]]) new_annos_lists.append(new_annos) new_imgs_list.append(new_img) return new_imgs_list, new_annos_lists, path_list def random_chars(number_char: int = 32) -> str: """ Automatic generate random 32 characters. Get random string code: '7b7ad245cdff75241935e4dd860f3bad' >>> len(random_chars(32)) 32 """ assert number_char > 1, "The number of character should greater than 1" letter_code = ascii_lowercase + digits return "".join(random.choice(letter_code) for _ in range(number_char)) if __name__ == "__main__": main() print("DONE ✅")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power. How many n-digit positive integers exist which are also an nth power? """ """ The maximum base can be 9 because all n-digit numbers < 10^n. Now 9**23 has 22 digits so the maximum power can be 22. Using these conclusions, we will calculate the result. """ def solution(max_base: int = 10, max_power: int = 22) -> int: """ Returns the count of all n-digit numbers which are nth power >>> solution(10, 22) 49 >>> solution(0, 0) 0 >>> solution(1, 1) 0 >>> solution(-1, -1) 0 """ bases = range(1, max_base) powers = range(1, max_power) return sum( 1 for power in powers for base in bases if len(str(base**power)) == power ) if __name__ == "__main__": print(f"{solution(10, 22) = }")
""" The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power. How many n-digit positive integers exist which are also an nth power? """ """ The maximum base can be 9 because all n-digit numbers < 10^n. Now 9**23 has 22 digits so the maximum power can be 22. Using these conclusions, we will calculate the result. """ def solution(max_base: int = 10, max_power: int = 22) -> int: """ Returns the count of all n-digit numbers which are nth power >>> solution(10, 22) 49 >>> solution(0, 0) 0 >>> solution(1, 1) 0 >>> solution(-1, -1) 0 """ bases = range(1, max_base) powers = range(1, max_power) return sum( 1 for power in powers for base in bases if len(str(base**power)) == power ) if __name__ == "__main__": print(f"{solution(10, 22) = }")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of an auto-balanced binary tree! For doctests run following command: python3 -m doctest -v avl_tree.py For testing run: python avl_tree.py """ from __future__ import annotations import math import random from typing import Any class my_queue: def __init__(self) -> None: self.data: list[Any] = [] self.head: int = 0 self.tail: int = 0 def is_empty(self) -> bool: return self.head == self.tail def push(self, data: Any) -> None: self.data.append(data) self.tail = self.tail + 1 def pop(self) -> Any: ret = self.data[self.head] self.head = self.head + 1 return ret def count(self) -> int: return self.tail - self.head def print(self) -> None: print(self.data) print("**************") print(self.data[self.head : self.tail]) class my_node: def __init__(self, data: Any) -> None: self.data = data self.left: my_node | None = None self.right: my_node | None = None self.height: int = 1 def get_data(self) -> Any: return self.data def get_left(self) -> my_node | None: return self.left def get_right(self) -> my_node | None: return self.right def get_height(self) -> int: return self.height def set_data(self, data: Any) -> None: self.data = data return def set_left(self, node: my_node | None) -> None: self.left = node return def set_right(self, node: my_node | None) -> None: self.right = node return def set_height(self, height: int) -> None: self.height = height return def get_height(node: my_node | None) -> int: if node is None: return 0 return node.get_height() def my_max(a: int, b: int) -> int: if a > b: return a return b def right_rotation(node: my_node) -> my_node: r""" A B / \ / \ B C Bl A / \ --> / / \ Bl Br UB Br C / UB UB = unbalanced node """ print("left rotation node:", node.get_data()) ret = node.get_left() assert ret is not None node.set_left(ret.get_right()) ret.set_right(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret def left_rotation(node: my_node) -> my_node: """ a mirror symmetry rotation of the left_rotation """ print("right rotation node:", node.get_data()) ret = node.get_right() assert ret is not None node.set_right(ret.get_left()) ret.set_left(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret def lr_rotation(node: my_node) -> my_node: r""" A A Br / \ / \ / \ B C LR Br C RR B A / \ --> / \ --> / / \ Bl Br B UB Bl UB C \ / UB Bl RR = right_rotation LR = left_rotation """ left_child = node.get_left() assert left_child is not None node.set_left(left_rotation(left_child)) return right_rotation(node) def rl_rotation(node: my_node) -> my_node: right_child = node.get_right() assert right_child is not None node.set_right(right_rotation(right_child)) return left_rotation(node) def insert_node(node: my_node | None, data: Any) -> my_node | None: if node is None: return my_node(data) if data < node.get_data(): node.set_left(insert_node(node.get_left(), data)) if ( get_height(node.get_left()) - get_height(node.get_right()) == 2 ): # an unbalance detected left_child = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child node = right_rotation(node) else: node = lr_rotation(node) else: node.set_right(insert_node(node.get_right(), data)) if get_height(node.get_right()) - get_height(node.get_left()) == 2: right_child = node.get_right() assert right_child is not None if data < right_child.get_data(): node = rl_rotation(node) else: node = left_rotation(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) return node def get_rightMost(root: my_node) -> Any: while True: right_child = root.get_right() if right_child is None: break root = right_child return root.get_data() def get_leftMost(root: my_node) -> Any: while True: left_child = root.get_left() if left_child is None: break root = left_child return root.get_data() def del_node(root: my_node, data: Any) -> my_node | None: left_child = root.get_left() right_child = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: temp_data = get_leftMost(right_child) root.set_data(temp_data) root.set_right(del_node(right_child, temp_data)) elif left_child is not None: root = left_child elif right_child is not None: root = right_child else: return None elif root.get_data() > data: if left_child is None: print("No such data") return root else: root.set_left(del_node(left_child, data)) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(right_child, data)) if get_height(right_child) - get_height(left_child) == 2: assert right_child is not None if get_height(right_child.get_right()) > get_height(right_child.get_left()): root = left_rotation(root) else: root = rl_rotation(root) elif get_height(right_child) - get_height(left_child) == -2: assert left_child is not None if get_height(left_child.get_left()) > get_height(left_child.get_right()): root = right_rotation(root) else: root = lr_rotation(root) height = my_max(get_height(root.get_right()), get_height(root.get_left())) + 1 root.set_height(height) return root class AVLtree: """ An AVL tree doctest Examples: >>> t = AVLtree() >>> t.insert(4) insert:4 >>> print(str(t).replace(" \\n","\\n")) 4 ************************************* >>> t.insert(2) insert:2 >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) 4 2 * ************************************* >>> t.insert(3) insert:3 right rotation node: 2 left rotation node: 4 >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) 3 2 4 ************************************* >>> t.get_height() 2 >>> t.del_node(3) delete:3 >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) 4 2 * ************************************* """ def __init__(self) -> None: self.root: my_node | None = None def get_height(self) -> int: return get_height(self.root) def insert(self, data: Any) -> None: print("insert:" + str(data)) self.root = insert_node(self.root, data) def del_node(self, data: Any) -> None: print("delete:" + str(data)) if self.root is None: print("Tree is empty!") return self.root = del_node(self.root, data) def __str__( self, ) -> str: # a level traversale, gives a more intuitive look on the tree output = "" q = my_queue() q.push(self.root) layer = self.get_height() if layer == 0: return output cnt = 0 while not q.is_empty(): node = q.pop() space = " " * int(math.pow(2, layer - 1)) output += space if node is None: output += "*" q.push(None) q.push(None) else: output += str(node.get_data()) q.push(node.get_left()) q.push(node.get_right()) output += space cnt = cnt + 1 for i in range(100): if cnt == math.pow(2, i) - 1: layer = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def _test() -> None: import doctest doctest.testmod() if __name__ == "__main__": _test() t = AVLtree() lst = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
""" Implementation of an auto-balanced binary tree! For doctests run following command: python3 -m doctest -v avl_tree.py For testing run: python avl_tree.py """ from __future__ import annotations import math import random from typing import Any class my_queue: def __init__(self) -> None: self.data: list[Any] = [] self.head: int = 0 self.tail: int = 0 def is_empty(self) -> bool: return self.head == self.tail def push(self, data: Any) -> None: self.data.append(data) self.tail = self.tail + 1 def pop(self) -> Any: ret = self.data[self.head] self.head = self.head + 1 return ret def count(self) -> int: return self.tail - self.head def print(self) -> None: print(self.data) print("**************") print(self.data[self.head : self.tail]) class my_node: def __init__(self, data: Any) -> None: self.data = data self.left: my_node | None = None self.right: my_node | None = None self.height: int = 1 def get_data(self) -> Any: return self.data def get_left(self) -> my_node | None: return self.left def get_right(self) -> my_node | None: return self.right def get_height(self) -> int: return self.height def set_data(self, data: Any) -> None: self.data = data return def set_left(self, node: my_node | None) -> None: self.left = node return def set_right(self, node: my_node | None) -> None: self.right = node return def set_height(self, height: int) -> None: self.height = height return def get_height(node: my_node | None) -> int: if node is None: return 0 return node.get_height() def my_max(a: int, b: int) -> int: if a > b: return a return b def right_rotation(node: my_node) -> my_node: r""" A B / \ / \ B C Bl A / \ --> / / \ Bl Br UB Br C / UB UB = unbalanced node """ print("left rotation node:", node.get_data()) ret = node.get_left() assert ret is not None node.set_left(ret.get_right()) ret.set_right(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret def left_rotation(node: my_node) -> my_node: """ a mirror symmetry rotation of the left_rotation """ print("right rotation node:", node.get_data()) ret = node.get_right() assert ret is not None node.set_right(ret.get_left()) ret.set_left(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret def lr_rotation(node: my_node) -> my_node: r""" A A Br / \ / \ / \ B C LR Br C RR B A / \ --> / \ --> / / \ Bl Br B UB Bl UB C \ / UB Bl RR = right_rotation LR = left_rotation """ left_child = node.get_left() assert left_child is not None node.set_left(left_rotation(left_child)) return right_rotation(node) def rl_rotation(node: my_node) -> my_node: right_child = node.get_right() assert right_child is not None node.set_right(right_rotation(right_child)) return left_rotation(node) def insert_node(node: my_node | None, data: Any) -> my_node | None: if node is None: return my_node(data) if data < node.get_data(): node.set_left(insert_node(node.get_left(), data)) if ( get_height(node.get_left()) - get_height(node.get_right()) == 2 ): # an unbalance detected left_child = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child node = right_rotation(node) else: node = lr_rotation(node) else: node.set_right(insert_node(node.get_right(), data)) if get_height(node.get_right()) - get_height(node.get_left()) == 2: right_child = node.get_right() assert right_child is not None if data < right_child.get_data(): node = rl_rotation(node) else: node = left_rotation(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) return node def get_rightMost(root: my_node) -> Any: while True: right_child = root.get_right() if right_child is None: break root = right_child return root.get_data() def get_leftMost(root: my_node) -> Any: while True: left_child = root.get_left() if left_child is None: break root = left_child return root.get_data() def del_node(root: my_node, data: Any) -> my_node | None: left_child = root.get_left() right_child = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: temp_data = get_leftMost(right_child) root.set_data(temp_data) root.set_right(del_node(right_child, temp_data)) elif left_child is not None: root = left_child elif right_child is not None: root = right_child else: return None elif root.get_data() > data: if left_child is None: print("No such data") return root else: root.set_left(del_node(left_child, data)) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(right_child, data)) if get_height(right_child) - get_height(left_child) == 2: assert right_child is not None if get_height(right_child.get_right()) > get_height(right_child.get_left()): root = left_rotation(root) else: root = rl_rotation(root) elif get_height(right_child) - get_height(left_child) == -2: assert left_child is not None if get_height(left_child.get_left()) > get_height(left_child.get_right()): root = right_rotation(root) else: root = lr_rotation(root) height = my_max(get_height(root.get_right()), get_height(root.get_left())) + 1 root.set_height(height) return root class AVLtree: """ An AVL tree doctest Examples: >>> t = AVLtree() >>> t.insert(4) insert:4 >>> print(str(t).replace(" \\n","\\n")) 4 ************************************* >>> t.insert(2) insert:2 >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) 4 2 * ************************************* >>> t.insert(3) insert:3 right rotation node: 2 left rotation node: 4 >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) 3 2 4 ************************************* >>> t.get_height() 2 >>> t.del_node(3) delete:3 >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) 4 2 * ************************************* """ def __init__(self) -> None: self.root: my_node | None = None def get_height(self) -> int: return get_height(self.root) def insert(self, data: Any) -> None: print("insert:" + str(data)) self.root = insert_node(self.root, data) def del_node(self, data: Any) -> None: print("delete:" + str(data)) if self.root is None: print("Tree is empty!") return self.root = del_node(self.root, data) def __str__( self, ) -> str: # a level traversale, gives a more intuitive look on the tree output = "" q = my_queue() q.push(self.root) layer = self.get_height() if layer == 0: return output cnt = 0 while not q.is_empty(): node = q.pop() space = " " * int(math.pow(2, layer - 1)) output += space if node is None: output += "*" q.push(None) q.push(None) else: output += str(node.get_data()) q.push(node.get_left()) q.push(node.get_right()) output += space cnt = cnt + 1 for i in range(100): if cnt == math.pow(2, i) - 1: layer = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def _test() -> None: import doctest doctest.testmod() if __name__ == "__main__": _test() t = AVLtree() lst = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Absolute Value.""" def abs_val(num): """ Find the absolute value of a number. >>> abs_val(-5.1) 5.1 >>> abs_val(-5) == abs_val(5) True >>> abs_val(0) 0 """ return -num if num < 0 else num def test_abs_val(): """ >>> test_abs_val() """ assert 0 == abs_val(0) assert 34 == abs_val(34) assert 100000000000 == abs_val(-100000000000) if __name__ == "__main__": print(abs_val(-34)) # --> 34
"""Absolute Value.""" def abs_val(num): """ Find the absolute value of a number. >>> abs_val(-5.1) 5.1 >>> abs_val(-5) == abs_val(5) True >>> abs_val(0) 0 """ return -num if num < 0 else num def test_abs_val(): """ >>> test_abs_val() """ assert 0 == abs_val(0) assert 34 == abs_val(34) assert 100000000000 == abs_val(-100000000000) if __name__ == "__main__": print(abs_val(-34)) # --> 34
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def stable_matching( donor_pref: list[list[int]], recipient_pref: list[list[int]] ) -> list[int]: """ Finds the stable match in any bipartite graph, i.e a pairing where no 2 objects prefer each other over their partner. The function accepts the preferences of oegan donors and recipients (where both are assigned numbers from 0 to n-1) and returns a list where the index position corresponds to the donor and value at the index is the organ recipient. To better understand the algorithm, see also: https://github.com/akashvshroff/Gale_Shapley_Stable_Matching (README). https://www.youtube.com/watch?v=Qcv1IqHWAzg&t=13s (Numberphile YouTube). >>> donor_pref = [[0, 1, 3, 2], [0, 2, 3, 1], [1, 0, 2, 3], [0, 3, 1, 2]] >>> recipient_pref = [[3, 1, 2, 0], [3, 1, 0, 2], [0, 3, 1, 2], [1, 0, 3, 2]] >>> print(stable_matching(donor_pref, recipient_pref)) [1, 2, 3, 0] """ assert len(donor_pref) == len(recipient_pref) n = len(donor_pref) unmatched_donors = list(range(n)) donor_record = [-1] * n # who the donor has donated to rec_record = [-1] * n # who the recipient has received from num_donations = [0] * n while unmatched_donors: donor = unmatched_donors[0] donor_preference = donor_pref[donor] recipient = donor_preference[num_donations[donor]] num_donations[donor] += 1 rec_preference = recipient_pref[recipient] prev_donor = rec_record[recipient] if prev_donor != -1: if rec_preference.index(prev_donor) > rec_preference.index(donor): rec_record[recipient] = donor donor_record[donor] = recipient unmatched_donors.append(prev_donor) unmatched_donors.remove(donor) else: rec_record[recipient] = donor donor_record[donor] = recipient unmatched_donors.remove(donor) return donor_record
from __future__ import annotations def stable_matching( donor_pref: list[list[int]], recipient_pref: list[list[int]] ) -> list[int]: """ Finds the stable match in any bipartite graph, i.e a pairing where no 2 objects prefer each other over their partner. The function accepts the preferences of oegan donors and recipients (where both are assigned numbers from 0 to n-1) and returns a list where the index position corresponds to the donor and value at the index is the organ recipient. To better understand the algorithm, see also: https://github.com/akashvshroff/Gale_Shapley_Stable_Matching (README). https://www.youtube.com/watch?v=Qcv1IqHWAzg&t=13s (Numberphile YouTube). >>> donor_pref = [[0, 1, 3, 2], [0, 2, 3, 1], [1, 0, 2, 3], [0, 3, 1, 2]] >>> recipient_pref = [[3, 1, 2, 0], [3, 1, 0, 2], [0, 3, 1, 2], [1, 0, 3, 2]] >>> print(stable_matching(donor_pref, recipient_pref)) [1, 2, 3, 0] """ assert len(donor_pref) == len(recipient_pref) n = len(donor_pref) unmatched_donors = list(range(n)) donor_record = [-1] * n # who the donor has donated to rec_record = [-1] * n # who the recipient has received from num_donations = [0] * n while unmatched_donors: donor = unmatched_donors[0] donor_preference = donor_pref[donor] recipient = donor_preference[num_donations[donor]] num_donations[donor] += 1 rec_preference = recipient_pref[recipient] prev_donor = rec_record[recipient] if prev_donor != -1: if rec_preference.index(prev_donor) > rec_preference.index(donor): rec_record[recipient] = donor donor_record[donor] = recipient unmatched_donors.append(prev_donor) unmatched_donors.remove(donor) else: rec_record[recipient] = donor donor_record[donor] = recipient unmatched_donors.remove(donor) return donor_record
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Approximization algorithm for minimum vertex cover problem. Matching Approach. Uses graphs represented with an adjacency list URL: https://mathworld.wolfram.com/MinimumVertexCover.html URL: https://www.princeton.edu/~aaa/Public/Teaching/ORF523/ORF523_Lec6.pdf """ def matching_min_vertex_cover(graph: dict) -> set: """ APX Algorithm for min Vertex Cover using Matching Approach @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} >>> matching_min_vertex_cover(graph) {0, 1, 2, 4} """ # chosen_vertices = set of chosen vertices chosen_vertices = set() # edges = list of graph's edges edges = get_edges(graph) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: from_node, to_node = edges.pop() chosen_vertices.add(from_node) chosen_vertices.add(to_node) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(edge) return chosen_vertices def get_edges(graph: dict) -> set: """ Return a set of couples that represents all of the edges. @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3], 3: [0, 1, 2]} >>> get_edges(graph) {(0, 1), (3, 1), (0, 3), (2, 0), (3, 0), (2, 3), (1, 0), (3, 2), (1, 3)} """ edges = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node)) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Approximization algorithm for minimum vertex cover problem. Matching Approach. Uses graphs represented with an adjacency list URL: https://mathworld.wolfram.com/MinimumVertexCover.html URL: https://www.princeton.edu/~aaa/Public/Teaching/ORF523/ORF523_Lec6.pdf """ def matching_min_vertex_cover(graph: dict) -> set: """ APX Algorithm for min Vertex Cover using Matching Approach @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} >>> matching_min_vertex_cover(graph) {0, 1, 2, 4} """ # chosen_vertices = set of chosen vertices chosen_vertices = set() # edges = list of graph's edges edges = get_edges(graph) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: from_node, to_node = edges.pop() chosen_vertices.add(from_node) chosen_vertices.add(to_node) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(edge) return chosen_vertices def get_edges(graph: dict) -> set: """ Return a set of couples that represents all of the edges. @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3], 3: [0, 1, 2]} >>> get_edges(graph) {(0, 1), (3, 1), (0, 3), (2, 0), (3, 0), (2, 3), (1, 0), (3, 2), (1, 3)} """ edges = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node)) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of gaussian filter algorithm """ from itertools import product from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uint8, zeros def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = mgrid[0 - center : k_size - center, 0 - center : k_size - center] g = 1 / (2 * pi * sigma) * exp(-(square(x) + square(y)) / (2 * square(sigma))) return g def gaussian_filter(image, k_size, sigma): height, width = image.shape[0], image.shape[1] # dst image height and width dst_height = height - k_size + 1 dst_width = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows image_array = zeros((dst_height * dst_width, k_size * k_size)) row = 0 for i, j in product(range(dst_height), range(dst_width)): window = ravel(image[i : i + k_size, j : j + k_size]) image_array[row, :] = window row += 1 # turn the kernel into shape(k*k, 1) gaussian_kernel = gen_gaussian_kernel(k_size, sigma) filter_array = ravel(gaussian_kernel) # reshape and get the dst image dst = dot(image_array, filter_array).reshape(dst_height, dst_width).astype(uint8) return dst if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size gaussian3x3 = gaussian_filter(gray, 3, sigma=1) gaussian5x5 = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow("gaussian filter with 3x3 mask", gaussian3x3) imshow("gaussian filter with 5x5 mask", gaussian5x5) waitKey()
""" Implementation of gaussian filter algorithm """ from itertools import product from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uint8, zeros def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = mgrid[0 - center : k_size - center, 0 - center : k_size - center] g = 1 / (2 * pi * sigma) * exp(-(square(x) + square(y)) / (2 * square(sigma))) return g def gaussian_filter(image, k_size, sigma): height, width = image.shape[0], image.shape[1] # dst image height and width dst_height = height - k_size + 1 dst_width = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows image_array = zeros((dst_height * dst_width, k_size * k_size)) row = 0 for i, j in product(range(dst_height), range(dst_width)): window = ravel(image[i : i + k_size, j : j + k_size]) image_array[row, :] = window row += 1 # turn the kernel into shape(k*k, 1) gaussian_kernel = gen_gaussian_kernel(k_size, sigma) filter_array = ravel(gaussian_kernel) # reshape and get the dst image dst = dot(image_array, filter_array).reshape(dst_height, dst_width).astype(uint8) return dst if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size gaussian3x3 = gaussian_filter(gray, 3, sigma=1) gaussian5x5 = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow("gaussian filter with 3x3 mask", gaussian3x3) imshow("gaussian filter with 5x5 mask", gaussian5x5) waitKey()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Created by sarathkaul on 12/11/19 import requests _NEWS_API = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def fetch_bbc_news(bbc_news_api_key: str) -> None: # fetching a list of articles in json format bbc_news_page = requests.get(_NEWS_API + bbc_news_api_key).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["articles"], 1): print(f"{i}.) {article['title']}") if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
# Created by sarathkaul on 12/11/19 import requests _NEWS_API = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def fetch_bbc_news(bbc_news_api_key: str) -> None: # fetching a list of articles in json format bbc_news_page = requests.get(_NEWS_API + bbc_news_api_key).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["articles"], 1): print(f"{i}.) {article['title']}") if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def bubble_sort(collection): """Pure implementation of bubble sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> bubble_sort([0, 5, 2, 3, 2]) [0, 2, 2, 3, 5] >>> bubble_sort([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2]) True >>> bubble_sort([]) == sorted([]) True >>> bubble_sort([-2, -45, -5]) == sorted([-2, -45, -5]) True >>> bubble_sort([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34]) True >>> bubble_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> bubble_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> bubble_sort(collection) == sorted(collection) True """ length = len(collection) for i in range(length - 1): swapped = False for j in range(length - 1 - i): if collection[j] > collection[j + 1]: swapped = True collection[j], collection[j + 1] = collection[j + 1], collection[j] if not swapped: break # Stop iteration if the collection is sorted. return collection if __name__ == "__main__": import doctest import time doctest.testmod() user_input = input("Enter numbers separated by a comma:").strip() unsorted = [int(item) for item in user_input.split(",")] start = time.process_time() print(*bubble_sort(unsorted), sep=",") print(f"Processing time: {time.process_time() - start}")
def bubble_sort(collection): """Pure implementation of bubble sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> bubble_sort([0, 5, 2, 3, 2]) [0, 2, 2, 3, 5] >>> bubble_sort([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2]) True >>> bubble_sort([]) == sorted([]) True >>> bubble_sort([-2, -45, -5]) == sorted([-2, -45, -5]) True >>> bubble_sort([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34]) True >>> bubble_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> bubble_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> bubble_sort(collection) == sorted(collection) True """ length = len(collection) for i in range(length - 1): swapped = False for j in range(length - 1 - i): if collection[j] > collection[j + 1]: swapped = True collection[j], collection[j + 1] = collection[j + 1], collection[j] if not swapped: break # Stop iteration if the collection is sorted. return collection if __name__ == "__main__": import doctest import time doctest.testmod() user_input = input("Enter numbers separated by a comma:").strip() unsorted = [int(item) for item in user_input.split(",")] start = time.process_time() print(*bubble_sort(unsorted), sep=",") print(f"Processing time: {time.process_time() - start}")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Minimum cut on Ford_Fulkerson algorithm. test_graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def BFS(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False] * len(graph) queue = [s] visited[s] = True while queue: u = queue.pop(0) for ind in range(len(graph[u])): if visited[ind] is False and graph[u][ind] > 0: queue.append(ind) visited[ind] = True parent[ind] = u return True if visited[t] else False def mincut(graph, source, sink): """This array is filled by BFS and to store path >>> mincut(test_graph, source=0, sink=5) [(1, 3), (4, 3), (4, 5)] """ parent = [-1] * (len(graph)) max_flow = 0 res = [] temp = [i[:] for i in graph] # Record original cut, copy. while BFS(graph, source, sink, parent): path_flow = float("Inf") s = sink while s != source: # Find the minimum value in select path path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] for i in range(len(graph)): for j in range(len(graph[0])): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j)) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
# Minimum cut on Ford_Fulkerson algorithm. test_graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def BFS(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False] * len(graph) queue = [s] visited[s] = True while queue: u = queue.pop(0) for ind in range(len(graph[u])): if visited[ind] is False and graph[u][ind] > 0: queue.append(ind) visited[ind] = True parent[ind] = u return True if visited[t] else False def mincut(graph, source, sink): """This array is filled by BFS and to store path >>> mincut(test_graph, source=0, sink=5) [(1, 3), (4, 3), (4, 5)] """ parent = [-1] * (len(graph)) max_flow = 0 res = [] temp = [i[:] for i in graph] # Record original cut, copy. while BFS(graph, source, sink, parent): path_flow = float("Inf") s = sink while s != source: # Find the minimum value in select path path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] for i in range(len(graph)): for j in range(len(graph[0])): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j)) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#
#
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import numpy as np from PIL import Image def rgb2gray(rgb: np.array) -> np.array: """ Return gray image from rgb image >>> rgb2gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb2gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb2gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb2gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray2binary(gray: np.array) -> np.array: """ Return binary image from gray image >>> gray2binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray2binary(np.array([[0]])) array([[False]]) >>> gray2binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray2binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (127 < gray) & (gray <= 255) def erosion(image: np.array, kernel: np.array) -> np.array: """ Return eroded image >>> erosion(np.array([[True, True, False]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> erosion(np.array([[True, False, False]]), np.array([[1, 1, 0]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation == 5) return output # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) if __name__ == "__main__": # read original image image = np.array(Image.open(r"..\image_data\lena.jpg")) # Apply erosion operation to a binary image output = erosion(gray2binary(rgb2gray(image)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_erosion.png")
import numpy as np from PIL import Image def rgb2gray(rgb: np.array) -> np.array: """ Return gray image from rgb image >>> rgb2gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb2gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb2gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb2gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray2binary(gray: np.array) -> np.array: """ Return binary image from gray image >>> gray2binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray2binary(np.array([[0]])) array([[False]]) >>> gray2binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray2binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (127 < gray) & (gray <= 255) def erosion(image: np.array, kernel: np.array) -> np.array: """ Return eroded image >>> erosion(np.array([[True, True, False]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> erosion(np.array([[True, False, False]]), np.array([[1, 1, 0]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation == 5) return output # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) if __name__ == "__main__": # read original image image = np.array(Image.open(r"..\image_data\lena.jpg")) # Apply erosion operation to a binary image output = erosion(gray2binary(rgb2gray(image)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_erosion.png")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" 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,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem Statement: By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. """ import os def solution() -> int: """ Finds the maximum total in a triangle as described by the problem statement above. >>> solution() 7273 """ script_dir = os.path.dirname(os.path.realpath(__file__)) triangle_path = os.path.join(script_dir, "triangle.txt") with open(triangle_path) as in_file: triangle = [[int(i) for i in line.split()] for line in in_file] while len(triangle) != 1: last_row = triangle.pop() curr_row = triangle[-1] for j in range(len(last_row) - 1): curr_row[j] += max(last_row[j], last_row[j + 1]) return triangle[0][0] if __name__ == "__main__": print(solution())
""" Problem Statement: By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. """ import os def solution() -> int: """ Finds the maximum total in a triangle as described by the problem statement above. >>> solution() 7273 """ script_dir = os.path.dirname(os.path.realpath(__file__)) triangle_path = os.path.join(script_dir, "triangle.txt") with open(triangle_path) as in_file: triangle = [[int(i) for i in line.split()] for line in in_file] while len(triangle) != 1: last_row = triangle.pop() curr_row = triangle[-1] for j in range(len(last_row) - 1): curr_row[j] += max(last_row[j], last_row[j + 1]) return triangle[0][0] if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#
#
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# @Author : lightXu # @File : sobel_filter.py # @Time : 2019/7/8 0008 下午 16:26 import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from digital_image_processing.filters.convolve import img_convolve def sobel_filter(image): kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) dst_x = np.abs(img_convolve(image, kernel_x)) dst_y = np.abs(img_convolve(image, kernel_y)) # modify the pix within [0, 255] dst_x = dst_x * 255 / np.max(dst_x) dst_y = dst_y * 255 / np.max(dst_y) dst_xy = np.sqrt((np.square(dst_x)) + (np.square(dst_y))) dst_xy = dst_xy * 255 / np.max(dst_xy) dst = dst_xy.astype(np.uint8) theta = np.arctan2(dst_y, dst_x) return dst, theta if __name__ == "__main__": # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) sobel_grad, sobel_theta = sobel_filter(gray) # show result images imshow("sobel filter", sobel_grad) imshow("sobel theta", sobel_theta) waitKey(0)
# @Author : lightXu # @File : sobel_filter.py # @Time : 2019/7/8 0008 下午 16:26 import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from digital_image_processing.filters.convolve import img_convolve def sobel_filter(image): kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) dst_x = np.abs(img_convolve(image, kernel_x)) dst_y = np.abs(img_convolve(image, kernel_y)) # modify the pix within [0, 255] dst_x = dst_x * 255 / np.max(dst_x) dst_y = dst_y * 255 / np.max(dst_y) dst_xy = np.sqrt((np.square(dst_x)) + (np.square(dst_y))) dst_xy = dst_xy * 255 / np.max(dst_xy) dst = dst_xy.astype(np.uint8) theta = np.arctan2(dst_y, dst_x) return dst, theta if __name__ == "__main__": # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) sobel_grad, sobel_theta = sobel_filter(gray) # show result images imshow("sobel filter", sobel_grad) imshow("sobel theta", sobel_theta) waitKey(0)
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def binary_count_setbits(a: int) -> int: """ Take in 1 integer, return a number that is the number of 1's in binary representation of that number. >>> binary_count_setbits(25) 3 >>> binary_count_setbits(36) 2 >>> binary_count_setbits(16) 1 >>> binary_count_setbits(58) 4 >>> binary_count_setbits(4294967295) 32 >>> binary_count_setbits(0) 0 >>> binary_count_setbits(-10) Traceback (most recent call last): ... ValueError: Input value must be a positive integer >>> binary_count_setbits(0.8) Traceback (most recent call last): ... TypeError: Input value must be a 'int' type >>> binary_count_setbits("0") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0: raise ValueError("Input value must be a positive integer") elif isinstance(a, float): raise TypeError("Input value must be a 'int' type") return bin(a).count("1") if __name__ == "__main__": import doctest doctest.testmod()
def binary_count_setbits(a: int) -> int: """ Take in 1 integer, return a number that is the number of 1's in binary representation of that number. >>> binary_count_setbits(25) 3 >>> binary_count_setbits(36) 2 >>> binary_count_setbits(16) 1 >>> binary_count_setbits(58) 4 >>> binary_count_setbits(4294967295) 32 >>> binary_count_setbits(0) 0 >>> binary_count_setbits(-10) Traceback (most recent call last): ... ValueError: Input value must be a positive integer >>> binary_count_setbits(0.8) Traceback (most recent call last): ... TypeError: Input value must be a 'int' type >>> binary_count_setbits("0") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0: raise ValueError("Input value must be a positive integer") elif isinstance(a, float): raise TypeError("Input value must be a 'int' type") return bin(a).count("1") if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65. For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message. Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable. Your task has been made easy, as the encryption key consists of three lower case characters. Using p059_cipher.txt (right click and 'Save Link/Target As...'), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text. """ from __future__ import annotations import string from itertools import cycle, product from pathlib import Path VALID_CHARS: str = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) LOWERCASE_INTS: list[int] = [ord(letter) for letter in string.ascii_lowercase] VALID_INTS: set[int] = {ord(char) for char in VALID_CHARS} COMMON_WORDS: list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"] def try_key(ciphertext: list[int], key: tuple[int, ...]) -> str | None: """ Given an encrypted message and a possible 3-character key, decrypt the message. If the decrypted message contains a invalid character, i.e. not an ASCII letter, a digit, punctuation or whitespace, then we know the key is incorrect, so return None. >>> try_key([0, 17, 20, 4, 27], (104, 116, 120)) 'hello' >>> try_key([68, 10, 300, 4, 27], (104, 116, 120)) is None True """ decoded: str = "" keychar: int cipherchar: int decodedchar: int for keychar, cipherchar in zip(cycle(key), ciphertext): decodedchar = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(decodedchar) return decoded def filter_valid_chars(ciphertext: list[int]) -> list[str]: """ Given an encrypted message, test all 3-character strings to try and find the key. Return a list of the possible decrypted messages. >>> from itertools import cycle >>> text = "The enemy's gate is down" >>> key = "end" >>> encoded = [ord(k) ^ ord(c) for k,c in zip(cycle(key), text)] >>> text in filter_valid_chars(encoded) True """ possibles: list[str] = [] for key in product(LOWERCASE_INTS, repeat=3): encoded = try_key(ciphertext, key) if encoded is not None: possibles.append(encoded) return possibles def filter_common_word(possibles: list[str], common_word: str) -> list[str]: """ Given a list of possible decoded messages, narrow down the possibilities for checking for the presence of a specified common word. Only decoded messages containing common_word will be returned. >>> filter_common_word(['asfla adf', 'I am here', ' !?! #a'], 'am') ['I am here'] >>> filter_common_word(['athla amf', 'I am here', ' !?! #a'], 'am') ['athla amf', 'I am here'] """ return [possible for possible in possibles if common_word in possible.lower()] def solution(filename: str = "p059_cipher.txt") -> int: """ Test the ciphertext against all possible 3-character keys, then narrow down the possibilities by filtering using common words until there's only one possible decoded message. >>> solution("test_cipher.txt") 3000 """ ciphertext: list[int] possibles: list[str] common_word: str decoded_text: str data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") ciphertext = [int(number) for number in data.strip().split(",")] possibles = filter_valid_chars(ciphertext) for common_word in COMMON_WORDS: possibles = filter_common_word(possibles, common_word) if len(possibles) == 1: break decoded_text = possibles[0] return sum(ord(char) for char in decoded_text) if __name__ == "__main__": print(f"{solution() = }")
""" Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65. For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message. Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable. Your task has been made easy, as the encryption key consists of three lower case characters. Using p059_cipher.txt (right click and 'Save Link/Target As...'), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text. """ from __future__ import annotations import string from itertools import cycle, product from pathlib import Path VALID_CHARS: str = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) LOWERCASE_INTS: list[int] = [ord(letter) for letter in string.ascii_lowercase] VALID_INTS: set[int] = {ord(char) for char in VALID_CHARS} COMMON_WORDS: list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"] def try_key(ciphertext: list[int], key: tuple[int, ...]) -> str | None: """ Given an encrypted message and a possible 3-character key, decrypt the message. If the decrypted message contains a invalid character, i.e. not an ASCII letter, a digit, punctuation or whitespace, then we know the key is incorrect, so return None. >>> try_key([0, 17, 20, 4, 27], (104, 116, 120)) 'hello' >>> try_key([68, 10, 300, 4, 27], (104, 116, 120)) is None True """ decoded: str = "" keychar: int cipherchar: int decodedchar: int for keychar, cipherchar in zip(cycle(key), ciphertext): decodedchar = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(decodedchar) return decoded def filter_valid_chars(ciphertext: list[int]) -> list[str]: """ Given an encrypted message, test all 3-character strings to try and find the key. Return a list of the possible decrypted messages. >>> from itertools import cycle >>> text = "The enemy's gate is down" >>> key = "end" >>> encoded = [ord(k) ^ ord(c) for k,c in zip(cycle(key), text)] >>> text in filter_valid_chars(encoded) True """ possibles: list[str] = [] for key in product(LOWERCASE_INTS, repeat=3): encoded = try_key(ciphertext, key) if encoded is not None: possibles.append(encoded) return possibles def filter_common_word(possibles: list[str], common_word: str) -> list[str]: """ Given a list of possible decoded messages, narrow down the possibilities for checking for the presence of a specified common word. Only decoded messages containing common_word will be returned. >>> filter_common_word(['asfla adf', 'I am here', ' !?! #a'], 'am') ['I am here'] >>> filter_common_word(['athla amf', 'I am here', ' !?! #a'], 'am') ['athla amf', 'I am here'] """ return [possible for possible in possibles if common_word in possible.lower()] def solution(filename: str = "p059_cipher.txt") -> int: """ Test the ciphertext against all possible 3-character keys, then narrow down the possibilities by filtering using common words until there's only one possible decoded message. >>> solution("test_cipher.txt") 3000 """ ciphertext: list[int] possibles: list[str] common_word: str decoded_text: str data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") ciphertext = [int(number) for number in data.strip().split(",")] possibles = filter_valid_chars(ciphertext) for common_word in COMMON_WORDS: possibles = filter_common_word(possibles, common_word) if len(possibles) == 1: break decoded_text = possibles[0] return sum(ord(char) for char in decoded_text) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" 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 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 """ fact = 1 result = 0 for i in range(1, num + 1): fact *= i for j in str(fact): result += int(j) 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 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 """ fact = 1 result = 0 for i in range(1, num + 1): fact *= i for j in str(fact): result += int(j) return result if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 """ Python program to translate to and from Morse code. https://en.wikipedia.org/wiki/Morse_code """ # fmt: off MORSE_CODE_DICT = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "0": "-----", "&": ".-...", "@": ".--.-.", ":": "---...", ",": "--..--", ".": ".-.-.-", "'": ".----.", '"': ".-..-.", "?": "..--..", "/": "-..-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "(": "-.--.", ")": "-.--.-", "!": "-.-.--", " ": "/" } # Exclamation mark is not in ITU-R recommendation # fmt: on REVERSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()} def encrypt(message: str) -> str: """ >>> encrypt("Sos!") '... --- ... -.-.--' >>> encrypt("SOS!") == encrypt("sos!") True """ return " ".join(MORSE_CODE_DICT[char] for char in message.upper()) def decrypt(message: str) -> str: """ >>> decrypt('... --- ... -.-.--') 'SOS!' """ return "".join(REVERSE_DICT[char] for char in message.split()) def main() -> None: """ >>> s = "".join(MORSE_CODE_DICT) >>> decrypt(encrypt(s)) == s True """ message = "Morse code here!" print(message) message = encrypt(message) print(message) message = decrypt(message) print(message) if __name__ == "__main__": main()
#!/usr/bin/env python3 """ Python program to translate to and from Morse code. https://en.wikipedia.org/wiki/Morse_code """ # fmt: off MORSE_CODE_DICT = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "0": "-----", "&": ".-...", "@": ".--.-.", ":": "---...", ",": "--..--", ".": ".-.-.-", "'": ".----.", '"': ".-..-.", "?": "..--..", "/": "-..-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "(": "-.--.", ")": "-.--.-", "!": "-.-.--", " ": "/" } # Exclamation mark is not in ITU-R recommendation # fmt: on REVERSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()} def encrypt(message: str) -> str: """ >>> encrypt("Sos!") '... --- ... -.-.--' >>> encrypt("SOS!") == encrypt("sos!") True """ return " ".join(MORSE_CODE_DICT[char] for char in message.upper()) def decrypt(message: str) -> str: """ >>> decrypt('... --- ... -.-.--') 'SOS!' """ return "".join(REVERSE_DICT[char] for char in message.split()) def main() -> None: """ >>> s = "".join(MORSE_CODE_DICT) >>> decrypt(encrypt(s)) == s True """ message = "Morse code here!" print(message) message = encrypt(message) print(message) message = decrypt(message) print(message) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The 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,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1