repo_name
stringclasses
1 value
pr_number
int64
4.12k
11.2k
pr_title
stringlengths
9
107
pr_description
stringlengths
107
5.48k
author
stringlengths
4
18
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
118
5.52k
before_content
stringlengths
0
7.93M
after_content
stringlengths
0
7.93M
label
int64
-1
1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a pure Python implementation of the heap sort algorithm. For doctests run following command: python -m doctest -v heap_sort.py or python3 -m doctest -v heap_sort.py For manual testing run: python heap_sort.py """ def heapify(unsorted, index, heap_size): largest = index left_index = 2 * index + 1 right_index = 2 * index + 2 if left_index < heap_size and unsorted[left_index] > unsorted[largest]: largest = left_index if right_index < heap_size and unsorted[right_index] > unsorted[largest]: largest = right_index if largest != index: unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest] heapify(unsorted, largest, heap_size) def heap_sort(unsorted): """ Pure implementation of the heap sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> heap_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> heap_sort([]) [] >>> heap_sort([-2, -5, -45]) [-45, -5, -2] """ n = len(unsorted) for i in range(n // 2 - 1, -1, -1): heapify(unsorted, i, n) for i in range(n - 1, 0, -1): unsorted[0], unsorted[i] = unsorted[i], unsorted[0] heapify(unsorted, 0, i) return unsorted if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(heap_sort(unsorted))
""" This is a pure Python implementation of the heap sort algorithm. For doctests run following command: python -m doctest -v heap_sort.py or python3 -m doctest -v heap_sort.py For manual testing run: python heap_sort.py """ def heapify(unsorted, index, heap_size): largest = index left_index = 2 * index + 1 right_index = 2 * index + 2 if left_index < heap_size and unsorted[left_index] > unsorted[largest]: largest = left_index if right_index < heap_size and unsorted[right_index] > unsorted[largest]: largest = right_index if largest != index: unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest] heapify(unsorted, largest, heap_size) def heap_sort(unsorted): """ Pure implementation of the heap sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> heap_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> heap_sort([]) [] >>> heap_sort([-2, -5, -45]) [-45, -5, -2] """ n = len(unsorted) for i in range(n // 2 - 1, -1, -1): heapify(unsorted, i, n) for i in range(n - 1, 0, -1): unsorted[0], unsorted[i] = unsorted[i], unsorted[0] heapify(unsorted, 0, i) return unsorted if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(heap_sort(unsorted))
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
if __name__ == "__main__": import socket # Import socket module sock = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12312 sock.connect((host, port)) sock.send(b"Hello server!") with open("Received_file", "wb") as out_file: print("File opened") print("Receiving data...") while True: data = sock.recv(1024) print(f"{data = }") if not data: break out_file.write(data) # Write data to a file print("Successfully got the file") sock.close() print("Connection closed")
if __name__ == "__main__": import socket # Import socket module sock = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12312 sock.connect((host, port)) sock.send(b"Hello server!") with open("Received_file", "wb") as out_file: print("File opened") print("Receiving data...") while True: data = sock.recv(1024) print(f"{data = }") if not data: break out_file.write(data) # Write data to a file print("Successfully got the file") sock.close() print("Connection closed")
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is pure Python implementation of fibonacci search. Resources used: https://en.wikipedia.org/wiki/Fibonacci_search_technique For doctests run following command: python3 -m doctest -v fibonacci_search.py For manual testing run: python3 fibonacci_search.py """ from functools import lru_cache @lru_cache def fibonacci(k: int) -> int: """Finds fibonacci number in index k. Parameters ---------- k : Index of fibonacci. Returns ------- int Fibonacci number in position k. >>> fibonacci(0) 0 >>> fibonacci(2) 1 >>> fibonacci(5) 5 >>> fibonacci(15) 610 >>> fibonacci('a') Traceback (most recent call last): TypeError: k must be an integer. >>> fibonacci(-5) Traceback (most recent call last): ValueError: k integer must be greater or equal to zero. """ if not isinstance(k, int): raise TypeError("k must be an integer.") if k < 0: raise ValueError("k integer must be greater or equal to zero.") if k == 0: return 0 elif k == 1: return 1 else: return fibonacci(k - 1) + fibonacci(k - 2) def fibonacci_search(arr: list, val: int) -> int: """A pure Python implementation of a fibonacci search algorithm. Parameters ---------- arr List of sorted elements. val Element to search in list. Returns ------- int The index of the element in the array. -1 if the element is not found. >>> fibonacci_search([4, 5, 6, 7], 4) 0 >>> fibonacci_search([4, 5, 6, 7], -10) -1 >>> fibonacci_search([-18, 2], -18) 0 >>> fibonacci_search([5], 5) 0 >>> fibonacci_search(['a', 'c', 'd'], 'c') 1 >>> fibonacci_search(['a', 'c', 'd'], 'f') -1 >>> fibonacci_search([], 1) -1 >>> fibonacci_search([.1, .4 , 7], .4) 1 >>> fibonacci_search([], 9) -1 >>> fibonacci_search(list(range(100)), 63) 63 >>> fibonacci_search(list(range(100)), 99) 99 >>> fibonacci_search(list(range(-100, 100, 3)), -97) 1 >>> fibonacci_search(list(range(-100, 100, 3)), 0) -1 >>> fibonacci_search(list(range(-100, 100, 5)), 0) 20 >>> fibonacci_search(list(range(-100, 100, 5)), 95) 39 """ len_list = len(arr) # Find m such that F_m >= n where F_i is the i_th fibonacci number. i = 0 while True: if fibonacci(i) >= len_list: fibb_k = i break i += 1 offset = 0 while fibb_k > 0: index_k = min( offset + fibonacci(fibb_k - 1), len_list - 1 ) # Prevent out of range item_k_1 = arr[index_k] if item_k_1 == val: return index_k elif val < item_k_1: fibb_k -= 1 elif val > item_k_1: offset += fibonacci(fibb_k - 1) fibb_k -= 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
""" This is pure Python implementation of fibonacci search. Resources used: https://en.wikipedia.org/wiki/Fibonacci_search_technique For doctests run following command: python3 -m doctest -v fibonacci_search.py For manual testing run: python3 fibonacci_search.py """ from functools import lru_cache @lru_cache def fibonacci(k: int) -> int: """Finds fibonacci number in index k. Parameters ---------- k : Index of fibonacci. Returns ------- int Fibonacci number in position k. >>> fibonacci(0) 0 >>> fibonacci(2) 1 >>> fibonacci(5) 5 >>> fibonacci(15) 610 >>> fibonacci('a') Traceback (most recent call last): TypeError: k must be an integer. >>> fibonacci(-5) Traceback (most recent call last): ValueError: k integer must be greater or equal to zero. """ if not isinstance(k, int): raise TypeError("k must be an integer.") if k < 0: raise ValueError("k integer must be greater or equal to zero.") if k == 0: return 0 elif k == 1: return 1 else: return fibonacci(k - 1) + fibonacci(k - 2) def fibonacci_search(arr: list, val: int) -> int: """A pure Python implementation of a fibonacci search algorithm. Parameters ---------- arr List of sorted elements. val Element to search in list. Returns ------- int The index of the element in the array. -1 if the element is not found. >>> fibonacci_search([4, 5, 6, 7], 4) 0 >>> fibonacci_search([4, 5, 6, 7], -10) -1 >>> fibonacci_search([-18, 2], -18) 0 >>> fibonacci_search([5], 5) 0 >>> fibonacci_search(['a', 'c', 'd'], 'c') 1 >>> fibonacci_search(['a', 'c', 'd'], 'f') -1 >>> fibonacci_search([], 1) -1 >>> fibonacci_search([.1, .4 , 7], .4) 1 >>> fibonacci_search([], 9) -1 >>> fibonacci_search(list(range(100)), 63) 63 >>> fibonacci_search(list(range(100)), 99) 99 >>> fibonacci_search(list(range(-100, 100, 3)), -97) 1 >>> fibonacci_search(list(range(-100, 100, 3)), 0) -1 >>> fibonacci_search(list(range(-100, 100, 5)), 0) 20 >>> fibonacci_search(list(range(-100, 100, 5)), 95) 39 """ len_list = len(arr) # Find m such that F_m >= n where F_i is the i_th fibonacci number. i = 0 while True: if fibonacci(i) >= len_list: fibb_k = i break i += 1 offset = 0 while fibb_k > 0: index_k = min( offset + fibonacci(fibb_k - 1), len_list - 1 ) # Prevent out of range item_k_1 = arr[index_k] if item_k_1 == val: return index_k elif val < item_k_1: fibb_k -= 1 elif val > item_k_1: offset += fibonacci(fibb_k - 1) fibb_k -= 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Rayleigh_quotient """ from typing import Any import numpy as np def is_hermitian(matrix: np.ndarray) -> bool: """ Checks if a matrix is Hermitian. >>> import numpy as np >>> A = np.array([ ... [2, 2+1j, 4], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) True >>> A = np.array([ ... [2, 2+1j, 4+1j], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) False """ return np.array_equal(matrix, matrix.conjugate().T) def rayleigh_quotient(a: np.ndarray, v: np.ndarray) -> Any: """ Returns the Rayleigh quotient of a Hermitian matrix A and vector v. >>> import numpy as np >>> A = np.array([ ... [1, 2, 4], ... [2, 3, -1], ... [4, -1, 1] ... ]) >>> v = np.array([ ... [1], ... [2], ... [3] ... ]) >>> rayleigh_quotient(A, v) array([[3.]]) """ v_star = v.conjugate().T v_star_dot = v_star.dot(a) assert isinstance(v_star_dot, np.ndarray) return (v_star_dot.dot(v)) / (v_star.dot(v)) def tests() -> None: a = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]]) v = np.array([[1], [2], [3]]) assert is_hermitian(a), f"{a} is not hermitian." print(rayleigh_quotient(a, v)) a = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]]) assert is_hermitian(a), f"{a} is not hermitian." assert rayleigh_quotient(a, v) == float(3) if __name__ == "__main__": import doctest doctest.testmod() tests()
""" https://en.wikipedia.org/wiki/Rayleigh_quotient """ from typing import Any import numpy as np def is_hermitian(matrix: np.ndarray) -> bool: """ Checks if a matrix is Hermitian. >>> import numpy as np >>> A = np.array([ ... [2, 2+1j, 4], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) True >>> A = np.array([ ... [2, 2+1j, 4+1j], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) False """ return np.array_equal(matrix, matrix.conjugate().T) def rayleigh_quotient(a: np.ndarray, v: np.ndarray) -> Any: """ Returns the Rayleigh quotient of a Hermitian matrix A and vector v. >>> import numpy as np >>> A = np.array([ ... [1, 2, 4], ... [2, 3, -1], ... [4, -1, 1] ... ]) >>> v = np.array([ ... [1], ... [2], ... [3] ... ]) >>> rayleigh_quotient(A, v) array([[3.]]) """ v_star = v.conjugate().T v_star_dot = v_star.dot(a) assert isinstance(v_star_dot, np.ndarray) return (v_star_dot.dot(v)) / (v_star.dot(v)) def tests() -> None: a = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]]) v = np.array([[1], [2], [3]]) assert is_hermitian(a), f"{a} is not hermitian." print(rayleigh_quotient(a, v)) a = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]]) assert is_hermitian(a), f"{a} is not hermitian." assert rayleigh_quotient(a, v) == float(3) if __name__ == "__main__": import doctest doctest.testmod() tests()
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from collections.abc import Sequence def compare_string(string1: str, string2: str) -> str: """ >>> compare_string('0010','0110') '0_10' >>> compare_string('0110','1101') 'X' """ list1 = list(string1) list2 = list(string2) count = 0 for i in range(len(list1)): if list1[i] != list2[i]: count += 1 list1[i] = "_" if count > 1: return "X" else: return "".join(list1) def check(binary: list[str]) -> list[str]: """ >>> check(['0.00.01.5']) ['0.00.01.5'] """ pi = [] while True: check1 = ["$"] * len(binary) temp = [] for i in range(len(binary)): for j in range(i + 1, len(binary)): k = compare_string(binary[i], binary[j]) if k != "X": check1[i] = "*" check1[j] = "*" temp.append(k) for i in range(len(binary)): if check1[i] == "$": pi.append(binary[i]) if len(temp) == 0: return pi binary = list(set(temp)) def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]: """ >>> decimal_to_binary(3,[1.5]) ['0.00.01.5'] """ temp = [] for minterm in minterms: string = "" for _ in range(no_of_variable): string = str(minterm % 2) + string minterm //= 2 temp.append(string) return temp def is_for_table(string1: str, string2: str, count: int) -> bool: """ >>> is_for_table('__1','011',2) True >>> is_for_table('01_','001',1) False """ list1 = list(string1) list2 = list(string2) count_n = 0 for i in range(len(list1)): if list1[i] != list2[i]: count_n += 1 return count_n == count def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]: """ >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] """ temp = [] select = [0] * len(chart) for i in range(len(chart[0])): count = 0 rem = -1 for j in range(len(chart)): if chart[j][i] == 1: count += 1 rem = j if count == 1: select[rem] = 1 for i in range(len(select)): if select[i] == 1: for j in range(len(chart[0])): if chart[i][j] == 1: for k in range(len(chart)): chart[k][j] = 0 temp.append(prime_implicants[i]) while True: max_n = 0 rem = -1 count_n = 0 for i in range(len(chart)): count_n = chart[i].count(1) if count_n > max_n: max_n = count_n rem = i if max_n == 0: return temp temp.append(prime_implicants[rem]) for i in range(len(chart[0])): if chart[rem][i] == 1: for j in range(len(chart)): chart[j][i] = 0 def prime_implicant_chart( prime_implicants: list[str], binary: list[str] ) -> list[list[int]]: """ >>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5']) [[1]] """ chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))] for i in range(len(prime_implicants)): count = prime_implicants[i].count("_") for j in range(len(binary)): if is_for_table(prime_implicants[i], binary[j], count): chart[i][j] = 1 return chart def main() -> None: no_of_variable = int(input("Enter the no. of variables\n")) minterms = [ float(x) for x in input( "Enter the decimal representation of Minterms 'Spaces Separated'\n" ).split() ] binary = decimal_to_binary(no_of_variable, minterms) prime_implicants = check(binary) print("Prime Implicants are:") print(prime_implicants) chart = prime_implicant_chart(prime_implicants, binary) essential_prime_implicants = selection(chart, prime_implicants) print("Essential Prime Implicants are:") print(essential_prime_implicants) if __name__ == "__main__": import doctest doctest.testmod() main()
from __future__ import annotations from collections.abc import Sequence def compare_string(string1: str, string2: str) -> str: """ >>> compare_string('0010','0110') '0_10' >>> compare_string('0110','1101') 'X' """ list1 = list(string1) list2 = list(string2) count = 0 for i in range(len(list1)): if list1[i] != list2[i]: count += 1 list1[i] = "_" if count > 1: return "X" else: return "".join(list1) def check(binary: list[str]) -> list[str]: """ >>> check(['0.00.01.5']) ['0.00.01.5'] """ pi = [] while True: check1 = ["$"] * len(binary) temp = [] for i in range(len(binary)): for j in range(i + 1, len(binary)): k = compare_string(binary[i], binary[j]) if k != "X": check1[i] = "*" check1[j] = "*" temp.append(k) for i in range(len(binary)): if check1[i] == "$": pi.append(binary[i]) if len(temp) == 0: return pi binary = list(set(temp)) def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]: """ >>> decimal_to_binary(3,[1.5]) ['0.00.01.5'] """ temp = [] for minterm in minterms: string = "" for _ in range(no_of_variable): string = str(minterm % 2) + string minterm //= 2 temp.append(string) return temp def is_for_table(string1: str, string2: str, count: int) -> bool: """ >>> is_for_table('__1','011',2) True >>> is_for_table('01_','001',1) False """ list1 = list(string1) list2 = list(string2) count_n = 0 for i in range(len(list1)): if list1[i] != list2[i]: count_n += 1 return count_n == count def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]: """ >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] """ temp = [] select = [0] * len(chart) for i in range(len(chart[0])): count = 0 rem = -1 for j in range(len(chart)): if chart[j][i] == 1: count += 1 rem = j if count == 1: select[rem] = 1 for i in range(len(select)): if select[i] == 1: for j in range(len(chart[0])): if chart[i][j] == 1: for k in range(len(chart)): chart[k][j] = 0 temp.append(prime_implicants[i]) while True: max_n = 0 rem = -1 count_n = 0 for i in range(len(chart)): count_n = chart[i].count(1) if count_n > max_n: max_n = count_n rem = i if max_n == 0: return temp temp.append(prime_implicants[rem]) for i in range(len(chart[0])): if chart[rem][i] == 1: for j in range(len(chart)): chart[j][i] = 0 def prime_implicant_chart( prime_implicants: list[str], binary: list[str] ) -> list[list[int]]: """ >>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5']) [[1]] """ chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))] for i in range(len(prime_implicants)): count = prime_implicants[i].count("_") for j in range(len(binary)): if is_for_table(prime_implicants[i], binary[j], count): chart[i][j] = 1 return chart def main() -> None: no_of_variable = int(input("Enter the no. of variables\n")) minterms = [ float(x) for x in input( "Enter the decimal representation of Minterms 'Spaces Separated'\n" ).split() ] binary = decimal_to_binary(no_of_variable, minterms) prime_implicants = check(binary) print("Prime Implicants are:") print(prime_implicants) chart = prime_implicant_chart(prime_implicants, binary) essential_prime_implicants = selection(chart, prime_implicants) print("Essential Prime Implicants are:") print(essential_prime_implicants) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
alphabet = { "A": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"), "B": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"), "C": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"), "D": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"), "E": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"), "F": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"), "G": ("ABCDEFGHIJKLM", "XYZNOPQRSTUVW"), "H": ("ABCDEFGHIJKLM", "XYZNOPQRSTUVW"), "I": ("ABCDEFGHIJKLM", "WXYZNOPQRSTUV"), "J": ("ABCDEFGHIJKLM", "WXYZNOPQRSTUV"), "K": ("ABCDEFGHIJKLM", "VWXYZNOPQRSTU"), "L": ("ABCDEFGHIJKLM", "VWXYZNOPQRSTU"), "M": ("ABCDEFGHIJKLM", "UVWXYZNOPQRST"), "N": ("ABCDEFGHIJKLM", "UVWXYZNOPQRST"), "O": ("ABCDEFGHIJKLM", "TUVWXYZNOPQRS"), "P": ("ABCDEFGHIJKLM", "TUVWXYZNOPQRS"), "Q": ("ABCDEFGHIJKLM", "STUVWXYZNOPQR"), "R": ("ABCDEFGHIJKLM", "STUVWXYZNOPQR"), "S": ("ABCDEFGHIJKLM", "RSTUVWXYZNOPQ"), "T": ("ABCDEFGHIJKLM", "RSTUVWXYZNOPQ"), "U": ("ABCDEFGHIJKLM", "QRSTUVWXYZNOP"), "V": ("ABCDEFGHIJKLM", "QRSTUVWXYZNOP"), "W": ("ABCDEFGHIJKLM", "PQRSTUVWXYZNO"), "X": ("ABCDEFGHIJKLM", "PQRSTUVWXYZNO"), "Y": ("ABCDEFGHIJKLM", "OPQRSTUVWXYZN"), "Z": ("ABCDEFGHIJKLM", "OPQRSTUVWXYZN"), } def generate_table(key: str) -> list[tuple[str, str]]: """ >>> generate_table('marvin') # doctest: +NORMALIZE_WHITESPACE [('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'), ('ABCDEFGHIJKLM', 'STUVWXYZNOPQR'), ('ABCDEFGHIJKLM', 'QRSTUVWXYZNOP'), ('ABCDEFGHIJKLM', 'WXYZNOPQRSTUV'), ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST')] """ return [alphabet[char] for char in key.upper()] def encrypt(key: str, words: str) -> str: """ >>> encrypt('marvin', 'jessica') 'QRACRWU' """ cipher = "" count = 0 table = generate_table(key) for char in words.upper(): cipher += get_opponent(table[count], char) count = (count + 1) % len(table) return cipher def decrypt(key: str, words: str) -> str: """ >>> decrypt('marvin', 'QRACRWU') 'JESSICA' """ return encrypt(key, words) def get_position(table: tuple[str, str], char: str) -> tuple[int, int]: """ >>> get_position(generate_table('marvin')[0], 'M') (0, 12) """ # `char` is either in the 0th row or the 1st row row = 0 if char in table[0] else 1 col = table[row].index(char) return row, col def get_opponent(table: tuple[str, str], char: str) -> str: """ >>> get_opponent(generate_table('marvin')[0], 'M') 'T' """ row, col = get_position(table, char.upper()) if row == 1: return table[0][col] else: return table[1][col] if row == 0 else char if __name__ == "__main__": import doctest doctest.testmod() # Fist ensure that all our tests are passing... """ Demo: Enter key: marvin Enter text to encrypt: jessica Encrypted: QRACRWU Decrypted with key: JESSICA """ key = input("Enter key: ").strip() text = input("Enter text to encrypt: ").strip() cipher_text = encrypt(key, text) print(f"Encrypted: {cipher_text}") print(f"Decrypted with key: {decrypt(key, cipher_text)}")
alphabet = { "A": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"), "B": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"), "C": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"), "D": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"), "E": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"), "F": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"), "G": ("ABCDEFGHIJKLM", "XYZNOPQRSTUVW"), "H": ("ABCDEFGHIJKLM", "XYZNOPQRSTUVW"), "I": ("ABCDEFGHIJKLM", "WXYZNOPQRSTUV"), "J": ("ABCDEFGHIJKLM", "WXYZNOPQRSTUV"), "K": ("ABCDEFGHIJKLM", "VWXYZNOPQRSTU"), "L": ("ABCDEFGHIJKLM", "VWXYZNOPQRSTU"), "M": ("ABCDEFGHIJKLM", "UVWXYZNOPQRST"), "N": ("ABCDEFGHIJKLM", "UVWXYZNOPQRST"), "O": ("ABCDEFGHIJKLM", "TUVWXYZNOPQRS"), "P": ("ABCDEFGHIJKLM", "TUVWXYZNOPQRS"), "Q": ("ABCDEFGHIJKLM", "STUVWXYZNOPQR"), "R": ("ABCDEFGHIJKLM", "STUVWXYZNOPQR"), "S": ("ABCDEFGHIJKLM", "RSTUVWXYZNOPQ"), "T": ("ABCDEFGHIJKLM", "RSTUVWXYZNOPQ"), "U": ("ABCDEFGHIJKLM", "QRSTUVWXYZNOP"), "V": ("ABCDEFGHIJKLM", "QRSTUVWXYZNOP"), "W": ("ABCDEFGHIJKLM", "PQRSTUVWXYZNO"), "X": ("ABCDEFGHIJKLM", "PQRSTUVWXYZNO"), "Y": ("ABCDEFGHIJKLM", "OPQRSTUVWXYZN"), "Z": ("ABCDEFGHIJKLM", "OPQRSTUVWXYZN"), } def generate_table(key: str) -> list[tuple[str, str]]: """ >>> generate_table('marvin') # doctest: +NORMALIZE_WHITESPACE [('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'), ('ABCDEFGHIJKLM', 'STUVWXYZNOPQR'), ('ABCDEFGHIJKLM', 'QRSTUVWXYZNOP'), ('ABCDEFGHIJKLM', 'WXYZNOPQRSTUV'), ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST')] """ return [alphabet[char] for char in key.upper()] def encrypt(key: str, words: str) -> str: """ >>> encrypt('marvin', 'jessica') 'QRACRWU' """ cipher = "" count = 0 table = generate_table(key) for char in words.upper(): cipher += get_opponent(table[count], char) count = (count + 1) % len(table) return cipher def decrypt(key: str, words: str) -> str: """ >>> decrypt('marvin', 'QRACRWU') 'JESSICA' """ return encrypt(key, words) def get_position(table: tuple[str, str], char: str) -> tuple[int, int]: """ >>> get_position(generate_table('marvin')[0], 'M') (0, 12) """ # `char` is either in the 0th row or the 1st row row = 0 if char in table[0] else 1 col = table[row].index(char) return row, col def get_opponent(table: tuple[str, str], char: str) -> str: """ >>> get_opponent(generate_table('marvin')[0], 'M') 'T' """ row, col = get_position(table, char.upper()) if row == 1: return table[0][col] else: return table[1][col] if row == 0 else char if __name__ == "__main__": import doctest doctest.testmod() # Fist ensure that all our tests are passing... """ Demo: Enter key: marvin Enter text to encrypt: jessica Encrypted: QRACRWU Decrypted with key: JESSICA """ key = input("Enter key: ").strip() text = input("Enter text to encrypt: ").strip() cipher_text = encrypt(key, text) print(f"Encrypted: {cipher_text}") print(f"Decrypted with key: {decrypt(key, cipher_text)}")
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ import sys N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def str_eval(s: str) -> int: """ Returns product of digits in given string n >>> str_eval("987654321") 362880 >>> str_eval("22222222") 256 """ product = 1 for digit in s: product *= int(digit) return product def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. """ largest_product = -sys.maxsize - 1 substr = n[:13] cur_index = 13 while cur_index < len(n) - 13: if int(n[cur_index]) >= int(substr[0]): substr = substr[1:] + n[cur_index] cur_index += 1 else: largest_product = max(largest_product, str_eval(substr)) substr = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ import sys N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def str_eval(s: str) -> int: """ Returns product of digits in given string n >>> str_eval("987654321") 362880 >>> str_eval("22222222") 256 """ product = 1 for digit in s: product *= int(digit) return product def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. """ largest_product = -sys.maxsize - 1 substr = n[:13] cur_index = 13 while cur_index < len(n) - 13: if int(n[cur_index]) >= int(substr[0]): substr = substr[1:] + n[cur_index] cur_index += 1 else: largest_product = max(largest_product, str_eval(substr)) substr = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
JFIFHHC     C  dd" }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz w!1AQaq"2B #3Rbr $4%&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz ? >{b?>|pjRò<w,Tν;YgwN7O-j2vFZ>3PG4a_Jit?IE]N7S@^9+-.b$ו*mwW=+Э(b`"sv' qJ^S"sp  F<PkV*XeA8RxwTүDf~=u3\z;q\l3<#/gVb0HvwƛnfY"`AAWįؾ]:&9x.}Z&꽾Q|8:߃c] ujRAT<֔TԖg9fqMRz5kA:C -J?\)H/um"o.[YX[1^}Que Pұ<k^]}ko*+" ]g%:~)Iǡ~_~,|=kkxO|ANԔX'!|To/0;l-! y1Fy=_ i/ǃMq@ *U1 rUQ,g`Qԕ<M~=]|XX2ncvolc8W,ޝ[8=S>nx7>X> C'yCkƣPռ;h:N$¹XdkGƟr~ W9[ @蒀$R@gr(ѽUGܴxή"rzm~Ρ~뺥My{\J1 C "E !1''OXXNElm lNq 4?CM0kwHh^*W普!eyc᥉e +Gc~ٍwoT-ęlҽ/5%#h `jԋŨoe&-Nw0b0vg kiVsC"e/-Fp;wkuIuy[ʹ[s%|| +i-(Y%0=k{|{YRtỻ[[d(SVǫ޼ګDx\ȥBjѮ\Y͐I#l9Xkcv1%w~#N?죳m<I#*=붍UterZAI~}O|+tEK2I Ўx<VƯ#Mچ0kodr2857x5ֿ_lb[\!ʇHM,Ha^??mυtK9[m;NHL o9'$\hzUcI8k{)`az|ɦm-4jh~,J-x]y<Oak\ |A=Y!yZB "+vuۍZ&Dq v9 =V$xHomMmeŬnBzcO[hMNΧrdaʏQp=_iZ')+Ie7t+b3G7fOEzxGjpǵ-e*obrKI&qrXی_Ts7)=YڹggkX~}}ko BJxT33>?iX]oK,qI4t&}Yx@񌰴垡<Itt;/J~TҖ\HZ]gp8+]˃5f ;#Ƿ⽓/? 5+ik,`e2 䏳|/Nwu.*]}F&hVN??2 kxoOmKTԖܐlc=yo'ŎmFYܗyYhc*c7 ώ}(Ҝn$/$K|i'q_7BK=J}H\*%i_=$-)bI KrL._#W/>+35Nõ_O>{{_gJy}{`$1ēf_<+ki!U8u G" `Nvo~^gI}}an. M:G 8 ^Ius6lcsҾc<<aoMoGեBRmkסw]6 ʓOʶPʡ@ _ ۿOڤ<a|Gt@%dObK2M[ m(5(uҼypҎ#Y8BO_A_^']fkSV:#]\4HXrX䞽}k,i:mv+zx| KW|{4wd|o?/ae$\#9C_7"%AW? \(-["Wב( Wتyi ^8IR^>y72j::}۞%ࢴ)MpKUkK|e]xQ^G$8|2k2/3)YA^)ҧ> E2ɂ_4Ǻ?ሥGyW _>$CHwI1Ԋm QF/WHuUZZY9|Zѥ6diR& l(3ΤB~EFIx>!oY E$ڋiJ|fFDnN61gijWEVlQ|)v|dW|Oo?ͮqGt+K׏(TF;Kf<XU`QUNSizwwclKho_Ħ:?u FKk"΀-2@#U9S~ o ~Ğ3P;W2?7XcR?305s^?/EwK͹w(}<A<F?xpَrEӑaE|U$gr2Ƽ$aM9_}9&W~68i=,kw[/4u6j -?k"r>ge .RpIPyHFCXc99,iu/&gom Ji&HF&rNT\3@'#oNd,VoTǥb~?Ӿ!hV: N,ʟ&F=g"Q\> q˫.]JI4X5ߊOoY>ەtM<13[gL<QfK&bTo@)Z?o_h6_Af%S"'«}cB[_28-&<{s=G޾ߪ劳m%%|cFq%t:dqU "/O뚂ZLӬs"BEݝ,rc{װɿ /Sy1+ȷF~18x*>Z]81Tip~uƣgH$YGlڊ|)ar2Lhx9WWiߩ? E hў3bHvmcbs&u@+?sÞ4JX|<ݯfQ1n_NL巴^[뫘ѭj`LglUrrs \WBZgT1C}yK|fѴF/o4ѓq:IsKwfC+O|ii_.->]RM P1ݕU?3|i?5F.2$&Ke3Ee5whz]ZZ6+cXY$,FQ~^erMIi_\CZ;7<Wg?ic: zFϳ;R5e"V|+H*##|qhcϜd$p?)|\6mHՂh:pA5XX3=/a<[;fyljeҠϳqTɯ)okF։eowm6DI4| `9}+GƿEŸ{Ö։njW7`Vw,T q_j=YTHwuߴSsuw6iJԭEzB:yc$a|bJ-a\OUz[5ω<a׺n6@E_'L/_@|>իxkM7LC'^"3g㯂4-X}ĥZ+HYP2>x~%m C|7jqmrYL@(ƛ\>&pջ{+ 噶kgtvb:z.x?K3.<AyaEEB0#teL,Q'2OE ΨK$&ݒf V1uMo+fmwO16z;hvGsAEt"Ay]<5j7>"|3(8Ԯ|Uqc߿.mdvYN[/zT$c%A1In!~xr?mGWDu8.n4),rS Lں,0|Vw^by.1ǤkN2L/.s=̵%M2#.^KZʷX>cR;u<W̦'|Ra ĐAo0 aշ_>h_e1I% ̝ht_XxRnͻaY*Q&  8Xy,|2<Ԛ/~]ji\hAͧιFm!) 峚'wg8VIotG+{⼯^ +V{9/@m%"!<cX f''}{?öa @ov q41? ĘC/ww_7eo~{E=l^{K28M{_:F| sxkOݧ̃ >xK+㐕e`1vgE-OI~_ \4LD}Ÿ=J иQ_?x'NaDU? u7ľ:nO!r)*~9x/~-~E6][&ۂ K#ʆc_GUqztb쓺OV[Abg}m|-x^%px~խ킏\$/;o qV4Ix:K{41-8IgOv/_߳uYHյ#Q𕬅PILQ^['PÜ->8Oy|Wxu'_!NrI+`xv7ve}VAJWZ*J+k)1c!OG:Q^OG^+wu%K[e39+ȴ3*ڑj_5Ɵ",bs/-ͤ|=Ӊӛ#'Ex;{I<P>Cvd7X!P=7FƳx[^!YaI(-iX1k$ `Z Sƨv:? ޥ}>.YBn rr:N VBBҊ+(mU6g\9G'#eb$b wX"+Žn6w)q +?q=:as+CJøz|'(+YG|p2M]mҭEQq c'pi|>WĻuߪZ$V,(d(1Edo>>J5Zis>#xU|Y►w. 4QEzRi_5P,4[#
JFIFHHC     C  dd" }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz w!1AQaq"2B #3Rbr $4%&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz ? >{b?>|pjRò<w,Tν;YgwN7O-j2vFZ>3PG4a_Jit?IE]N7S@^9+-.b$ו*mwW=+Э(b`"sv' qJ^S"sp  F<PkV*XeA8RxwTүDf~=u3\z;q\l3<#/gVb0HvwƛnfY"`AAWįؾ]:&9x.}Z&꽾Q|8:߃c] ujRAT<֔TԖg9fqMRz5kA:C -J?\)H/um"o.[YX[1^}Que Pұ<k^]}ko*+" ]g%:~)Iǡ~_~,|=kkxO|ANԔX'!|To/0;l-! y1Fy=_ i/ǃMq@ *U1 rUQ,g`Qԕ<M~=]|XX2ncvolc8W,ޝ[8=S>nx7>X> C'yCkƣPռ;h:N$¹XdkGƟr~ W9[ @蒀$R@gr(ѽUGܴxή"rzm~Ρ~뺥My{\J1 C "E !1''OXXNElm lNq 4?CM0kwHh^*W普!eyc᥉e +Gc~ٍwoT-ęlҽ/5%#h `jԋŨoe&-Nw0b0vg kiVsC"e/-Fp;wkuIuy[ʹ[s%|| +i-(Y%0=k{|{YRtỻ[[d(SVǫ޼ګDx\ȥBjѮ\Y͐I#l9Xkcv1%w~#N?죳m<I#*=붍UterZAI~}O|+tEK2I Ўx<VƯ#Mچ0kodr2857x5ֿ_lb[\!ʇHM,Ha^??mυtK9[m;NHL o9'$\hzUcI8k{)`az|ɦm-4jh~,J-x]y<Oak\ |A=Y!yZB "+vuۍZ&Dq v9 =V$xHomMmeŬnBzcO[hMNΧrdaʏQp=_iZ')+Ie7t+b3G7fOEzxGjpǵ-e*obrKI&qrXی_Ts7)=YڹggkX~}}ko BJxT33>?iX]oK,qI4t&}Yx@񌰴垡<Itt;/J~TҖ\HZ]gp8+]˃5f ;#Ƿ⽓/? 5+ik,`e2 䏳|/Nwu.*]}F&hVN??2 kxoOmKTԖܐlc=yo'ŎmFYܗyYhc*c7 ώ}(Ҝn$/$K|i'q_7BK=J}H\*%i_=$-)bI KrL._#W/>+35Nõ_O>{{_gJy}{`$1ēf_<+ki!U8u G" `Nvo~^gI}}an. M:G 8 ^Ius6lcsҾc<<aoMoGեBRmkסw]6 ʓOʶPʡ@ _ ۿOڤ<a|Gt@%dObK2M[ m(5(uҼypҎ#Y8BO_A_^']fkSV:#]\4HXrX䞽}k,i:mv+zx| KW|{4wd|o?/ae$\#9C_7"%AW? \(-["Wב( Wتyi ^8IR^>y72j::}۞%ࢴ)MpKUkK|e]xQ^G$8|2k2/3)YA^)ҧ> E2ɂ_4Ǻ?ሥGyW _>$CHwI1Ԋm QF/WHuUZZY9|Zѥ6diR& l(3ΤB~EFIx>!oY E$ڋiJ|fFDnN61gijWEVlQ|)v|dW|Oo?ͮqGt+K׏(TF;Kf<XU`QUNSizwwclKho_Ħ:?u FKk"΀-2@#U9S~ o ~Ğ3P;W2?7XcR?305s^?/EwK͹w(}<A<F?xpَrEӑaE|U$gr2Ƽ$aM9_}9&W~68i=,kw[/4u6j -?k"r>ge .RpIPyHFCXc99,iu/&gom Ji&HF&rNT\3@'#oNd,VoTǥb~?Ӿ!hV: N,ʟ&F=g"Q\> q˫.]JI4X5ߊOoY>ەtM<13[gL<QfK&bTo@)Z?o_h6_Af%S"'«}cB[_28-&<{s=G޾ߪ劳m%%|cFq%t:dqU "/O뚂ZLӬs"BEݝ,rc{װɿ /Sy1+ȷF~18x*>Z]81Tip~uƣgH$YGlڊ|)ar2Lhx9WWiߩ? E hў3bHvmcbs&u@+?sÞ4JX|<ݯfQ1n_NL巴^[뫘ѭj`LglUrrs \WBZgT1C}yK|fѴF/o4ѓq:IsKwfC+O|ii_.->]RM P1ݕU?3|i?5F.2$&Ke3Ee5whz]ZZ6+cXY$,FQ~^erMIi_\CZ;7<Wg?ic: zFϳ;R5e"V|+H*##|qhcϜd$p?)|\6mHՂh:pA5XX3=/a<[;fyljeҠϳqTɯ)okF։eowm6DI4| `9}+GƿEŸ{Ö։njW7`Vw,T q_j=YTHwuߴSsuw6iJԭEzB:yc$a|bJ-a\OUz[5ω<a׺n6@E_'L/_@|>իxkM7LC'^"3g㯂4-X}ĥZ+HYP2>x~%m C|7jqmrYL@(ƛ\>&pջ{+ 噶kgtvb:z.x?K3.<AyaEEB0#teL,Q'2OE ΨK$&ݒf V1uMo+fmwO16z;hvGsAEt"Ay]<5j7>"|3(8Ԯ|Uqc߿.mdvYN[/zT$c%A1In!~xr?mGWDu8.n4),rS Lں,0|Vw^by.1ǤkN2L/.s=̵%M2#.^KZʷX>cR;u<W̦'|Ra ĐAo0 aշ_>h_e1I% ̝ht_XxRnͻaY*Q&  8Xy,|2<Ԛ/~]ji\hAͧιFm!) 峚'wg8VIotG+{⼯^ +V{9/@m%"!<cX f''}{?öa @ov q41? ĘC/ww_7eo~{E=l^{K28M{_:F| sxkOݧ̃ >xK+㐕e`1vgE-OI~_ \4LD}Ÿ=J иQ_?x'NaDU? u7ľ:nO!r)*~9x/~-~E6][&ۂ K#ʆc_GUqztb쓺OV[Abg}m|-x^%px~խ킏\$/;o qV4Ix:K{41-8IgOv/_߳uYHյ#Q𕬅PILQ^['PÜ->8Oy|Wxu'_!NrI+`xv7ve}VAJWZ*J+k)1c!OG:Q^OG^+wu%K[e39+ȴ3*ڑj_5Ɵ",bs/-ͤ|=Ӊӛ#'Ex;{I<P>Cvd7X!P=7FƳx[^!YaI(-iX1k$ `Z Sƨv:? ޥ}>.YBn rr:N VBBҊ+(mU6g\9G'#eb$b wX"+Žn6w)q +?q=:as+CJøz|'(+YG|p2M]mҭEQq c'pi|>WĻuߪZ$V,(d(1Edo>>J5Zis>#xU|Y►w. 4QEzRi_5P,4[#
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the 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 _ 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 _ 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
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is pure Python implementation of sentinel linear search algorithm For doctests run following command: python -m doctest -v sentinel_linear_search.py or python3 -m doctest -v sentinel_linear_search.py For manual testing run: python sentinel_linear_search.py """ def sentinel_linear_search(sequence, target): """Pure implementation of sentinel linear search algorithm in Python :param sequence: some sequence with comparable items :param target: item value to search :return: index of found item or None if item is not found Examples: >>> sentinel_linear_search([0, 5, 7, 10, 15], 0) 0 >>> sentinel_linear_search([0, 5, 7, 10, 15], 15) 4 >>> sentinel_linear_search([0, 5, 7, 10, 15], 5) 1 >>> sentinel_linear_search([0, 5, 7, 10, 15], 6) """ sequence.append(target) index = 0 while sequence[index] != target: index += 1 sequence.pop() if index == len(sequence): return None return index if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item) for item in user_input.split(",")] target_input = input("Enter a single number to be found in the list:\n") target = int(target_input) result = sentinel_linear_search(sequence, target) if result is not None: print(f"{target} found at positions: {result}") else: print("Not found")
""" This is pure Python implementation of sentinel linear search algorithm For doctests run following command: python -m doctest -v sentinel_linear_search.py or python3 -m doctest -v sentinel_linear_search.py For manual testing run: python sentinel_linear_search.py """ def sentinel_linear_search(sequence, target): """Pure implementation of sentinel linear search algorithm in Python :param sequence: some sequence with comparable items :param target: item value to search :return: index of found item or None if item is not found Examples: >>> sentinel_linear_search([0, 5, 7, 10, 15], 0) 0 >>> sentinel_linear_search([0, 5, 7, 10, 15], 15) 4 >>> sentinel_linear_search([0, 5, 7, 10, 15], 5) 1 >>> sentinel_linear_search([0, 5, 7, 10, 15], 6) """ sequence.append(target) index = 0 while sequence[index] != target: index += 1 sequence.pop() if index == len(sequence): return None return index if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item) for item in user_input.split(",")] target_input = input("Enter a single number to be found in the list:\n") target = int(target_input) result = sentinel_linear_search(sequence, target) if result is not None: print(f"{target} found at positions: {result}") else: print("Not found")
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Implementation of GradientBoostingRegressor in sklearn using the boston dataset which is very popular for regression problem to predict house price. """ import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_boston from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split def main(): # loading the dataset from the sklearn df = load_boston() print(df.keys()) # now let construct a data frame df_boston = pd.DataFrame(df.data, columns=df.feature_names) # let add the target to the dataframe df_boston["Price"] = df.target # print the first five rows using the head function print(df_boston.head()) # Summary statistics print(df_boston.describe().T) # Feature selection x = df_boston.iloc[:, :-1] y = df_boston.iloc[:, -1] # target variable # split the data with 75% train and 25% test sets. x_train, x_test, y_train, y_test = train_test_split( x, y, random_state=0, test_size=0.25 ) model = GradientBoostingRegressor( n_estimators=500, max_depth=5, min_samples_split=4, learning_rate=0.01 ) # training the model model.fit(x_train, y_train) # to see how good the model fit the data training_score = model.score(x_train, y_train).round(3) test_score = model.score(x_test, y_test).round(3) print("Training score of GradientBoosting is :", training_score) print("The test score of GradientBoosting is :", test_score) # Let us evaluation the model by finding the errors y_pred = model.predict(x_test) # The mean squared error print(f"Mean squared error: {mean_squared_error(y_test, y_pred):.2f}") # Explained variance score: 1 is perfect prediction print(f"Test Variance score: {r2_score(y_test, y_pred):.2f}") # So let's run the model against the test data fig, ax = plt.subplots() ax.scatter(y_test, y_pred, edgecolors=(0, 0, 0)) ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], "k--", lw=4) ax.set_xlabel("Actual") ax.set_ylabel("Predicted") ax.set_title("Truth vs Predicted") # this show function will display the plotting plt.show() if __name__ == "__main__": main()
"""Implementation of GradientBoostingRegressor in sklearn using the boston dataset which is very popular for regression problem to predict house price. """ import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_boston from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split def main(): # loading the dataset from the sklearn df = load_boston() print(df.keys()) # now let construct a data frame df_boston = pd.DataFrame(df.data, columns=df.feature_names) # let add the target to the dataframe df_boston["Price"] = df.target # print the first five rows using the head function print(df_boston.head()) # Summary statistics print(df_boston.describe().T) # Feature selection x = df_boston.iloc[:, :-1] y = df_boston.iloc[:, -1] # target variable # split the data with 75% train and 25% test sets. x_train, x_test, y_train, y_test = train_test_split( x, y, random_state=0, test_size=0.25 ) model = GradientBoostingRegressor( n_estimators=500, max_depth=5, min_samples_split=4, learning_rate=0.01 ) # training the model model.fit(x_train, y_train) # to see how good the model fit the data training_score = model.score(x_train, y_train).round(3) test_score = model.score(x_test, y_test).round(3) print("Training score of GradientBoosting is :", training_score) print("The test score of GradientBoosting is :", test_score) # Let us evaluation the model by finding the errors y_pred = model.predict(x_test) # The mean squared error print(f"Mean squared error: {mean_squared_error(y_test, y_pred):.2f}") # Explained variance score: 1 is perfect prediction print(f"Test Variance score: {r2_score(y_test, y_pred):.2f}") # So let's run the model against the test data fig, ax = plt.subplots() ax.scatter(y_test, y_pred, edgecolors=(0, 0, 0)) ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], "k--", lw=4) ax.set_xlabel("Actual") ax.set_ylabel("Predicted") ax.set_title("Truth vs Predicted") # this show function will display the plotting plt.show() if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implements a disjoint set using Lists and some added heuristics for efficiency Union by Rank Heuristic and Path Compression """ class DisjointSet: def __init__(self, set_counts: list) -> None: """ Initialize with a list of the number of items in each set and with rank = 1 for each set """ self.set_counts = set_counts self.max_set = max(set_counts) num_sets = len(set_counts) self.ranks = [1] * num_sets self.parents = list(range(num_sets)) def merge(self, src: int, dst: int) -> bool: """ Merge two sets together using Union by rank heuristic Return True if successful Merge two disjoint sets >>> A = DisjointSet([1, 1, 1]) >>> A.merge(1, 2) True >>> A.merge(0, 2) True >>> A.merge(0, 1) False """ src_parent = self.get_parent(src) dst_parent = self.get_parent(dst) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] self.set_counts[src_parent] = 0 self.parents[src_parent] = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 joined_set_size = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] self.set_counts[dst_parent] = 0 self.parents[dst_parent] = src_parent joined_set_size = self.set_counts[src_parent] self.max_set = max(self.max_set, joined_set_size) return True def get_parent(self, disj_set: int) -> int: """ Find the Parent of a given set >>> A = DisjointSet([1, 1, 1]) >>> A.merge(1, 2) True >>> A.get_parent(0) 0 >>> A.get_parent(1) 2 """ if self.parents[disj_set] == disj_set: return disj_set self.parents[disj_set] = self.get_parent(self.parents[disj_set]) return self.parents[disj_set]
""" Implements a disjoint set using Lists and some added heuristics for efficiency Union by Rank Heuristic and Path Compression """ class DisjointSet: def __init__(self, set_counts: list) -> None: """ Initialize with a list of the number of items in each set and with rank = 1 for each set """ self.set_counts = set_counts self.max_set = max(set_counts) num_sets = len(set_counts) self.ranks = [1] * num_sets self.parents = list(range(num_sets)) def merge(self, src: int, dst: int) -> bool: """ Merge two sets together using Union by rank heuristic Return True if successful Merge two disjoint sets >>> A = DisjointSet([1, 1, 1]) >>> A.merge(1, 2) True >>> A.merge(0, 2) True >>> A.merge(0, 1) False """ src_parent = self.get_parent(src) dst_parent = self.get_parent(dst) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] self.set_counts[src_parent] = 0 self.parents[src_parent] = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 joined_set_size = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] self.set_counts[dst_parent] = 0 self.parents[dst_parent] = src_parent joined_set_size = self.set_counts[src_parent] self.max_set = max(self.max_set, joined_set_size) return True def get_parent(self, disj_set: int) -> int: """ Find the Parent of a given set >>> A = DisjointSet([1, 1, 1]) >>> A.merge(1, 2) True >>> A.get_parent(0) 0 >>> A.get_parent(1) 2 """ if self.parents[disj_set] == disj_set: return disj_set self.parents[disj_set] = self.get_parent(self.parents[disj_set]) return self.parents[disj_set]
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ result = 0 for i in range(n): if i % 3 == 0 or i % 5 == 0: result += i return result if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ result = 0 for i in range(n): if i % 3 == 0 or i % 5 == 0: result += i return result if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://en.wikipedia.org/wiki/Hill_climbing import math class SearchProblem: """ An interface to define search problems. The interface will be illustrated using the example of mathematical function. """ def __init__(self, x: int, y: int, step_size: int, function_to_optimize): """ The constructor of the search problem. x: the x coordinate of the current search state. y: the y coordinate of the current search state. step_size: size of the step to take when looking for neighbors. function_to_optimize: a function to optimize having the signature f(x, y). """ self.x = x self.y = y self.step_size = step_size self.function = function_to_optimize def score(self) -> int: """ Returns the output of the function called with current x and y coordinates. >>> def test_function(x, y): ... return x + y >>> SearchProblem(0, 0, 1, test_function).score() # 0 + 0 = 0 0 >>> SearchProblem(5, 7, 1, test_function).score() # 5 + 7 = 12 12 """ return self.function(self.x, self.y) def get_neighbors(self): """ Returns a list of coordinates of neighbors adjacent to the current coordinates. Neighbors: | 0 | 1 | 2 | | 3 | _ | 4 | | 5 | 6 | 7 | """ step_size = self.step_size return [ SearchProblem(x, y, step_size, self.function) for x, y in ( (self.x - step_size, self.y - step_size), (self.x - step_size, self.y), (self.x - step_size, self.y + step_size), (self.x, self.y - step_size), (self.x, self.y + step_size), (self.x + step_size, self.y - step_size), (self.x + step_size, self.y), (self.x + step_size, self.y + step_size), ) ] def __hash__(self): """ hash the string representation of the current search state. """ return hash(str(self)) def __eq__(self, obj): """ Check if the 2 objects are equal. """ if isinstance(obj, SearchProblem): return hash(str(self)) == hash(str(obj)) return False def __str__(self): """ string representation of the current search state. >>> str(SearchProblem(0, 0, 1, None)) 'x: 0 y: 0' >>> str(SearchProblem(2, 5, 1, None)) 'x: 2 y: 5' """ return f"x: {self.x} y: {self.y}" def hill_climbing( search_prob, find_max: bool = True, max_x: float = math.inf, min_x: float = -math.inf, max_y: float = math.inf, min_y: float = -math.inf, visualization: bool = False, max_iter: int = 10000, ) -> SearchProblem: """ Implementation of the hill climbling algorithm. We start with a given state, find all its neighbors, move towards the neighbor which provides the maximum (or minimum) change. We keep doing this until we are at a state where we do not have any neighbors which can improve the solution. Args: search_prob: The search state at the start. find_max: If True, the algorithm should find the maximum else the minimum. max_x, min_x, max_y, min_y: the maximum and minimum bounds of x and y. visualization: If True, a matplotlib graph is displayed. max_iter: number of times to run the iteration. Returns a search state having the maximum (or minimum) score. """ current_state = search_prob scores = [] # list to store the current score at each iteration iterations = 0 solution_found = False visited = set() while not solution_found and iterations < max_iter: visited.add(current_state) iterations += 1 current_score = current_state.score() scores.append(current_score) neighbors = current_state.get_neighbors() max_change = -math.inf min_change = math.inf next_state = None # to hold the next best neighbor for neighbor in neighbors: if neighbor in visited: continue # do not want to visit the same state again if ( neighbor.x > max_x or neighbor.x < min_x or neighbor.y > max_y or neighbor.y < min_y ): continue # neighbor outside our bounds change = neighbor.score() - current_score if find_max: # finding max # going to direction with greatest ascent if change > max_change and change > 0: max_change = change next_state = neighbor else: # finding min # to direction with greatest descent if change < min_change and change < 0: min_change = change next_state = neighbor if next_state is not None: # we found at least one neighbor which improved the current state current_state = next_state else: # since we have no neighbor that improves the solution we stop the search solution_found = True if visualization: from matplotlib import pyplot as plt plt.plot(range(iterations), scores) plt.xlabel("Iterations") plt.ylabel("Function values") plt.show() return current_state if __name__ == "__main__": import doctest doctest.testmod() def test_f1(x, y): return (x**2) + (y**2) # starting the problem with initial coordinates (3, 4) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing(prob, find_max=False) print( "The minimum score for f(x, y) = x^2 + y^2 found via hill climbing: " f"{local_min.score()}" ) # starting the problem with initial coordinates (12, 47) prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f"and 50 > y > - 5 found via hill climbing: {local_min.score()}" ) def test_f2(x, y): return (3 * x**2) - (6 * y) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing(prob, find_max=True) print( "The maximum score for f(x, y) = x^2 + y^2 found via hill climbing: " f"{local_min.score()}" )
# https://en.wikipedia.org/wiki/Hill_climbing import math class SearchProblem: """ An interface to define search problems. The interface will be illustrated using the example of mathematical function. """ def __init__(self, x: int, y: int, step_size: int, function_to_optimize): """ The constructor of the search problem. x: the x coordinate of the current search state. y: the y coordinate of the current search state. step_size: size of the step to take when looking for neighbors. function_to_optimize: a function to optimize having the signature f(x, y). """ self.x = x self.y = y self.step_size = step_size self.function = function_to_optimize def score(self) -> int: """ Returns the output of the function called with current x and y coordinates. >>> def test_function(x, y): ... return x + y >>> SearchProblem(0, 0, 1, test_function).score() # 0 + 0 = 0 0 >>> SearchProblem(5, 7, 1, test_function).score() # 5 + 7 = 12 12 """ return self.function(self.x, self.y) def get_neighbors(self): """ Returns a list of coordinates of neighbors adjacent to the current coordinates. Neighbors: | 0 | 1 | 2 | | 3 | _ | 4 | | 5 | 6 | 7 | """ step_size = self.step_size return [ SearchProblem(x, y, step_size, self.function) for x, y in ( (self.x - step_size, self.y - step_size), (self.x - step_size, self.y), (self.x - step_size, self.y + step_size), (self.x, self.y - step_size), (self.x, self.y + step_size), (self.x + step_size, self.y - step_size), (self.x + step_size, self.y), (self.x + step_size, self.y + step_size), ) ] def __hash__(self): """ hash the string representation of the current search state. """ return hash(str(self)) def __eq__(self, obj): """ Check if the 2 objects are equal. """ if isinstance(obj, SearchProblem): return hash(str(self)) == hash(str(obj)) return False def __str__(self): """ string representation of the current search state. >>> str(SearchProblem(0, 0, 1, None)) 'x: 0 y: 0' >>> str(SearchProblem(2, 5, 1, None)) 'x: 2 y: 5' """ return f"x: {self.x} y: {self.y}" def hill_climbing( search_prob, find_max: bool = True, max_x: float = math.inf, min_x: float = -math.inf, max_y: float = math.inf, min_y: float = -math.inf, visualization: bool = False, max_iter: int = 10000, ) -> SearchProblem: """ Implementation of the hill climbling algorithm. We start with a given state, find all its neighbors, move towards the neighbor which provides the maximum (or minimum) change. We keep doing this until we are at a state where we do not have any neighbors which can improve the solution. Args: search_prob: The search state at the start. find_max: If True, the algorithm should find the maximum else the minimum. max_x, min_x, max_y, min_y: the maximum and minimum bounds of x and y. visualization: If True, a matplotlib graph is displayed. max_iter: number of times to run the iteration. Returns a search state having the maximum (or minimum) score. """ current_state = search_prob scores = [] # list to store the current score at each iteration iterations = 0 solution_found = False visited = set() while not solution_found and iterations < max_iter: visited.add(current_state) iterations += 1 current_score = current_state.score() scores.append(current_score) neighbors = current_state.get_neighbors() max_change = -math.inf min_change = math.inf next_state = None # to hold the next best neighbor for neighbor in neighbors: if neighbor in visited: continue # do not want to visit the same state again if ( neighbor.x > max_x or neighbor.x < min_x or neighbor.y > max_y or neighbor.y < min_y ): continue # neighbor outside our bounds change = neighbor.score() - current_score if find_max: # finding max # going to direction with greatest ascent if change > max_change and change > 0: max_change = change next_state = neighbor else: # finding min # to direction with greatest descent if change < min_change and change < 0: min_change = change next_state = neighbor if next_state is not None: # we found at least one neighbor which improved the current state current_state = next_state else: # since we have no neighbor that improves the solution we stop the search solution_found = True if visualization: from matplotlib import pyplot as plt plt.plot(range(iterations), scores) plt.xlabel("Iterations") plt.ylabel("Function values") plt.show() return current_state if __name__ == "__main__": import doctest doctest.testmod() def test_f1(x, y): return (x**2) + (y**2) # starting the problem with initial coordinates (3, 4) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing(prob, find_max=False) print( "The minimum score for f(x, y) = x^2 + y^2 found via hill climbing: " f"{local_min.score()}" ) # starting the problem with initial coordinates (12, 47) prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f"and 50 > y > - 5 found via hill climbing: {local_min.score()}" ) def test_f2(x, y): return (3 * x**2) - (6 * y) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing(prob, find_max=True) print( "The maximum score for f(x, y) = x^2 + y^2 found via hill climbing: " f"{local_min.score()}" )
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" In mathematics, the Lucas–Lehmer test (LLT) is a primality test for Mersenne numbers. https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test A Mersenne number is a number that is one less than a power of two. That is M_p = 2^p - 1 https://en.wikipedia.org/wiki/Mersenne_prime The Lucas–Lehmer test is the primality test used by the Great Internet Mersenne Prime Search (GIMPS) to locate large primes. """ # Primality test 2^p - 1 # Return true if 2^p - 1 is prime def lucas_lehmer_test(p: int) -> bool: """ >>> lucas_lehmer_test(p=7) True >>> lucas_lehmer_test(p=11) False # M_11 = 2^11 - 1 = 2047 = 23 * 89 """ if p < 2: raise ValueError("p should not be less than 2!") elif p == 2: return True s = 4 m = (1 << p) - 1 for _ in range(p - 2): s = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
""" In mathematics, the Lucas–Lehmer test (LLT) is a primality test for Mersenne numbers. https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test A Mersenne number is a number that is one less than a power of two. That is M_p = 2^p - 1 https://en.wikipedia.org/wiki/Mersenne_prime The Lucas–Lehmer test is the primality test used by the Great Internet Mersenne Prime Search (GIMPS) to locate large primes. """ # Primality test 2^p - 1 # Return true if 2^p - 1 is prime def lucas_lehmer_test(p: int) -> bool: """ >>> lucas_lehmer_test(p=7) True >>> lucas_lehmer_test(p=11) False # M_11 = 2^11 - 1 = 2047 = 23 * 89 """ if p < 2: raise ValueError("p should not be less than 2!") elif p == 2: return True s = 4 m = (1 << p) - 1 for _ in range(p - 2): s = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Horizontal Projectile Motion problem in physics. This algorithm solves a specific problem in which the motion starts from the ground as can be seen below: (v = 0) * * * * * * * * * * * * GROUND GROUND For more info: https://en.wikipedia.org/wiki/Projectile_motion """ # Importing packages from math import radians as angle_to_radians from math import sin # Acceleration Constant on Earth (unit m/s^2) g = 9.80665 def check_args(init_velocity: float, angle: float) -> None: """ Check that the arguments are valid """ # Ensure valid instance if not isinstance(init_velocity, (int, float)): raise TypeError("Invalid velocity. Should be a positive number.") if not isinstance(angle, (int, float)): raise TypeError("Invalid angle. Range is 1-90 degrees.") # Ensure valid angle if angle > 90 or angle < 1: raise ValueError("Invalid angle. Range is 1-90 degrees.") # Ensure valid velocity if init_velocity < 0: raise ValueError("Invalid velocity. Should be a positive number.") def horizontal_distance(init_velocity: float, angle: float) -> float: """ Returns the horizontal distance that the object cover Formula: v_0^2 * sin(2 * alpha) --------------------- g v_0 - initial velocity alpha - angle >>> horizontal_distance(30, 45) 91.77 >>> horizontal_distance(100, 78) 414.76 >>> horizontal_distance(-1, 20) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, -20) Traceback (most recent call last): ... ValueError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(2 * angle) return round(init_velocity**2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: """ Returns the maximum height that the object reach Formula: v_0^2 * sin^2(alpha) -------------------- 2g v_0 - initial velocity alpha - angle >>> max_height(30, 45) 22.94 >>> max_height(100, 78) 487.82 >>> max_height("a", 20) Traceback (most recent call last): ... TypeError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: """ Returns total time of the motion Formula: 2 * v_0 * sin(alpha) -------------------- g v_0 - initial velocity alpha - angle >>> total_time(30, 45) 4.33 >>> total_time(100, 78) 19.95 >>> total_time(-10, 40) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> total_time(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(2 * init_velocity * sin(radians) / g, 2) def test_motion() -> None: """ >>> test_motion() """ v0, angle = 25, 20 assert horizontal_distance(v0, angle) == 40.97 assert max_height(v0, angle) == 3.73 assert total_time(v0, angle) == 1.74 if __name__ == "__main__": from doctest import testmod testmod() # Get input from user init_vel = float(input("Initial Velocity: ").strip()) # Get input from user angle = float(input("angle: ").strip()) # Print results print() print("Results: ") print(f"Horizontal Distance: {str(horizontal_distance(init_vel, angle))} [m]") print(f"Maximum Height: {str(max_height(init_vel, angle))} [m]") print(f"Total Time: {str(total_time(init_vel, angle))} [s]")
""" Horizontal Projectile Motion problem in physics. This algorithm solves a specific problem in which the motion starts from the ground as can be seen below: (v = 0) * * * * * * * * * * * * GROUND GROUND For more info: https://en.wikipedia.org/wiki/Projectile_motion """ # Importing packages from math import radians as angle_to_radians from math import sin # Acceleration Constant on Earth (unit m/s^2) g = 9.80665 def check_args(init_velocity: float, angle: float) -> None: """ Check that the arguments are valid """ # Ensure valid instance if not isinstance(init_velocity, (int, float)): raise TypeError("Invalid velocity. Should be a positive number.") if not isinstance(angle, (int, float)): raise TypeError("Invalid angle. Range is 1-90 degrees.") # Ensure valid angle if angle > 90 or angle < 1: raise ValueError("Invalid angle. Range is 1-90 degrees.") # Ensure valid velocity if init_velocity < 0: raise ValueError("Invalid velocity. Should be a positive number.") def horizontal_distance(init_velocity: float, angle: float) -> float: """ Returns the horizontal distance that the object cover Formula: v_0^2 * sin(2 * alpha) --------------------- g v_0 - initial velocity alpha - angle >>> horizontal_distance(30, 45) 91.77 >>> horizontal_distance(100, 78) 414.76 >>> horizontal_distance(-1, 20) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, -20) Traceback (most recent call last): ... ValueError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(2 * angle) return round(init_velocity**2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: """ Returns the maximum height that the object reach Formula: v_0^2 * sin^2(alpha) -------------------- 2g v_0 - initial velocity alpha - angle >>> max_height(30, 45) 22.94 >>> max_height(100, 78) 487.82 >>> max_height("a", 20) Traceback (most recent call last): ... TypeError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: """ Returns total time of the motion Formula: 2 * v_0 * sin(alpha) -------------------- g v_0 - initial velocity alpha - angle >>> total_time(30, 45) 4.33 >>> total_time(100, 78) 19.95 >>> total_time(-10, 40) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> total_time(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(2 * init_velocity * sin(radians) / g, 2) def test_motion() -> None: """ >>> test_motion() """ v0, angle = 25, 20 assert horizontal_distance(v0, angle) == 40.97 assert max_height(v0, angle) == 3.73 assert total_time(v0, angle) == 1.74 if __name__ == "__main__": from doctest import testmod testmod() # Get input from user init_vel = float(input("Initial Velocity: ").strip()) # Get input from user angle = float(input("angle: ").strip()) # Print results print() print("Results: ") print(f"Horizontal Distance: {str(horizontal_distance(init_vel, angle))} [m]") print(f"Maximum Height: {str(max_height(init_vel, angle))} [m]") print(f"Total Time: {str(total_time(init_vel, angle))} [s]")
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def double_sort(lst): """This sorting algorithm sorts an array using the principle of bubble sort, but does it both from left to right and right to left. Hence, it's called "Double sort" :param collection: mutable ordered sequence of elements :return: the same collection in ascending order Examples: >>> double_sort([-1 ,-2 ,-3 ,-4 ,-5 ,-6 ,-7]) [-7, -6, -5, -4, -3, -2, -1] >>> double_sort([]) [] >>> double_sort([-1 ,-2 ,-3 ,-4 ,-5 ,-6]) [-6, -5, -4, -3, -2, -1] >>> double_sort([-3, 10, 16, -42, 29]) == sorted([-3, 10, 16, -42, 29]) True """ no_of_elements = len(lst) for _ in range( 0, int(((no_of_elements - 1) / 2) + 1) ): # we don't need to traverse to end of list as for j in range(0, no_of_elements - 1): if ( lst[j + 1] < lst[j] ): # applying bubble sort algorithm from left to right (or forwards) temp = lst[j + 1] lst[j + 1] = lst[j] lst[j] = temp if ( lst[no_of_elements - 1 - j] < lst[no_of_elements - 2 - j] ): # applying bubble sort algorithm from right to left (or backwards) temp = lst[no_of_elements - 1 - j] lst[no_of_elements - 1 - j] = lst[no_of_elements - 2 - j] lst[no_of_elements - 2 - j] = temp return lst if __name__ == "__main__": print("enter the list to be sorted") lst = [int(x) for x in input().split()] # inputing elements of the list in one line sorted_lst = double_sort(lst) print("the sorted list is") print(sorted_lst)
def double_sort(lst): """This sorting algorithm sorts an array using the principle of bubble sort, but does it both from left to right and right to left. Hence, it's called "Double sort" :param collection: mutable ordered sequence of elements :return: the same collection in ascending order Examples: >>> double_sort([-1 ,-2 ,-3 ,-4 ,-5 ,-6 ,-7]) [-7, -6, -5, -4, -3, -2, -1] >>> double_sort([]) [] >>> double_sort([-1 ,-2 ,-3 ,-4 ,-5 ,-6]) [-6, -5, -4, -3, -2, -1] >>> double_sort([-3, 10, 16, -42, 29]) == sorted([-3, 10, 16, -42, 29]) True """ no_of_elements = len(lst) for _ in range( 0, int(((no_of_elements - 1) / 2) + 1) ): # we don't need to traverse to end of list as for j in range(0, no_of_elements - 1): if ( lst[j + 1] < lst[j] ): # applying bubble sort algorithm from left to right (or forwards) temp = lst[j + 1] lst[j + 1] = lst[j] lst[j] = temp if ( lst[no_of_elements - 1 - j] < lst[no_of_elements - 2 - j] ): # applying bubble sort algorithm from right to left (or backwards) temp = lst[no_of_elements - 1 - j] lst[no_of_elements - 1 - j] = lst[no_of_elements - 2 - j] lst[no_of_elements - 2 - j] = temp return lst if __name__ == "__main__": print("enter the list to be sorted") lst = [int(x) for x in input().split()] # inputing elements of the list in one line sorted_lst = double_sort(lst) print("the sorted list is") print(sorted_lst)
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import numpy as np """ Here I implemented the scoring functions. MAE, MSE, RMSE, RMSLE are included. Those are used for calculating differences between predicted values and actual values. Metrics are slightly differentiated. Sometimes squared, rooted, even log is used. Using log and roots can be perceived as tools for penalizing big errors. However, using appropriate metrics depends on the situations, and types of data """ # Mean Absolute Error def mae(predict, actual): """ Examples(rounded for precision): >>> actual = [1,2,3];predict = [1,4,3] >>> np.around(mae(predict,actual),decimals = 2) 0.67 >>> actual = [1,1,1];predict = [1,1,1] >>> mae(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) difference = abs(predict - actual) score = difference.mean() return score # Mean Squared Error def mse(predict, actual): """ Examples(rounded for precision): >>> actual = [1,2,3];predict = [1,4,3] >>> np.around(mse(predict,actual),decimals = 2) 1.33 >>> actual = [1,1,1];predict = [1,1,1] >>> mse(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) difference = predict - actual square_diff = np.square(difference) score = square_diff.mean() return score # Root Mean Squared Error def rmse(predict, actual): """ Examples(rounded for precision): >>> actual = [1,2,3];predict = [1,4,3] >>> np.around(rmse(predict,actual),decimals = 2) 1.15 >>> actual = [1,1,1];predict = [1,1,1] >>> rmse(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) difference = predict - actual square_diff = np.square(difference) mean_square_diff = square_diff.mean() score = np.sqrt(mean_square_diff) return score # Root Mean Square Logarithmic Error def rmsle(predict, actual): """ Examples(rounded for precision): >>> actual = [10,10,30];predict = [10,2,30] >>> np.around(rmsle(predict,actual),decimals = 2) 0.75 >>> actual = [1,1,1];predict = [1,1,1] >>> rmsle(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) log_predict = np.log(predict + 1) log_actual = np.log(actual + 1) difference = log_predict - log_actual square_diff = np.square(difference) mean_square_diff = square_diff.mean() score = np.sqrt(mean_square_diff) return score # Mean Bias Deviation def mbd(predict, actual): """ This value is Negative, if the model underpredicts, positive, if it overpredicts. Example(rounded for precision): Here the model overpredicts >>> actual = [1,2,3];predict = [2,3,4] >>> np.around(mbd(predict,actual),decimals = 2) 50.0 Here the model underpredicts >>> actual = [1,2,3];predict = [0,1,1] >>> np.around(mbd(predict,actual),decimals = 2) -66.67 """ predict = np.array(predict) actual = np.array(actual) difference = predict - actual numerator = np.sum(difference) / len(predict) denumerator = np.sum(actual) / len(predict) # print(numerator, denumerator) score = float(numerator) / denumerator * 100 return score def manual_accuracy(predict, actual): return np.mean(np.array(actual) == np.array(predict))
import numpy as np """ Here I implemented the scoring functions. MAE, MSE, RMSE, RMSLE are included. Those are used for calculating differences between predicted values and actual values. Metrics are slightly differentiated. Sometimes squared, rooted, even log is used. Using log and roots can be perceived as tools for penalizing big errors. However, using appropriate metrics depends on the situations, and types of data """ # Mean Absolute Error def mae(predict, actual): """ Examples(rounded for precision): >>> actual = [1,2,3];predict = [1,4,3] >>> np.around(mae(predict,actual),decimals = 2) 0.67 >>> actual = [1,1,1];predict = [1,1,1] >>> mae(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) difference = abs(predict - actual) score = difference.mean() return score # Mean Squared Error def mse(predict, actual): """ Examples(rounded for precision): >>> actual = [1,2,3];predict = [1,4,3] >>> np.around(mse(predict,actual),decimals = 2) 1.33 >>> actual = [1,1,1];predict = [1,1,1] >>> mse(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) difference = predict - actual square_diff = np.square(difference) score = square_diff.mean() return score # Root Mean Squared Error def rmse(predict, actual): """ Examples(rounded for precision): >>> actual = [1,2,3];predict = [1,4,3] >>> np.around(rmse(predict,actual),decimals = 2) 1.15 >>> actual = [1,1,1];predict = [1,1,1] >>> rmse(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) difference = predict - actual square_diff = np.square(difference) mean_square_diff = square_diff.mean() score = np.sqrt(mean_square_diff) return score # Root Mean Square Logarithmic Error def rmsle(predict, actual): """ Examples(rounded for precision): >>> actual = [10,10,30];predict = [10,2,30] >>> np.around(rmsle(predict,actual),decimals = 2) 0.75 >>> actual = [1,1,1];predict = [1,1,1] >>> rmsle(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actual) log_predict = np.log(predict + 1) log_actual = np.log(actual + 1) difference = log_predict - log_actual square_diff = np.square(difference) mean_square_diff = square_diff.mean() score = np.sqrt(mean_square_diff) return score # Mean Bias Deviation def mbd(predict, actual): """ This value is Negative, if the model underpredicts, positive, if it overpredicts. Example(rounded for precision): Here the model overpredicts >>> actual = [1,2,3];predict = [2,3,4] >>> np.around(mbd(predict,actual),decimals = 2) 50.0 Here the model underpredicts >>> actual = [1,2,3];predict = [0,1,1] >>> np.around(mbd(predict,actual),decimals = 2) -66.67 """ predict = np.array(predict) actual = np.array(actual) difference = predict - actual numerator = np.sum(difference) / len(predict) denumerator = np.sum(actual) / len(predict) # print(numerator, denumerator) score = float(numerator) / denumerator * 100 return score def manual_accuracy(predict, actual): return np.mean(np.array(actual) == np.array(predict))
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# This is a comment. # Each line is a file pattern followed by one or more owners. # More details are here: https://help.github.com/articles/about-codeowners/ # The '*' pattern is global owners. # Order is important. The last matching pattern has the most precedence. /.* @cclauss @dhruvmanila # /arithmetic_analysis/ # /backtracking/ # /bit_manipulation/ # /blockchain/ # /boolean_algebra/ # /cellular_automata/ # /ciphers/ @cclauss # TODO: Uncomment this line after Hacktoberfest # /compression/ # /computer_vision/ # /conversions/ @cclauss # TODO: Uncomment this line after Hacktoberfest # /data_structures/ @cclauss # TODO: Uncomment this line after Hacktoberfest # /digital_image_processing/ # /divide_and_conquer/ # /dynamic_programming/ # /file_transfer/ # /fuzzy_logic/ # /genetic_algorithm/ # /geodesy/ # /graphics/ # /graphs/ # /greedy_method/ # /hashes/ # /images/ # /linear_algebra/ # /machine_learning/ # /maths/ # /matrix/ # /networking_flow/ # /neural_network/ # /other/ @cclauss # TODO: Uncomment this line after Hacktoberfest /project_euler/ @dhruvmanila # /quantum/ # /scheduling/ # /scripts/ # /searches/ # /sorts/ # /strings/ @cclauss # TODO: Uncomment this line after Hacktoberfest # /traversals/ /web_programming/ @cclauss
# This is a comment. # Each line is a file pattern followed by one or more owners. # More details are here: https://help.github.com/articles/about-codeowners/ # The '*' pattern is global owners. # Order is important. The last matching pattern has the most precedence. /.* @cclauss @dhruvmanila # /arithmetic_analysis/ # /backtracking/ # /bit_manipulation/ # /blockchain/ # /boolean_algebra/ # /cellular_automata/ # /ciphers/ @cclauss # TODO: Uncomment this line after Hacktoberfest # /compression/ # /computer_vision/ # /conversions/ @cclauss # TODO: Uncomment this line after Hacktoberfest # /data_structures/ @cclauss # TODO: Uncomment this line after Hacktoberfest # /digital_image_processing/ # /divide_and_conquer/ # /dynamic_programming/ # /file_transfer/ # /fuzzy_logic/ # /genetic_algorithm/ # /geodesy/ # /graphics/ # /graphs/ # /greedy_method/ # /hashes/ # /images/ # /linear_algebra/ # /machine_learning/ # /maths/ # /matrix/ # /networking_flow/ # /neural_network/ # /other/ @cclauss # TODO: Uncomment this line after Hacktoberfest /project_euler/ @dhruvmanila # /quantum/ # /scheduling/ # /scripts/ # /searches/ # /sorts/ # /strings/ @cclauss # TODO: Uncomment this line after Hacktoberfest # /traversals/ /web_programming/ @cclauss
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations import csv import requests from bs4 import BeautifulSoup def get_imdb_top_250_movies(url: str = "") -> dict[str, float]: url = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250" soup = BeautifulSoup(requests.get(url).text, "html.parser") titles = soup.find_all("td", attrs="titleColumn") ratings = soup.find_all("td", class_="ratingColumn imdbRating") return { title.a.text: float(rating.strong.text) for title, rating in zip(titles, ratings) } def write_movies(filename: str = "IMDb_Top_250_Movies.csv") -> None: movies = get_imdb_top_250_movies() with open(filename, "w", newline="") as out_file: writer = csv.writer(out_file) writer.writerow(["Movie title", "IMDb rating"]) for title, rating in movies.items(): writer.writerow([title, rating]) if __name__ == "__main__": write_movies()
from __future__ import annotations import csv import requests from bs4 import BeautifulSoup def get_imdb_top_250_movies(url: str = "") -> dict[str, float]: url = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250" soup = BeautifulSoup(requests.get(url).text, "html.parser") titles = soup.find_all("td", attrs="titleColumn") ratings = soup.find_all("td", class_="ratingColumn imdbRating") return { title.a.text: float(rating.strong.text) for title, rating in zip(titles, ratings) } def write_movies(filename: str = "IMDb_Top_250_Movies.csv") -> None: movies = get_imdb_top_250_movies() with open(filename, "w", newline="") as out_file: writer = csv.writer(out_file) writer.writerow(["Movie title", "IMDb rating"]) for title, rating in movies.items(): writer.writerow([title, rating]) if __name__ == "__main__": write_movies()
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def largest_product(grid): n_columns = len(grid[0]) n_rows = len(grid) largest = 0 lr_diag_product = 0 rl_diag_product = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(n_columns): for j in range(n_rows - 3): vert_product = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] horz_product = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: lr_diag_product = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: rl_diag_product = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) max_product = max( vert_product, horz_product, lr_diag_product, rl_diag_product ) if max_product > largest: largest = max_product return largest def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ grid = [] with open(os.path.dirname(__file__) + "/grid.txt") as file: for line in file: grid.append(line.strip("\n").split(" ")) grid = [[int(i) for i in grid[j]] for j in range(len(grid))] return largest_product(grid) if __name__ == "__main__": print(solution())
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def largest_product(grid): n_columns = len(grid[0]) n_rows = len(grid) largest = 0 lr_diag_product = 0 rl_diag_product = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(n_columns): for j in range(n_rows - 3): vert_product = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] horz_product = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: lr_diag_product = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: rl_diag_product = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) max_product = max( vert_product, horz_product, lr_diag_product, rl_diag_product ) if max_product > largest: largest = max_product return largest def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ grid = [] with open(os.path.dirname(__file__) + "/grid.txt") as file: for line in file: grid.append(line.strip("\n").split(" ")) grid = [[int(i) for i in grid[j]] for j in range(len(grid))] return largest_product(grid) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import numpy as np def qr_householder(a): """Return a QR-decomposition of the matrix A using Householder reflection. The QR-decomposition decomposes the matrix A of shape (m, n) into an orthogonal matrix Q of shape (m, m) and an upper triangular matrix R of shape (m, n). Note that the matrix A does not have to be square. This method of decomposing A uses the Householder reflection, which is numerically stable and of complexity O(n^3). https://en.wikipedia.org/wiki/QR_decomposition#Using_Householder_reflections Arguments: A -- a numpy.ndarray of shape (m, n) Note: several optimizations can be made for numeric efficiency, but this is intended to demonstrate how it would be represented in a mathematics textbook. In cases where efficiency is particularly important, an optimized version from BLAS should be used. >>> A = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]], dtype=float) >>> Q, R = qr_householder(A) >>> # check that the decomposition is correct >>> np.allclose(Q@R, A) True >>> # check that Q is orthogonal >>> np.allclose([email protected], np.eye(A.shape[0])) True >>> np.allclose(Q.T@Q, np.eye(A.shape[0])) True >>> # check that R is upper triangular >>> np.allclose(np.triu(R), R) True """ m, n = a.shape t = min(m, n) q = np.eye(m) r = a.copy() for k in range(t - 1): # select a column of modified matrix A': x = r[k:, [k]] # construct first basis vector e1 = np.zeros_like(x) e1[0] = 1.0 # determine scaling factor alpha = np.linalg.norm(x) # construct vector v for Householder reflection v = x + np.sign(x[0]) * alpha * e1 v /= np.linalg.norm(v) # construct the Householder matrix q_k = np.eye(m - k) - 2.0 * v @ v.T # pad with ones and zeros as necessary q_k = np.block([[np.eye(k), np.zeros((k, m - k))], [np.zeros((m - k, k)), q_k]]) q = q @ q_k.T r = q_k @ r return q, r if __name__ == "__main__": import doctest doctest.testmod()
import numpy as np def qr_householder(a): """Return a QR-decomposition of the matrix A using Householder reflection. The QR-decomposition decomposes the matrix A of shape (m, n) into an orthogonal matrix Q of shape (m, m) and an upper triangular matrix R of shape (m, n). Note that the matrix A does not have to be square. This method of decomposing A uses the Householder reflection, which is numerically stable and of complexity O(n^3). https://en.wikipedia.org/wiki/QR_decomposition#Using_Householder_reflections Arguments: A -- a numpy.ndarray of shape (m, n) Note: several optimizations can be made for numeric efficiency, but this is intended to demonstrate how it would be represented in a mathematics textbook. In cases where efficiency is particularly important, an optimized version from BLAS should be used. >>> A = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]], dtype=float) >>> Q, R = qr_householder(A) >>> # check that the decomposition is correct >>> np.allclose(Q@R, A) True >>> # check that Q is orthogonal >>> np.allclose([email protected], np.eye(A.shape[0])) True >>> np.allclose(Q.T@Q, np.eye(A.shape[0])) True >>> # check that R is upper triangular >>> np.allclose(np.triu(R), R) True """ m, n = a.shape t = min(m, n) q = np.eye(m) r = a.copy() for k in range(t - 1): # select a column of modified matrix A': x = r[k:, [k]] # construct first basis vector e1 = np.zeros_like(x) e1[0] = 1.0 # determine scaling factor alpha = np.linalg.norm(x) # construct vector v for Householder reflection v = x + np.sign(x[0]) * alpha * e1 v /= np.linalg.norm(v) # construct the Householder matrix q_k = np.eye(m - k) - 2.0 * v @ v.T # pad with ones and zeros as necessary q_k = np.block([[np.eye(k), np.zeros((k, m - k))], [np.zeros((m - k, k)), q_k]]) q = q @ q_k.T r = q_k @ r return q, r if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 from .hash_table import HashTable class QuadraticProbing(HashTable): """ Basic Hash Table example with open addressing using Quadratic Probing """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _collision_resolution(self, key, data=None): i = 1 new_key = self.hash_function(key + i * i) while self.values[new_key] is not None and self.values[new_key] != key: i += 1 new_key = ( self.hash_function(key + i * i) if not self.balanced_factor() >= self.lim_charge else None ) if new_key is None: break return new_key
#!/usr/bin/env python3 from .hash_table import HashTable class QuadraticProbing(HashTable): """ Basic Hash Table example with open addressing using Quadratic Probing """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _collision_resolution(self, key, data=None): i = 1 new_key = self.hash_function(key + i * i) while self.values[new_key] is not None and self.values[new_key] != key: i += 1 new_key = ( self.hash_function(key + i * i) if not self.balanced_factor() >= self.lim_charge else None ) if new_key is None: break return new_key
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Author : Mehdi ALAOUI This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence. The problem is : Given an array, to find the longest and increasing sub-array in that given array and return it. Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output """ from __future__ import annotations def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive """ Some examples >>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) [10, 22, 33, 41, 60, 80] >>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9]) [1, 2, 3, 9] >>> longest_subsequence([9, 8, 7, 6, 5, 7]) [8] >>> longest_subsequence([1, 1, 1]) [1, 1, 1] >>> longest_subsequence([]) [] """ array_length = len(array) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else pivot = array[0] is_found = False i = 1 longest_subseq: list[int] = [] while not is_found and i < array_length: if array[i] < pivot: is_found = True temp_array = [element for element in array[i:] if element >= array[i]] temp_array = longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): longest_subseq = temp_array else: i += 1 temp_array = [element for element in array[1:] if element >= pivot] temp_array = [pivot] + longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
""" Author : Mehdi ALAOUI This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence. The problem is : Given an array, to find the longest and increasing sub-array in that given array and return it. Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output """ from __future__ import annotations def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive """ Some examples >>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) [10, 22, 33, 41, 60, 80] >>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9]) [1, 2, 3, 9] >>> longest_subsequence([9, 8, 7, 6, 5, 7]) [8] >>> longest_subsequence([1, 1, 1]) [1, 1, 1] >>> longest_subsequence([]) [] """ array_length = len(array) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else pivot = array[0] is_found = False i = 1 longest_subseq: list[int] = [] while not is_found and i < array_length: if array[i] < pivot: is_found = True temp_array = [element for element in array[i:] if element >= array[i]] temp_array = longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): longest_subseq = temp_array else: i += 1 temp_array = [element for element in array[1:] if element >= pivot] temp_array = [pivot] + longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,949
Flake8: Drop ignore of issue A003
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-02T18:01:55Z"
"2022-11-02T18:20:46Z"
598f6a26a14d815f5fd079f43787995b0f076c03
45b3383c3952f646e985972d1fcd772d3d9f5d3f
Flake8: Drop ignore of issue A003. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a type of divide and conquer algorithm which divides the search space into 3 parts and finds the target value based on the property of the array or list (usually monotonic property). Time Complexity : O(log3 N) Space Complexity : O(1) """ from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. precision = 10 # This is the linear search that will occur after the search space has become smaller. def lin_search(left: int, right: int, array: list[int], target: int) -> int: """Perform linear search in list. Returns -1 if element is not found. Parameters ---------- left : int left index bound. right : int right index bound. array : List[int] List of elements to be searched on target : int Element that is searched Returns ------- int index of element that is looked for. Examples -------- >>> lin_search(0, 4, [4, 5, 6, 7], 7) 3 >>> lin_search(0, 3, [4, 5, 6, 7], 7) -1 >>> lin_search(0, 2, [-18, 2], -18) 0 >>> lin_search(0, 1, [5], 5) 0 >>> lin_search(0, 3, ['a', 'c', 'd'], 'c') 1 >>> lin_search(0, 3, [.1, .4 , -.1], .1) 0 >>> lin_search(0, 3, [.1, .4 , -.1], -.1) 2 """ for i in range(left, right): if array[i] == target: return i return -1 def ite_ternary_search(array: list[int], target: int) -> int: """Iterative method of the ternary search algorithm. >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> ite_ternary_search(test_list, 3) -1 >>> ite_ternary_search(test_list, 13) 4 >>> ite_ternary_search([4, 5, 6, 7], 4) 0 >>> ite_ternary_search([4, 5, 6, 7], -10) -1 >>> ite_ternary_search([-18, 2], -18) 0 >>> ite_ternary_search([5], 5) 0 >>> ite_ternary_search(['a', 'c', 'd'], 'c') 1 >>> ite_ternary_search(['a', 'c', 'd'], 'f') -1 >>> ite_ternary_search([], 1) -1 >>> ite_ternary_search([.1, .4 , -.1], .1) 0 """ left = 0 right = len(array) while left <= right: if right - left < precision: return lin_search(left, right, array, target) one_third = (left + right) // 3 + 1 two_third = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: right = one_third - 1 elif array[two_third] < target: left = two_third + 1 else: left = one_third + 1 right = two_third - 1 else: return -1 def rec_ternary_search(left: int, right: int, array: list[int], target: int) -> int: """Recursive method of the ternary search algorithm. >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> rec_ternary_search(0, len(test_list), test_list, 3) -1 >>> rec_ternary_search(4, len(test_list), test_list, 42) 8 >>> rec_ternary_search(0, 2, [4, 5, 6, 7], 4) 0 >>> rec_ternary_search(0, 3, [4, 5, 6, 7], -10) -1 >>> rec_ternary_search(0, 1, [-18, 2], -18) 0 >>> rec_ternary_search(0, 1, [5], 5) 0 >>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'c') 1 >>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'f') -1 >>> rec_ternary_search(0, 0, [], 1) -1 >>> rec_ternary_search(0, 3, [.1, .4 , -.1], .1) 0 """ if left < right: if right - left < precision: return lin_search(left, right, array, target) one_third = (left + right) // 3 + 1 two_third = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(left, one_third - 1, array, target) elif array[two_third] < target: return rec_ternary_search(two_third + 1, right, array, target) else: return rec_ternary_search(one_third + 1, two_third - 1, array, target) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by comma:\n").strip() collection = [int(item.strip()) for item in user_input.split(",")] assert collection == sorted(collection), f"List must be ordered.\n{collection}." target = int(input("Enter the number to be found in the list:\n").strip()) result1 = ite_ternary_search(collection, target) result2 = rec_ternary_search(0, len(collection) - 1, collection, target) if result2 != -1: print(f"Iterative search: {target} found at positions: {result1}") print(f"Recursive search: {target} found at positions: {result2}") else: print("Not found")
""" This is a type of divide and conquer algorithm which divides the search space into 3 parts and finds the target value based on the property of the array or list (usually monotonic property). Time Complexity : O(log3 N) Space Complexity : O(1) """ from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. precision = 10 # This is the linear search that will occur after the search space has become smaller. def lin_search(left: int, right: int, array: list[int], target: int) -> int: """Perform linear search in list. Returns -1 if element is not found. Parameters ---------- left : int left index bound. right : int right index bound. array : List[int] List of elements to be searched on target : int Element that is searched Returns ------- int index of element that is looked for. Examples -------- >>> lin_search(0, 4, [4, 5, 6, 7], 7) 3 >>> lin_search(0, 3, [4, 5, 6, 7], 7) -1 >>> lin_search(0, 2, [-18, 2], -18) 0 >>> lin_search(0, 1, [5], 5) 0 >>> lin_search(0, 3, ['a', 'c', 'd'], 'c') 1 >>> lin_search(0, 3, [.1, .4 , -.1], .1) 0 >>> lin_search(0, 3, [.1, .4 , -.1], -.1) 2 """ for i in range(left, right): if array[i] == target: return i return -1 def ite_ternary_search(array: list[int], target: int) -> int: """Iterative method of the ternary search algorithm. >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> ite_ternary_search(test_list, 3) -1 >>> ite_ternary_search(test_list, 13) 4 >>> ite_ternary_search([4, 5, 6, 7], 4) 0 >>> ite_ternary_search([4, 5, 6, 7], -10) -1 >>> ite_ternary_search([-18, 2], -18) 0 >>> ite_ternary_search([5], 5) 0 >>> ite_ternary_search(['a', 'c', 'd'], 'c') 1 >>> ite_ternary_search(['a', 'c', 'd'], 'f') -1 >>> ite_ternary_search([], 1) -1 >>> ite_ternary_search([.1, .4 , -.1], .1) 0 """ left = 0 right = len(array) while left <= right: if right - left < precision: return lin_search(left, right, array, target) one_third = (left + right) // 3 + 1 two_third = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: right = one_third - 1 elif array[two_third] < target: left = two_third + 1 else: left = one_third + 1 right = two_third - 1 else: return -1 def rec_ternary_search(left: int, right: int, array: list[int], target: int) -> int: """Recursive method of the ternary search algorithm. >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> rec_ternary_search(0, len(test_list), test_list, 3) -1 >>> rec_ternary_search(4, len(test_list), test_list, 42) 8 >>> rec_ternary_search(0, 2, [4, 5, 6, 7], 4) 0 >>> rec_ternary_search(0, 3, [4, 5, 6, 7], -10) -1 >>> rec_ternary_search(0, 1, [-18, 2], -18) 0 >>> rec_ternary_search(0, 1, [5], 5) 0 >>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'c') 1 >>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'f') -1 >>> rec_ternary_search(0, 0, [], 1) -1 >>> rec_ternary_search(0, 3, [.1, .4 , -.1], .1) 0 """ if left < right: if right - left < precision: return lin_search(left, right, array, target) one_third = (left + right) // 3 + 1 two_third = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(left, one_third - 1, array, target) elif array[two_third] < target: return rec_ternary_search(two_third + 1, right, array, target) else: return rec_ternary_search(one_third + 1, two_third - 1, array, target) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by comma:\n").strip() collection = [int(item.strip()) for item in user_input.split(",")] assert collection == sorted(collection), f"List must be ordered.\n{collection}." target = int(input("Enter the number to be found in the list:\n").strip()) result1 = ite_ternary_search(collection, target) result2 = rec_ternary_search(0, len(collection) - 1, collection, target) if result2 != -1: print(f"Iterative search: {target} found at positions: {result1}") print(f"Recursive search: {target} found at positions: {result2}") else: print("Not found")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from collections.abc import Sequence def compare_string(string1: str, string2: str) -> str: """ >>> compare_string('0010','0110') '0_10' >>> compare_string('0110','1101') 'X' """ list1 = list(string1) list2 = list(string2) count = 0 for i in range(len(list1)): if list1[i] != list2[i]: count += 1 list1[i] = "_" if count > 1: return "X" else: return "".join(list1) def check(binary: list[str]) -> list[str]: """ >>> check(['0.00.01.5']) ['0.00.01.5'] """ pi = [] while True: check1 = ["$"] * len(binary) temp = [] for i in range(len(binary)): for j in range(i + 1, len(binary)): k = compare_string(binary[i], binary[j]) if k != "X": check1[i] = "*" check1[j] = "*" temp.append(k) for i in range(len(binary)): if check1[i] == "$": pi.append(binary[i]) if len(temp) == 0: return pi binary = list(set(temp)) def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]: """ >>> decimal_to_binary(3,[1.5]) ['0.00.01.5'] """ temp = [] for minterm in minterms: string = "" for _ in range(no_of_variable): string = str(minterm % 2) + string minterm //= 2 temp.append(string) return temp def is_for_table(string1: str, string2: str, count: int) -> bool: """ >>> is_for_table('__1','011',2) True >>> is_for_table('01_','001',1) False """ list1 = list(string1) list2 = list(string2) count_n = 0 for i in range(len(list1)): if list1[i] != list2[i]: count_n += 1 return count_n == count def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]: """ >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] """ temp = [] select = [0] * len(chart) for i in range(len(chart[0])): count = 0 rem = -1 for j in range(len(chart)): if chart[j][i] == 1: count += 1 rem = j if count == 1: select[rem] = 1 for i in range(len(select)): if select[i] == 1: for j in range(len(chart[0])): if chart[i][j] == 1: for k in range(len(chart)): chart[k][j] = 0 temp.append(prime_implicants[i]) while True: max_n = 0 rem = -1 count_n = 0 for i in range(len(chart)): count_n = chart[i].count(1) if count_n > max_n: max_n = count_n rem = i if max_n == 0: return temp temp.append(prime_implicants[rem]) for i in range(len(chart[0])): if chart[rem][i] == 1: for j in range(len(chart)): chart[j][i] = 0 def prime_implicant_chart( prime_implicants: list[str], binary: list[str] ) -> list[list[int]]: """ >>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5']) [[1]] """ chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))] for i in range(len(prime_implicants)): count = prime_implicants[i].count("_") for j in range(len(binary)): if is_for_table(prime_implicants[i], binary[j], count): chart[i][j] = 1 return chart def main() -> None: no_of_variable = int(input("Enter the no. of variables\n")) minterms = [ float(x) for x in input( "Enter the decimal representation of Minterms 'Spaces Separated'\n" ).split() ] binary = decimal_to_binary(no_of_variable, minterms) prime_implicants = check(binary) print("Prime Implicants are:") print(prime_implicants) chart = prime_implicant_chart(prime_implicants, binary) essential_prime_implicants = selection(chart, prime_implicants) print("Essential Prime Implicants are:") print(essential_prime_implicants) if __name__ == "__main__": import doctest doctest.testmod() main()
from __future__ import annotations from collections.abc import Sequence from typing import Literal def compare_string(string1: str, string2: str) -> str | Literal[False]: """ >>> compare_string('0010','0110') '0_10' >>> compare_string('0110','1101') False """ list1 = list(string1) list2 = list(string2) count = 0 for i in range(len(list1)): if list1[i] != list2[i]: count += 1 list1[i] = "_" if count > 1: return False else: return "".join(list1) def check(binary: list[str]) -> list[str]: """ >>> check(['0.00.01.5']) ['0.00.01.5'] """ pi = [] while True: check1 = ["$"] * len(binary) temp = [] for i in range(len(binary)): for j in range(i + 1, len(binary)): k = compare_string(binary[i], binary[j]) if k is False: check1[i] = "*" check1[j] = "*" temp.append("X") for i in range(len(binary)): if check1[i] == "$": pi.append(binary[i]) if len(temp) == 0: return pi binary = list(set(temp)) def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]: """ >>> decimal_to_binary(3,[1.5]) ['0.00.01.5'] """ temp = [] for minterm in minterms: string = "" for _ in range(no_of_variable): string = str(minterm % 2) + string minterm //= 2 temp.append(string) return temp def is_for_table(string1: str, string2: str, count: int) -> bool: """ >>> is_for_table('__1','011',2) True >>> is_for_table('01_','001',1) False """ list1 = list(string1) list2 = list(string2) count_n = 0 for i in range(len(list1)): if list1[i] != list2[i]: count_n += 1 return count_n == count def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]: """ >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] >>> selection([[1]],['0.00.01.5']) ['0.00.01.5'] """ temp = [] select = [0] * len(chart) for i in range(len(chart[0])): count = 0 rem = -1 for j in range(len(chart)): if chart[j][i] == 1: count += 1 rem = j if count == 1: select[rem] = 1 for i in range(len(select)): if select[i] == 1: for j in range(len(chart[0])): if chart[i][j] == 1: for k in range(len(chart)): chart[k][j] = 0 temp.append(prime_implicants[i]) while True: max_n = 0 rem = -1 count_n = 0 for i in range(len(chart)): count_n = chart[i].count(1) if count_n > max_n: max_n = count_n rem = i if max_n == 0: return temp temp.append(prime_implicants[rem]) for i in range(len(chart[0])): if chart[rem][i] == 1: for j in range(len(chart)): chart[j][i] = 0 def prime_implicant_chart( prime_implicants: list[str], binary: list[str] ) -> list[list[int]]: """ >>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5']) [[1]] """ chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))] for i in range(len(prime_implicants)): count = prime_implicants[i].count("_") for j in range(len(binary)): if is_for_table(prime_implicants[i], binary[j], count): chart[i][j] = 1 return chart def main() -> None: no_of_variable = int(input("Enter the no. of variables\n")) minterms = [ float(x) for x in input( "Enter the decimal representation of Minterms 'Spaces Separated'\n" ).split() ] binary = decimal_to_binary(no_of_variable, minterms) prime_implicants = check(binary) print("Prime Implicants are:") print(prime_implicants) chart = prime_implicant_chart(prime_implicants, binary) essential_prime_implicants = selection(chart, prime_implicants) print("Essential Prime Implicants are:") print(essential_prime_implicants) if __name__ == "__main__": import doctest doctest.testmod() main()
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations import random import string class ShuffledShiftCipher: """ This algorithm uses the Caesar Cipher algorithm but removes the option to use brute force to decrypt the message. The passcode is a random password from the selection buffer of 1. uppercase letters of the English alphabet 2. lowercase letters of the English alphabet 3. digits from 0 to 9 Using unique characters from the passcode, the normal list of characters, that can be allowed in the plaintext, is pivoted and shuffled. Refer to docstring of __make_key_list() to learn more about the shuffling. Then, using the passcode, a number is calculated which is used to encrypt the plaintext message with the normal shift cipher method, only in this case, the reference, to look back at while decrypting, is shuffled. Each cipher object can possess an optional argument as passcode, without which a new passcode is generated for that object automatically. cip1 = ShuffledShiftCipher('d4usr9TWxw9wMD') cip2 = ShuffledShiftCipher() """ def __init__(self, passcode: str | None = None) -> None: """ Initializes a cipher object with a passcode as it's entity Note: No new passcode is generated if user provides a passcode while creating the object """ self.__passcode = passcode or self.__passcode_creator() self.__key_list = self.__make_key_list() self.__shift_key = self.__make_shift_key() def __str__(self) -> str: """ :return: passcode of the cipher object """ return "Passcode is: " + "".join(self.__passcode) def __neg_pos(self, iterlist: list[int]) -> list[int]: """ Mutates the list by changing the sign of each alternate element :param iterlist: takes a list iterable :return: the mutated list """ for i in range(1, len(iterlist), 2): iterlist[i] *= -1 return iterlist def __passcode_creator(self) -> list[str]: """ Creates a random password from the selection buffer of 1. uppercase letters of the English alphabet 2. lowercase letters of the English alphabet 3. digits from 0 to 9 :rtype: list :return: a password of a random length between 10 to 20 """ choices = string.ascii_letters + string.digits password = [random.choice(choices) for _ in range(random.randint(10, 20))] return password def __make_key_list(self) -> list[str]: """ Shuffles the ordered character choices by pivoting at breakpoints Breakpoints are the set of characters in the passcode eg: if, ABCDEFGHIJKLMNOPQRSTUVWXYZ are the possible characters and CAMERA is the passcode then, breakpoints = [A,C,E,M,R] # sorted set of characters from passcode shuffled parts: [A,CB,ED,MLKJIHGF,RQPON,ZYXWVUTS] shuffled __key_list : ACBEDMLKJIHGFRQPONZYXWVUTS Shuffling only 26 letters of the english alphabet can generate 26! combinations for the shuffled list. In the program we consider, a set of 97 characters (including letters, digits, punctuation and whitespaces), thereby creating a possibility of 97! combinations (which is a 152 digit number in itself), thus diminishing the possibility of a brute force approach. Moreover, shift keys even introduce a multiple of 26 for a brute force approach for each of the already 97! combinations. """ # key_list_options contain nearly all printable except few elements from # string.whitespace key_list_options = ( string.ascii_letters + string.digits + string.punctuation + " \t\n" ) keys_l = [] # creates points known as breakpoints to break the key_list_options at those # points and pivot each substring breakpoints = sorted(set(self.__passcode)) temp_list: list[str] = [] # algorithm for creating a new shuffled list, keys_l, out of key_list_options for i in key_list_options: temp_list.extend(i) # checking breakpoints at which to pivot temporary sublist and add it into # keys_l if i in breakpoints or i == key_list_options[-1]: keys_l.extend(temp_list[::-1]) temp_list.clear() # returning a shuffled keys_l to prevent brute force guessing of shift key return keys_l def __make_shift_key(self) -> int: """ sum() of the mutated list of ascii values of all characters where the mutated list is the one returned by __neg_pos() """ num = sum(self.__neg_pos([ord(x) for x in self.__passcode])) return num if num > 0 else len(self.__passcode) def decrypt(self, encoded_message: str) -> str: """ Performs shifting of the encoded_message w.r.t. the shuffled __key_list to create the decoded_message >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44') >>> ssc.decrypt("d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#") 'Hello, this is a modified Caesar cipher' """ decoded_message = "" # decoding shift like Caesar cipher algorithm implementing negative shift or # reverse shift or left shift for i in encoded_message: position = self.__key_list.index(i) decoded_message += self.__key_list[ (position - self.__shift_key) % -len(self.__key_list) ] return decoded_message def encrypt(self, plaintext: str) -> str: """ Performs shifting of the plaintext w.r.t. the shuffled __key_list to create the encoded_message >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44') >>> ssc.encrypt('Hello, this is a modified Caesar cipher') "d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#" """ encoded_message = "" # encoding shift like Caesar cipher algorithm implementing positive shift or # forward shift or right shift for i in plaintext: position = self.__key_list.index(i) encoded_message += self.__key_list[ (position + self.__shift_key) % len(self.__key_list) ] return encoded_message def test_end_to_end(msg: str = "Hello, this is a modified Caesar cipher") -> str: """ >>> test_end_to_end() 'Hello, this is a modified Caesar cipher' """ cip1 = ShuffledShiftCipher() return cip1.decrypt(cip1.encrypt(msg)) if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations import random import string class ShuffledShiftCipher: """ This algorithm uses the Caesar Cipher algorithm but removes the option to use brute force to decrypt the message. The passcode is a random password from the selection buffer of 1. uppercase letters of the English alphabet 2. lowercase letters of the English alphabet 3. digits from 0 to 9 Using unique characters from the passcode, the normal list of characters, that can be allowed in the plaintext, is pivoted and shuffled. Refer to docstring of __make_key_list() to learn more about the shuffling. Then, using the passcode, a number is calculated which is used to encrypt the plaintext message with the normal shift cipher method, only in this case, the reference, to look back at while decrypting, is shuffled. Each cipher object can possess an optional argument as passcode, without which a new passcode is generated for that object automatically. cip1 = ShuffledShiftCipher('d4usr9TWxw9wMD') cip2 = ShuffledShiftCipher() """ def __init__(self, passcode: str | None = None) -> None: """ Initializes a cipher object with a passcode as it's entity Note: No new passcode is generated if user provides a passcode while creating the object """ self.__passcode = passcode or self.__passcode_creator() self.__key_list = self.__make_key_list() self.__shift_key = self.__make_shift_key() def __str__(self) -> str: """ :return: passcode of the cipher object """ return "".join(self.__passcode) def __neg_pos(self, iterlist: list[int]) -> list[int]: """ Mutates the list by changing the sign of each alternate element :param iterlist: takes a list iterable :return: the mutated list """ for i in range(1, len(iterlist), 2): iterlist[i] *= -1 return iterlist def __passcode_creator(self) -> list[str]: """ Creates a random password from the selection buffer of 1. uppercase letters of the English alphabet 2. lowercase letters of the English alphabet 3. digits from 0 to 9 :rtype: list :return: a password of a random length between 10 to 20 """ choices = string.ascii_letters + string.digits password = [random.choice(choices) for _ in range(random.randint(10, 20))] return password def __make_key_list(self) -> list[str]: """ Shuffles the ordered character choices by pivoting at breakpoints Breakpoints are the set of characters in the passcode eg: if, ABCDEFGHIJKLMNOPQRSTUVWXYZ are the possible characters and CAMERA is the passcode then, breakpoints = [A,C,E,M,R] # sorted set of characters from passcode shuffled parts: [A,CB,ED,MLKJIHGF,RQPON,ZYXWVUTS] shuffled __key_list : ACBEDMLKJIHGFRQPONZYXWVUTS Shuffling only 26 letters of the english alphabet can generate 26! combinations for the shuffled list. In the program we consider, a set of 97 characters (including letters, digits, punctuation and whitespaces), thereby creating a possibility of 97! combinations (which is a 152 digit number in itself), thus diminishing the possibility of a brute force approach. Moreover, shift keys even introduce a multiple of 26 for a brute force approach for each of the already 97! combinations. """ # key_list_options contain nearly all printable except few elements from # string.whitespace key_list_options = ( string.ascii_letters + string.digits + string.punctuation + " \t\n" ) keys_l = [] # creates points known as breakpoints to break the key_list_options at those # points and pivot each substring breakpoints = sorted(set(self.__passcode)) temp_list: list[str] = [] # algorithm for creating a new shuffled list, keys_l, out of key_list_options for i in key_list_options: temp_list.extend(i) # checking breakpoints at which to pivot temporary sublist and add it into # keys_l if i in breakpoints or i == key_list_options[-1]: keys_l.extend(temp_list[::-1]) temp_list.clear() # returning a shuffled keys_l to prevent brute force guessing of shift key return keys_l def __make_shift_key(self) -> int: """ sum() of the mutated list of ascii values of all characters where the mutated list is the one returned by __neg_pos() """ num = sum(self.__neg_pos([ord(x) for x in self.__passcode])) return num if num > 0 else len(self.__passcode) def decrypt(self, encoded_message: str) -> str: """ Performs shifting of the encoded_message w.r.t. the shuffled __key_list to create the decoded_message >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44') >>> ssc.decrypt("d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#") 'Hello, this is a modified Caesar cipher' """ decoded_message = "" # decoding shift like Caesar cipher algorithm implementing negative shift or # reverse shift or left shift for i in encoded_message: position = self.__key_list.index(i) decoded_message += self.__key_list[ (position - self.__shift_key) % -len(self.__key_list) ] return decoded_message def encrypt(self, plaintext: str) -> str: """ Performs shifting of the plaintext w.r.t. the shuffled __key_list to create the encoded_message >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44') >>> ssc.encrypt('Hello, this is a modified Caesar cipher') "d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#" """ encoded_message = "" # encoding shift like Caesar cipher algorithm implementing positive shift or # forward shift or right shift for i in plaintext: position = self.__key_list.index(i) encoded_message += self.__key_list[ (position + self.__shift_key) % len(self.__key_list) ] return encoded_message def test_end_to_end(msg: str = "Hello, this is a modified Caesar cipher") -> str: """ >>> test_end_to_end() 'Hello, this is a modified Caesar cipher' """ cip1 = ShuffledShiftCipher() return cip1.decrypt(cip1.encrypt(msg)) if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import cv2 import numpy as np """ Harris Corner Detector https://en.wikipedia.org/wiki/Harris_Corner_Detector """ class HarrisCorner: def __init__(self, k: float, window_size: int): """ k : is an empirically determined constant in [0.04,0.06] window_size : neighbourhoods considered """ if k in (0.04, 0.06): self.k = k self.window_size = window_size else: raise ValueError("invalid k value") def __str__(self) -> str: return f"Harris Corner detection with k : {self.k}" def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]: """ Returns the image with corners identified img_path : path of the image output : list of the corner positions, image """ img = cv2.imread(img_path, 0) h, w = img.shape corner_list: list[list[int]] = [] color_img = img.copy() color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB) dy, dx = np.gradient(img) ixx = dx**2 iyy = dy**2 ixy = dx * dy k = 0.04 offset = self.window_size // 2 for y in range(offset, h - offset): for x in range(offset, w - offset): wxx = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wyy = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wxy = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() det = (wxx * wyy) - (wxy**2) trace = wxx + wyy r = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r]) color_img.itemset((y, x, 0), 0) color_img.itemset((y, x, 1), 0) color_img.itemset((y, x, 2), 255) return color_img, corner_list if __name__ == "__main__": edge_detect = HarrisCorner(0.04, 3) color_img, _ = edge_detect.detect("path_to_image") cv2.imwrite("detect.png", color_img)
import cv2 import numpy as np """ Harris Corner Detector https://en.wikipedia.org/wiki/Harris_Corner_Detector """ class HarrisCorner: def __init__(self, k: float, window_size: int): """ k : is an empirically determined constant in [0.04,0.06] window_size : neighbourhoods considered """ if k in (0.04, 0.06): self.k = k self.window_size = window_size else: raise ValueError("invalid k value") def __str__(self) -> str: return str(self.k) def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]: """ Returns the image with corners identified img_path : path of the image output : list of the corner positions, image """ img = cv2.imread(img_path, 0) h, w = img.shape corner_list: list[list[int]] = [] color_img = img.copy() color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB) dy, dx = np.gradient(img) ixx = dx**2 iyy = dy**2 ixy = dx * dy k = 0.04 offset = self.window_size // 2 for y in range(offset, h - offset): for x in range(offset, w - offset): wxx = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wyy = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wxy = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() det = (wxx * wyy) - (wxy**2) trace = wxx + wyy r = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r]) color_img.itemset((y, x, 0), 0) color_img.itemset((y, x, 1), 0) color_img.itemset((y, x, 2), 255) return color_img, corner_list if __name__ == "__main__": edge_detect = HarrisCorner(0.04, 3) color_img, _ = edge_detect.detect("path_to_image") cv2.imwrite("detect.png", color_img)
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another 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 __repr__(self): return f"SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})" class SegmentTree: """ >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE (SegmentTreeNode(start=0, end=4, val=15), SegmentTreeNode(start=0, end=2, val=8), SegmentTreeNode(start=3, end=4, val=7), SegmentTreeNode(start=0, end=1, val=3), SegmentTreeNode(start=2, end=2, val=5), SegmentTreeNode(start=3, end=3, val=3), SegmentTreeNode(start=4, end=4, val=4), SegmentTreeNode(start=0, end=0, val=2), SegmentTreeNode(start=1, end=1, val=1)) >>> >>> num_arr.update(1, 5) >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE (SegmentTreeNode(start=0, end=4, val=19), SegmentTreeNode(start=0, end=2, val=12), SegmentTreeNode(start=3, end=4, val=7), SegmentTreeNode(start=0, end=1, val=7), SegmentTreeNode(start=2, end=2, val=5), SegmentTreeNode(start=3, end=3, val=3), SegmentTreeNode(start=4, end=4, val=4), SegmentTreeNode(start=0, end=0, val=2), SegmentTreeNode(start=1, end=1, val=5)) >>> >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> >>> max_arr = SegmentTree([2, 1, 5, 3, 4], max) >>> for node in max_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=5) SegmentTreeNode(start=0, end=2, val=5) SegmentTreeNode(start=3, end=4, val=4) SegmentTreeNode(start=0, end=1, val=2) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=1) >>> >>> max_arr.update(1, 5) >>> for node in max_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=5) SegmentTreeNode(start=0, end=2, val=5) SegmentTreeNode(start=3, end=4, val=4) SegmentTreeNode(start=0, end=1, val=5) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=5) >>> >>> max_arr.query_range(3, 4) 4 >>> max_arr.query_range(2, 2) 5 >>> max_arr.query_range(1, 3) 5 >>> >>> min_arr = SegmentTree([2, 1, 5, 3, 4], min) >>> for node in min_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=1) SegmentTreeNode(start=0, end=2, val=1) SegmentTreeNode(start=3, end=4, val=3) SegmentTreeNode(start=0, end=1, val=1) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=1) >>> >>> min_arr.update(1, 5) >>> for node in min_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=2) SegmentTreeNode(start=0, end=2, val=2) SegmentTreeNode(start=3, end=4, val=3) SegmentTreeNode(start=0, end=1, val=2) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=5) >>> >>> min_arr.query_range(3, 4) 3 >>> min_arr.query_range(2, 2) 5 >>> min_arr.query_range(1, 3) 3 >>> """ def __init__(self, collection: Sequence, function): self.collection = collection self.fn = function if self.collection: self.root = self._build_tree(0, len(collection) - 1) def update(self, i, val): """ Update an element in log(N) time :param i: position to be update :param val: new value >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(1, 3) 13 """ self._update_tree(self.root, i, val) def query_range(self, i, j): """ Get range query value in log(N) time :param i: left element index :param j: right element index :return: element combined in the range [i, j] >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> """ return self._query_range(self.root, i, j) def _build_tree(self, start, end): if start == end: return SegmentTreeNode(start, end, self.collection[start]) mid = (start + end) // 2 left = self._build_tree(start, mid) right = self._build_tree(mid + 1, end) return SegmentTreeNode(start, end, self.fn(left.val, right.val), left, right) def _update_tree(self, node, i, val): if node.start == i and node.end == i: node.val = val return if i <= node.mid: self._update_tree(node.left, i, val) else: self._update_tree(node.right, i, val) node.val = self.fn(node.left.val, node.right.val) def _query_range(self, node, i, j): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left, i, j) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left, i, node.mid), self._query_range(node.right, node.mid + 1, j), ) else: # range in right child tree return self._query_range(node.right, i, j) def traverse(self): if self.root is not None: queue = Queue() queue.put(self.root) while not queue.empty(): node = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 50) arr = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Wavelet tree is a data-structure designed to efficiently answer various range queries for arrays. Wavelets trees are different from other binary trees in the sense that the nodes are split based on the actual values of the elements and not on indices, such as the with segment trees or fenwick trees. You can read more about them here: 1. https://users.dcc.uchile.cl/~jperez/papers/ioiconf16.pdf 2. https://www.youtube.com/watch?v=4aSv9PcecDw&t=811s 3. https://www.youtube.com/watch?v=CybAgVF-MMc&t=1178s """ from __future__ import annotations test_array = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7] class Node: def __init__(self, length: int) -> None: self.minn: int = -1 self.maxx: int = -1 self.map_left: list[int] = [-1] * length self.left: Node | None = None self.right: Node | None = None def __repr__(self) -> str: """ >>> node = Node(length=27) >>> repr(node) 'min_value: -1, max_value: -1' >>> repr(node) == str(node) True """ return f"min_value: {self.minn}, max_value: {self.maxx}" def build_tree(arr: list[int]) -> Node | None: """ Builds the tree for arr and returns the root of the constructed tree >>> build_tree(test_array) min_value: 0, max_value: 9 """ root = Node(len(arr)) root.minn, root.maxx = min(arr), max(arr) # Leaf node case where the node contains only one unique value if root.minn == root.maxx: return root """ Take the mean of min and max element of arr as the pivot and partition arr into left_arr and right_arr with all elements <= pivot in the left_arr and the rest in right_arr, maintaining the order of the elements, then recursively build trees for left_arr and right_arr """ pivot = (root.minn + root.maxx) // 2 left_arr: list[int] = [] right_arr: list[int] = [] for index, num in enumerate(arr): if num <= pivot: left_arr.append(num) else: right_arr.append(num) root.map_left[index] = len(left_arr) root.left = build_tree(left_arr) root.right = build_tree(right_arr) return root def rank_till_index(node: Node | None, num: int, index: int) -> int: """ Returns the number of occurrences of num in interval [0, index] in the list >>> root = build_tree(test_array) >>> rank_till_index(root, 6, 6) 1 >>> rank_till_index(root, 2, 0) 1 >>> rank_till_index(root, 1, 10) 2 >>> rank_till_index(root, 17, 7) 0 >>> rank_till_index(root, 0, 9) 1 """ if index < 0 or node is None: return 0 # Leaf node cases if node.minn == node.maxx: return index + 1 if node.minn == num else 0 pivot = (node.minn + node.maxx) // 2 if num <= pivot: # go the left subtree and map index to the left subtree return rank_till_index(node.left, num, node.map_left[index] - 1) else: # go to the right subtree and map index to the right subtree return rank_till_index(node.right, num, index - node.map_left[index]) def rank(node: Node | None, num: int, start: int, end: int) -> int: """ Returns the number of occurrences of num in interval [start, end] in the list >>> root = build_tree(test_array) >>> rank(root, 6, 3, 13) 2 >>> rank(root, 2, 0, 19) 4 >>> rank(root, 9, 2 ,2) 0 >>> rank(root, 0, 5, 10) 2 """ if start > end: return 0 rank_till_end = rank_till_index(node, num, end) rank_before_start = rank_till_index(node, num, start - 1) return rank_till_end - rank_before_start def quantile(node: Node | None, index: int, start: int, end: int) -> int: """ Returns the index'th smallest element in interval [start, end] in the list index is 0-indexed >>> root = build_tree(test_array) >>> quantile(root, 2, 2, 5) 5 >>> quantile(root, 5, 2, 13) 4 >>> quantile(root, 0, 6, 6) 8 >>> quantile(root, 4, 2, 5) -1 """ if index > (end - start) or start > end or node is None: return -1 # Leaf node case if node.minn == node.maxx: return node.minn # Number of elements in the left subtree in interval [start, end] num_elements_in_left_tree = node.map_left[end] - ( node.map_left[start - 1] if start else 0 ) if num_elements_in_left_tree > index: return quantile( node.left, index, (node.map_left[start - 1] if start else 0), node.map_left[end] - 1, ) else: return quantile( node.right, index - num_elements_in_left_tree, start - (node.map_left[start - 1] if start else 0), end - node.map_left[end], ) def range_counting( node: Node | None, start: int, end: int, start_num: int, end_num: int ) -> int: """ Returns the number of elements in range [start_num, end_num] in interval [start, end] in the list >>> root = build_tree(test_array) >>> range_counting(root, 1, 10, 3, 7) 3 >>> range_counting(root, 2, 2, 1, 4) 1 >>> range_counting(root, 0, 19, 0, 100) 20 >>> range_counting(root, 1, 0, 1, 100) 0 >>> range_counting(root, 0, 17, 100, 1) 0 """ if ( start > end or node is None or start_num > end_num or node.minn > end_num or node.maxx < start_num ): return 0 if start_num <= node.minn and node.maxx <= end_num: return end - start + 1 left = range_counting( node.left, (node.map_left[start - 1] if start else 0), node.map_left[end] - 1, start_num, end_num, ) right = range_counting( node.right, start - (node.map_left[start - 1] if start else 0), end - node.map_left[end], start_num, end_num, ) return left + right if __name__ == "__main__": import doctest doctest.testmod()
""" Wavelet tree is a data-structure designed to efficiently answer various range queries for arrays. Wavelets trees are different from other binary trees in the sense that the nodes are split based on the actual values of the elements and not on indices, such as the with segment trees or fenwick trees. You can read more about them here: 1. https://users.dcc.uchile.cl/~jperez/papers/ioiconf16.pdf 2. https://www.youtube.com/watch?v=4aSv9PcecDw&t=811s 3. https://www.youtube.com/watch?v=CybAgVF-MMc&t=1178s """ from __future__ import annotations test_array = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7] class Node: def __init__(self, length: int) -> None: self.minn: int = -1 self.maxx: int = -1 self.map_left: list[int] = [-1] * length self.left: Node | None = None self.right: Node | None = None def __repr__(self) -> str: """ >>> node = Node(length=27) >>> repr(node) 'Node(min_value=-1 max_value=-1)' >>> repr(node) == str(node) True """ return f"Node(min_value={self.minn} max_value={self.maxx})" def build_tree(arr: list[int]) -> Node | None: """ Builds the tree for arr and returns the root of the constructed tree >>> build_tree(test_array) Node(min_value=0 max_value=9) """ root = Node(len(arr)) root.minn, root.maxx = min(arr), max(arr) # Leaf node case where the node contains only one unique value if root.minn == root.maxx: return root """ Take the mean of min and max element of arr as the pivot and partition arr into left_arr and right_arr with all elements <= pivot in the left_arr and the rest in right_arr, maintaining the order of the elements, then recursively build trees for left_arr and right_arr """ pivot = (root.minn + root.maxx) // 2 left_arr: list[int] = [] right_arr: list[int] = [] for index, num in enumerate(arr): if num <= pivot: left_arr.append(num) else: right_arr.append(num) root.map_left[index] = len(left_arr) root.left = build_tree(left_arr) root.right = build_tree(right_arr) return root def rank_till_index(node: Node | None, num: int, index: int) -> int: """ Returns the number of occurrences of num in interval [0, index] in the list >>> root = build_tree(test_array) >>> rank_till_index(root, 6, 6) 1 >>> rank_till_index(root, 2, 0) 1 >>> rank_till_index(root, 1, 10) 2 >>> rank_till_index(root, 17, 7) 0 >>> rank_till_index(root, 0, 9) 1 """ if index < 0 or node is None: return 0 # Leaf node cases if node.minn == node.maxx: return index + 1 if node.minn == num else 0 pivot = (node.minn + node.maxx) // 2 if num <= pivot: # go the left subtree and map index to the left subtree return rank_till_index(node.left, num, node.map_left[index] - 1) else: # go to the right subtree and map index to the right subtree return rank_till_index(node.right, num, index - node.map_left[index]) def rank(node: Node | None, num: int, start: int, end: int) -> int: """ Returns the number of occurrences of num in interval [start, end] in the list >>> root = build_tree(test_array) >>> rank(root, 6, 3, 13) 2 >>> rank(root, 2, 0, 19) 4 >>> rank(root, 9, 2 ,2) 0 >>> rank(root, 0, 5, 10) 2 """ if start > end: return 0 rank_till_end = rank_till_index(node, num, end) rank_before_start = rank_till_index(node, num, start - 1) return rank_till_end - rank_before_start def quantile(node: Node | None, index: int, start: int, end: int) -> int: """ Returns the index'th smallest element in interval [start, end] in the list index is 0-indexed >>> root = build_tree(test_array) >>> quantile(root, 2, 2, 5) 5 >>> quantile(root, 5, 2, 13) 4 >>> quantile(root, 0, 6, 6) 8 >>> quantile(root, 4, 2, 5) -1 """ if index > (end - start) or start > end or node is None: return -1 # Leaf node case if node.minn == node.maxx: return node.minn # Number of elements in the left subtree in interval [start, end] num_elements_in_left_tree = node.map_left[end] - ( node.map_left[start - 1] if start else 0 ) if num_elements_in_left_tree > index: return quantile( node.left, index, (node.map_left[start - 1] if start else 0), node.map_left[end] - 1, ) else: return quantile( node.right, index - num_elements_in_left_tree, start - (node.map_left[start - 1] if start else 0), end - node.map_left[end], ) def range_counting( node: Node | None, start: int, end: int, start_num: int, end_num: int ) -> int: """ Returns the number of elements in range [start_num, end_num] in interval [start, end] in the list >>> root = build_tree(test_array) >>> range_counting(root, 1, 10, 3, 7) 3 >>> range_counting(root, 2, 2, 1, 4) 1 >>> range_counting(root, 0, 19, 0, 100) 20 >>> range_counting(root, 1, 0, 1, 100) 0 >>> range_counting(root, 0, 17, 100, 1) 0 """ if ( start > end or node is None or start_num > end_num or node.minn > end_num or node.maxx < start_num ): return 0 if start_num <= node.minn and node.maxx <= end_num: return end - start + 1 left = range_counting( node.left, (node.map_left[start - 1] if start else 0), node.map_left[end] - 1, start_num, end_num, ) right = range_counting( node.right, start - (node.map_left[start - 1] if start else 0), end - node.map_left[end], start_num, end_num, ) return left + right if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another 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/Doubly_linked_list """ class Node: def __init__(self, data): self.data = data self.previous = None self.next = None def __str__(self): return f"{self.data}" class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def __iter__(self): """ >>> linked_list = DoublyLinkedList() >>> linked_list.insert_at_head('b') >>> linked_list.insert_at_head('a') >>> linked_list.insert_at_tail('c') >>> tuple(linked_list) ('a', 'b', 'c') """ node = self.head while node: yield node.data node = node.next def __str__(self): """ >>> linked_list = DoublyLinkedList() >>> linked_list.insert_at_tail('a') >>> linked_list.insert_at_tail('b') >>> linked_list.insert_at_tail('c') >>> str(linked_list) 'a->b->c' """ return "->".join([str(item) for item in self]) def __len__(self): """ >>> linked_list = DoublyLinkedList() >>> for i in range(0, 5): ... linked_list.insert_at_nth(i, i + 1) >>> len(linked_list) == 5 True """ return len(tuple(iter(self))) def insert_at_head(self, data): self.insert_at_nth(0, data) def insert_at_tail(self, data): self.insert_at_nth(len(self), data) def insert_at_nth(self, index: int, data): """ >>> linked_list = DoublyLinkedList() >>> linked_list.insert_at_nth(-1, 666) Traceback (most recent call last): .... IndexError: list index out of range >>> linked_list.insert_at_nth(1, 666) Traceback (most recent call last): .... IndexError: list index out of range >>> linked_list.insert_at_nth(0, 2) >>> linked_list.insert_at_nth(0, 1) >>> linked_list.insert_at_nth(2, 4) >>> linked_list.insert_at_nth(2, 3) >>> str(linked_list) '1->2->3->4' >>> linked_list.insert_at_nth(5, 5) Traceback (most recent call last): .... IndexError: list index out of range """ if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = self.tail = new_node elif index == 0: self.head.previous = new_node new_node.next = self.head self.head = new_node elif index == len(self): self.tail.next = new_node new_node.previous = self.tail self.tail = new_node else: temp = self.head for _ in range(0, index): temp = temp.next temp.previous.next = new_node new_node.previous = temp.previous new_node.next = temp temp.previous = new_node def delete_head(self): return self.delete_at_nth(0) def delete_tail(self): return self.delete_at_nth(len(self) - 1) def delete_at_nth(self, index: int): """ >>> linked_list = DoublyLinkedList() >>> linked_list.delete_at_nth(0) Traceback (most recent call last): .... IndexError: list index out of range >>> for i in range(0, 5): ... linked_list.insert_at_nth(i, i + 1) >>> linked_list.delete_at_nth(0) == 1 True >>> linked_list.delete_at_nth(3) == 5 True >>> linked_list.delete_at_nth(1) == 3 True >>> str(linked_list) '2->4' >>> linked_list.delete_at_nth(2) Traceback (most recent call last): .... IndexError: list index out of range """ if not 0 <= index <= len(self) - 1: raise IndexError("list index out of range") delete_node = self.head # default first node if len(self) == 1: self.head = self.tail = None elif index == 0: self.head = self.head.next self.head.previous = None elif index == len(self) - 1: delete_node = self.tail self.tail = self.tail.previous self.tail.next = None else: temp = self.head for _ in range(0, index): temp = temp.next delete_node = temp temp.next.previous = temp.previous temp.previous.next = temp.next return delete_node.data def delete(self, data) -> str: current = self.head while current.data != data: # Find the position to delete if current.next: current = current.next else: # We have reached the end an no value matches return "No data matching given value" if current == self.head: self.delete_head() elif current == self.tail: self.delete_tail() else: # Before: 1 <--> 2(current) <--> 3 current.previous.next = current.next # 1 --> 3 current.next.previous = current.previous # 1 <--> 3 return data def is_empty(self): """ >>> linked_list = DoublyLinkedList() >>> linked_list.is_empty() True >>> linked_list.insert_at_tail(1) >>> linked_list.is_empty() False """ return len(self) == 0 def test_doubly_linked_list() -> None: """ >>> test_doubly_linked_list() """ linked_list = DoublyLinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(linked_list) == i linked_list.insert_at_nth(i, i + 1) assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) linked_list.insert_at_head(0) linked_list.insert_at_tail(11) assert str(linked_list) == "->".join(str(i) for i in range(0, 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_at_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) if __name__ == "__main__": from doctest import testmod testmod()
""" https://en.wikipedia.org/wiki/Doubly_linked_list """ class Node: def __init__(self, data): self.data = data self.previous = None self.next = None def __str__(self): return f"{self.data}" class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def __iter__(self): """ >>> linked_list = DoublyLinkedList() >>> linked_list.insert_at_head('b') >>> linked_list.insert_at_head('a') >>> linked_list.insert_at_tail('c') >>> tuple(linked_list) ('a', 'b', 'c') """ node = self.head while node: yield node.data node = node.next def __str__(self): """ >>> linked_list = DoublyLinkedList() >>> linked_list.insert_at_tail('a') >>> linked_list.insert_at_tail('b') >>> linked_list.insert_at_tail('c') >>> str(linked_list) 'a->b->c' """ return "->".join([str(item) for item in self]) def __len__(self): """ >>> linked_list = DoublyLinkedList() >>> for i in range(0, 5): ... linked_list.insert_at_nth(i, i + 1) >>> len(linked_list) == 5 True """ return len(tuple(iter(self))) def insert_at_head(self, data): self.insert_at_nth(0, data) def insert_at_tail(self, data): self.insert_at_nth(len(self), data) def insert_at_nth(self, index: int, data): """ >>> linked_list = DoublyLinkedList() >>> linked_list.insert_at_nth(-1, 666) Traceback (most recent call last): .... IndexError: list index out of range >>> linked_list.insert_at_nth(1, 666) Traceback (most recent call last): .... IndexError: list index out of range >>> linked_list.insert_at_nth(0, 2) >>> linked_list.insert_at_nth(0, 1) >>> linked_list.insert_at_nth(2, 4) >>> linked_list.insert_at_nth(2, 3) >>> str(linked_list) '1->2->3->4' >>> linked_list.insert_at_nth(5, 5) Traceback (most recent call last): .... IndexError: list index out of range """ if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = self.tail = new_node elif index == 0: self.head.previous = new_node new_node.next = self.head self.head = new_node elif index == len(self): self.tail.next = new_node new_node.previous = self.tail self.tail = new_node else: temp = self.head for _ in range(0, index): temp = temp.next temp.previous.next = new_node new_node.previous = temp.previous new_node.next = temp temp.previous = new_node def delete_head(self): return self.delete_at_nth(0) def delete_tail(self): return self.delete_at_nth(len(self) - 1) def delete_at_nth(self, index: int): """ >>> linked_list = DoublyLinkedList() >>> linked_list.delete_at_nth(0) Traceback (most recent call last): .... IndexError: list index out of range >>> for i in range(0, 5): ... linked_list.insert_at_nth(i, i + 1) >>> linked_list.delete_at_nth(0) == 1 True >>> linked_list.delete_at_nth(3) == 5 True >>> linked_list.delete_at_nth(1) == 3 True >>> str(linked_list) '2->4' >>> linked_list.delete_at_nth(2) Traceback (most recent call last): .... IndexError: list index out of range """ if not 0 <= index <= len(self) - 1: raise IndexError("list index out of range") delete_node = self.head # default first node if len(self) == 1: self.head = self.tail = None elif index == 0: self.head = self.head.next self.head.previous = None elif index == len(self) - 1: delete_node = self.tail self.tail = self.tail.previous self.tail.next = None else: temp = self.head for _ in range(0, index): temp = temp.next delete_node = temp temp.next.previous = temp.previous temp.previous.next = temp.next return delete_node.data def delete(self, data) -> str: current = self.head while current.data != data: # Find the position to delete if current.next: current = current.next else: # We have reached the end an no value matches raise ValueError("No data matching given value") if current == self.head: self.delete_head() elif current == self.tail: self.delete_tail() else: # Before: 1 <--> 2(current) <--> 3 current.previous.next = current.next # 1 --> 3 current.next.previous = current.previous # 1 <--> 3 return data def is_empty(self): """ >>> linked_list = DoublyLinkedList() >>> linked_list.is_empty() True >>> linked_list.insert_at_tail(1) >>> linked_list.is_empty() False """ return len(self) == 0 def test_doubly_linked_list() -> None: """ >>> test_doubly_linked_list() """ linked_list = DoublyLinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError() # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(linked_list) == i linked_list.insert_at_nth(i, i + 1) assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) linked_list.insert_at_head(0) linked_list.insert_at_tail(11) assert str(linked_list) == "->".join(str(i) for i in range(0, 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_at_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) if __name__ == "__main__": from doctest import testmod testmod()
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of double ended queue. """ from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from typing import Any class Deque: """ Deque data structure. Operations ---------- append(val: Any) -> None appendleft(val: Any) -> None extend(iterable: Iterable) -> None extendleft(iterable: Iterable) -> None pop() -> Any popleft() -> Any Observers --------- is_empty() -> bool Attributes ---------- _front: _Node front of the deque a.k.a. the first element _back: _Node back of the element a.k.a. the last element _len: int the number of nodes """ __slots__ = ["_front", "_back", "_len"] @dataclass class _Node: """ Representation of a node. Contains a value and a pointer to the next node as well as to the previous one. """ val: Any = None next_node: Deque._Node | None = None prev_node: Deque._Node | None = None class _Iterator: """ Helper class for iteration. Will be used to implement iteration. Attributes ---------- _cur: _Node the current node of the iteration. """ __slots__ = ["_cur"] def __init__(self, cur: Deque._Node | None) -> None: self._cur = cur def __iter__(self) -> Deque._Iterator: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) """ return self def __next__(self) -> Any: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) >>> next(iterator) 1 >>> next(iterator) 2 >>> next(iterator) 3 """ if self._cur is None: # finished iterating raise StopIteration val = self._cur.val self._cur = self._cur.next_node return val def __init__(self, iterable: Iterable[Any] | None = None) -> None: self._front: Any = None self._back: Any = None self._len: int = 0 if iterable is not None: # append every value to the deque for val in iterable: self.append(val) def append(self, val: Any) -> None: """ Adds val to the end of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.append(4) >>> our_deque_1 [1, 2, 3, 4] >>> our_deque_2 = Deque('ab') >>> our_deque_2.append('c') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.append(4) >>> deque_collections_1 deque([1, 2, 3, 4]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.append('c') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes self._back.next_node = node node.prev_node = self._back self._back = node # assign new back to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def appendleft(self, val: Any) -> None: """ Adds val to the beginning of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([2, 3]) >>> our_deque_1.appendleft(1) >>> our_deque_1 [1, 2, 3] >>> our_deque_2 = Deque('bc') >>> our_deque_2.appendleft('a') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([2, 3]) >>> deque_collections_1.appendleft(1) >>> deque_collections_1 deque([1, 2, 3]) >>> deque_collections_2 = deque('bc') >>> deque_collections_2.appendleft('a') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes node.next_node = self._front self._front.prev_node = node self._front = node # assign new front to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def extend(self, iterable: Iterable[Any]) -> None: """ Appends every value of iterable to the end of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extend([4, 5]) >>> our_deque_1 [1, 2, 3, 4, 5] >>> our_deque_2 = Deque('ab') >>> our_deque_2.extend('cd') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extend([4, 5]) >>> deque_collections_1 deque([1, 2, 3, 4, 5]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.extend('cd') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iterable: self.append(val) def extendleft(self, iterable: Iterable[Any]) -> None: """ Appends every value of iterable to the beginning of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extendleft([0, -1]) >>> our_deque_1 [-1, 0, 1, 2, 3] >>> our_deque_2 = Deque('cd') >>> our_deque_2.extendleft('ba') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extendleft([0, -1]) >>> deque_collections_1 deque([-1, 0, 1, 2, 3]) >>> deque_collections_2 = deque('cd') >>> deque_collections_2.extendleft('ba') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iterable: self.appendleft(val) def pop(self) -> Any: """ Removes the last element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([1, 2, 3, 15182]) >>> our_popped = our_deque.pop() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([1, 2, 3, 15182]) >>> collections_popped = deque_collections.pop() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._back self._back = self._back.prev_node # set new back # drop the last node - python will deallocate memory automatically self._back.next_node = None self._len -= 1 return topop.val def popleft(self) -> Any: """ Removes the first element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([15182, 1, 2, 3]) >>> our_popped = our_deque.popleft() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([15182, 1, 2, 3]) >>> collections_popped = deque_collections.popleft() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._front self._front = self._front.next_node # set new front and drop the first node self._front.prev_node = None self._len -= 1 return topop.val def is_empty(self) -> bool: """ Checks if the deque is empty. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> our_deque.is_empty() False >>> our_empty_deque = Deque() >>> our_empty_deque.is_empty() True >>> from collections import deque >>> empty_deque_collections = deque() >>> list(our_empty_deque) == list(empty_deque_collections) True """ return self._front is None def __len__(self) -> int: """ Implements len() function. Returns the length of the deque. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> len(our_deque) 3 >>> our_empty_deque = Deque() >>> len(our_empty_deque) 0 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> len(deque_collections) 3 >>> empty_deque_collections = deque() >>> len(empty_deque_collections) 0 >>> len(our_empty_deque) == len(empty_deque_collections) True """ return self._len def __eq__(self, other: object) -> bool: """ Implements "==" operator. Returns if *self* is equal to *other*. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_2 = Deque([1, 2, 3]) >>> our_deque_1 == our_deque_2 True >>> our_deque_3 = Deque([1, 2]) >>> our_deque_1 == our_deque_3 False >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_2 = deque([1, 2, 3]) >>> deque_collections_1 == deque_collections_2 True >>> deque_collections_3 = deque([1, 2]) >>> deque_collections_1 == deque_collections_3 False >>> (our_deque_1 == our_deque_2) == (deque_collections_1 == deque_collections_2) True >>> (our_deque_1 == our_deque_3) == (deque_collections_1 == deque_collections_3) True """ if not isinstance(other, Deque): return NotImplemented me = self._front oth = other._front # if the length of the dequeues are not the same, they are not equal if len(self) != len(other): return False while me is not None and oth is not None: # compare every value if me.val != oth.val: return False me = me.next_node oth = oth.next_node return True def __iter__(self) -> Deque._Iterator: """ Implements iteration. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> for v in our_deque: ... print(v) 1 2 3 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> for v in deque_collections: ... print(v) 1 2 3 """ return Deque._Iterator(self._front) def __repr__(self) -> str: """ Implements representation of the deque. Represents it as a list, with its values between '[' and ']'. Time complexity: O(n) >>> our_deque = Deque([1, 2, 3]) >>> our_deque [1, 2, 3] """ values_list = [] aux = self._front while aux is not None: # append the values in a list to display values_list.append(aux.val) aux = aux.next_node return "[" + ", ".join(repr(val) for val in values_list) + "]" if __name__ == "__main__": import doctest doctest.testmod()
""" Implementation of double ended queue. """ from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from typing import Any class Deque: """ Deque data structure. Operations ---------- append(val: Any) -> None appendleft(val: Any) -> None extend(iterable: Iterable) -> None extendleft(iterable: Iterable) -> None pop() -> Any popleft() -> Any Observers --------- is_empty() -> bool Attributes ---------- _front: _Node front of the deque a.k.a. the first element _back: _Node back of the element a.k.a. the last element _len: int the number of nodes """ __slots__ = ["_front", "_back", "_len"] @dataclass class _Node: """ Representation of a node. Contains a value and a pointer to the next node as well as to the previous one. """ val: Any = None next_node: Deque._Node | None = None prev_node: Deque._Node | None = None class _Iterator: """ Helper class for iteration. Will be used to implement iteration. Attributes ---------- _cur: _Node the current node of the iteration. """ __slots__ = ["_cur"] def __init__(self, cur: Deque._Node | None) -> None: self._cur = cur def __iter__(self) -> Deque._Iterator: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) """ return self def __next__(self) -> Any: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) >>> next(iterator) 1 >>> next(iterator) 2 >>> next(iterator) 3 """ if self._cur is None: # finished iterating raise StopIteration val = self._cur.val self._cur = self._cur.next_node return val def __init__(self, iterable: Iterable[Any] | None = None) -> None: self._front: Any = None self._back: Any = None self._len: int = 0 if iterable is not None: # append every value to the deque for val in iterable: self.append(val) def append(self, val: Any) -> None: """ Adds val to the end of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.append(4) >>> our_deque_1 [1, 2, 3, 4] >>> our_deque_2 = Deque('ab') >>> our_deque_2.append('c') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.append(4) >>> deque_collections_1 deque([1, 2, 3, 4]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.append('c') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes self._back.next_node = node node.prev_node = self._back self._back = node # assign new back to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def appendleft(self, val: Any) -> None: """ Adds val to the beginning of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([2, 3]) >>> our_deque_1.appendleft(1) >>> our_deque_1 [1, 2, 3] >>> our_deque_2 = Deque('bc') >>> our_deque_2.appendleft('a') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([2, 3]) >>> deque_collections_1.appendleft(1) >>> deque_collections_1 deque([1, 2, 3]) >>> deque_collections_2 = deque('bc') >>> deque_collections_2.appendleft('a') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes node.next_node = self._front self._front.prev_node = node self._front = node # assign new front to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def extend(self, iterable: Iterable[Any]) -> None: """ Appends every value of iterable to the end of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extend([4, 5]) >>> our_deque_1 [1, 2, 3, 4, 5] >>> our_deque_2 = Deque('ab') >>> our_deque_2.extend('cd') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extend([4, 5]) >>> deque_collections_1 deque([1, 2, 3, 4, 5]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.extend('cd') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iterable: self.append(val) def extendleft(self, iterable: Iterable[Any]) -> None: """ Appends every value of iterable to the beginning of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extendleft([0, -1]) >>> our_deque_1 [-1, 0, 1, 2, 3] >>> our_deque_2 = Deque('cd') >>> our_deque_2.extendleft('ba') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extendleft([0, -1]) >>> deque_collections_1 deque([-1, 0, 1, 2, 3]) >>> deque_collections_2 = deque('cd') >>> deque_collections_2.extendleft('ba') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iterable: self.appendleft(val) def pop(self) -> Any: """ Removes the last element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([1, 2, 3, 15182]) >>> our_popped = our_deque.pop() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([1, 2, 3, 15182]) >>> collections_popped = deque_collections.pop() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._back self._back = self._back.prev_node # set new back # drop the last node - python will deallocate memory automatically self._back.next_node = None self._len -= 1 return topop.val def popleft(self) -> Any: """ Removes the first element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([15182, 1, 2, 3]) >>> our_popped = our_deque.popleft() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([15182, 1, 2, 3]) >>> collections_popped = deque_collections.popleft() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._front self._front = self._front.next_node # set new front and drop the first node self._front.prev_node = None self._len -= 1 return topop.val def is_empty(self) -> bool: """ Checks if the deque is empty. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> our_deque.is_empty() False >>> our_empty_deque = Deque() >>> our_empty_deque.is_empty() True >>> from collections import deque >>> empty_deque_collections = deque() >>> list(our_empty_deque) == list(empty_deque_collections) True """ return self._front is None def __len__(self) -> int: """ Implements len() function. Returns the length of the deque. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> len(our_deque) 3 >>> our_empty_deque = Deque() >>> len(our_empty_deque) 0 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> len(deque_collections) 3 >>> empty_deque_collections = deque() >>> len(empty_deque_collections) 0 >>> len(our_empty_deque) == len(empty_deque_collections) True """ return self._len def __eq__(self, other: object) -> bool: """ Implements "==" operator. Returns if *self* is equal to *other*. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_2 = Deque([1, 2, 3]) >>> our_deque_1 == our_deque_2 True >>> our_deque_3 = Deque([1, 2]) >>> our_deque_1 == our_deque_3 False >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_2 = deque([1, 2, 3]) >>> deque_collections_1 == deque_collections_2 True >>> deque_collections_3 = deque([1, 2]) >>> deque_collections_1 == deque_collections_3 False >>> (our_deque_1 == our_deque_2) == (deque_collections_1 == deque_collections_2) True >>> (our_deque_1 == our_deque_3) == (deque_collections_1 == deque_collections_3) True """ if not isinstance(other, Deque): return NotImplemented me = self._front oth = other._front # if the length of the dequeues are not the same, they are not equal if len(self) != len(other): return False while me is not None and oth is not None: # compare every value if me.val != oth.val: return False me = me.next_node oth = oth.next_node return True def __iter__(self) -> Deque._Iterator: """ Implements iteration. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> for v in our_deque: ... print(v) 1 2 3 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> for v in deque_collections: ... print(v) 1 2 3 """ return Deque._Iterator(self._front) def __repr__(self) -> str: """ Implements representation of the deque. Represents it as a list, with its values between '[' and ']'. Time complexity: O(n) >>> our_deque = Deque([1, 2, 3]) >>> our_deque [1, 2, 3] """ values_list = [] aux = self._front while aux is not None: # append the values in a list to display values_list.append(aux.val) aux = aux.next_node return f"[{', '.join(repr(val) for val in values_list)}]" if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Breath First Search (BFS) can be used when finding the shortest path from a given source node to a target node in an unweighted graph. """ from __future__ import annotations graph = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } class Graph: def __init__(self, graph: dict[str, list[str]], source_vertex: str) -> None: """ Graph is implemented as dictionary of adjacency lists. Also, Source vertex have to be defined upon initialization. """ self.graph = graph # mapping node to its parent in resulting breadth first tree self.parent: dict[str, str | None] = {} self.source_vertex = source_vertex def breath_first_search(self) -> None: """ This function is a helper for running breath first search on this graph. >>> g = Graph(graph, "G") >>> g.breath_first_search() >>> g.parent {'G': None, 'C': 'G', 'A': 'C', 'F': 'C', 'B': 'A', 'E': 'A', 'D': 'B'} """ visited = {self.source_vertex} self.parent[self.source_vertex] = None queue = [self.source_vertex] # first in first out queue while queue: vertex = queue.pop(0) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(adjacent_vertex) self.parent[adjacent_vertex] = vertex queue.append(adjacent_vertex) def shortest_path(self, target_vertex: str) -> str: """ This shortest path function returns a string, describing the result: 1.) No path is found. The string is a human readable message to indicate this. 2.) The shortest path is found. The string is in the form `v1(->v2->v3->...->vn)`, where v1 is the source vertex and vn is the target vertex, if it exists separately. >>> g = Graph(graph, "G") >>> g.breath_first_search() Case 1 - No path is found. >>> g.shortest_path("Foo") 'No path from vertex:G to vertex:Foo' Case 2 - The path is found. >>> g.shortest_path("D") 'G->C->A->B->D' >>> g.shortest_path("G") 'G' """ if target_vertex == self.source_vertex: return self.source_vertex target_vertex_parent = self.parent.get(target_vertex) if target_vertex_parent is None: return f"No path from vertex:{self.source_vertex} to vertex:{target_vertex}" return self.shortest_path(target_vertex_parent) + f"->{target_vertex}" if __name__ == "__main__": g = Graph(graph, "G") g.breath_first_search() print(g.shortest_path("D")) print(g.shortest_path("G")) print(g.shortest_path("Foo"))
"""Breath First Search (BFS) can be used when finding the shortest path from a given source node to a target node in an unweighted graph. """ from __future__ import annotations graph = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } class Graph: def __init__(self, graph: dict[str, list[str]], source_vertex: str) -> None: """ Graph is implemented as dictionary of adjacency lists. Also, Source vertex have to be defined upon initialization. """ self.graph = graph # mapping node to its parent in resulting breadth first tree self.parent: dict[str, str | None] = {} self.source_vertex = source_vertex def breath_first_search(self) -> None: """ This function is a helper for running breath first search on this graph. >>> g = Graph(graph, "G") >>> g.breath_first_search() >>> g.parent {'G': None, 'C': 'G', 'A': 'C', 'F': 'C', 'B': 'A', 'E': 'A', 'D': 'B'} """ visited = {self.source_vertex} self.parent[self.source_vertex] = None queue = [self.source_vertex] # first in first out queue while queue: vertex = queue.pop(0) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(adjacent_vertex) self.parent[adjacent_vertex] = vertex queue.append(adjacent_vertex) def shortest_path(self, target_vertex: str) -> str: """ This shortest path function returns a string, describing the result: 1.) No path is found. The string is a human readable message to indicate this. 2.) The shortest path is found. The string is in the form `v1(->v2->v3->...->vn)`, where v1 is the source vertex and vn is the target vertex, if it exists separately. >>> g = Graph(graph, "G") >>> g.breath_first_search() Case 1 - No path is found. >>> g.shortest_path("Foo") Traceback (most recent call last): ... ValueError: No path from vertex: G to vertex: Foo Case 2 - The path is found. >>> g.shortest_path("D") 'G->C->A->B->D' >>> g.shortest_path("G") 'G' """ if target_vertex == self.source_vertex: return self.source_vertex target_vertex_parent = self.parent.get(target_vertex) if target_vertex_parent is None: raise ValueError( f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) return self.shortest_path(target_vertex_parent) + f"->{target_vertex}" if __name__ == "__main__": g = Graph(graph, "G") g.breath_first_search() print(g.shortest_path("D")) print(g.shortest_path("G")) print(g.shortest_path("Foo"))
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Author: https://github.com/bhushan-borole """ """ The input graph for the algorithm is: A B C A 0 1 1 B 0 0 1 C 1 0 0 """ graph = [[0, 1, 1], [0, 0, 1], [1, 0, 0]] class Node: def __init__(self, name): self.name = name self.inbound = [] self.outbound = [] def add_inbound(self, node): self.inbound.append(node) def add_outbound(self, node): self.outbound.append(node) def __repr__(self): return f"Node {self.name}: Inbound: {self.inbound} ; Outbound: {self.outbound}" def page_rank(nodes, limit=3, d=0.85): ranks = {} for node in nodes: ranks[node.name] = 1 outbounds = {} for node in nodes: outbounds[node.name] = len(node.outbound) for i in range(limit): print(f"======= Iteration {i + 1} =======") for _, node in enumerate(nodes): ranks[node.name] = (1 - d) + d * sum( ranks[ib] / outbounds[ib] for ib in node.inbound ) print(ranks) def main(): names = list(input("Enter Names of the Nodes: ").split()) nodes = [Node(name) for name in names] for ri, row in enumerate(graph): for ci, col in enumerate(row): if col == 1: nodes[ci].add_inbound(names[ri]) nodes[ri].add_outbound(names[ci]) print("======= Nodes =======") for node in nodes: print(node) page_rank(nodes) if __name__ == "__main__": main()
""" Author: https://github.com/bhushan-borole """ """ The input graph for the algorithm is: A B C A 0 1 1 B 0 0 1 C 1 0 0 """ graph = [[0, 1, 1], [0, 0, 1], [1, 0, 0]] class Node: def __init__(self, name): self.name = name self.inbound = [] self.outbound = [] def add_inbound(self, node): self.inbound.append(node) def add_outbound(self, node): self.outbound.append(node) def __repr__(self): return f"<node={self.name} inbound={self.inbound} outbound={self.outbound}>" def page_rank(nodes, limit=3, d=0.85): ranks = {} for node in nodes: ranks[node.name] = 1 outbounds = {} for node in nodes: outbounds[node.name] = len(node.outbound) for i in range(limit): print(f"======= Iteration {i + 1} =======") for _, node in enumerate(nodes): ranks[node.name] = (1 - d) + d * sum( ranks[ib] / outbounds[ib] for ib in node.inbound ) print(ranks) def main(): names = list(input("Enter Names of the Nodes: ").split()) nodes = [Node(name) for name in names] for ri, row in enumerate(graph): for ci, col in enumerate(row): if col == 1: nodes[ci].add_inbound(names[ri]) nodes[ri].add_outbound(names[ci]) print("======= Nodes =======") for node in nodes: print(node) page_rank(nodes) if __name__ == "__main__": main()
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def points_to_polynomial(coordinates: list[list[int]]) -> str: """ coordinates is a two dimensional matrix: [[x, y], [x, y], ...] number of points you want to use >>> print(points_to_polynomial([])) The program cannot work out a fitting polynomial. >>> print(points_to_polynomial([[]])) The program cannot work out a fitting polynomial. >>> print(points_to_polynomial([[1, 0], [2, 0], [3, 0]])) f(x)=x^2*0.0+x^1*-0.0+x^0*0.0 >>> print(points_to_polynomial([[1, 1], [2, 1], [3, 1]])) f(x)=x^2*0.0+x^1*-0.0+x^0*1.0 >>> print(points_to_polynomial([[1, 3], [2, 3], [3, 3]])) f(x)=x^2*0.0+x^1*-0.0+x^0*3.0 >>> print(points_to_polynomial([[1, 1], [2, 2], [3, 3]])) f(x)=x^2*0.0+x^1*1.0+x^0*0.0 >>> print(points_to_polynomial([[1, 1], [2, 4], [3, 9]])) f(x)=x^2*1.0+x^1*-0.0+x^0*0.0 >>> print(points_to_polynomial([[1, 3], [2, 6], [3, 11]])) f(x)=x^2*1.0+x^1*-0.0+x^0*2.0 >>> print(points_to_polynomial([[1, -3], [2, -6], [3, -11]])) f(x)=x^2*-1.0+x^1*-0.0+x^0*-2.0 >>> print(points_to_polynomial([[1, 5], [2, 2], [3, 9]])) f(x)=x^2*5.0+x^1*-18.0+x^0*18.0 """ if len(coordinates) == 0 or not all(len(pair) == 2 for pair in coordinates): return "The program cannot work out a fitting polynomial." if len({tuple(pair) for pair in coordinates}) != len(coordinates): return "The program cannot work out a fitting polynomial." set_x = {x for x, _ in coordinates} if len(set_x) == 1: return f"x={coordinates[0][0]}" if len(set_x) != len(coordinates): return "The program cannot work out a fitting polynomial." x = len(coordinates) count_of_line = 0 matrix: list[list[float]] = [] # put the x and x to the power values in a matrix while count_of_line < x: count_in_line = 0 a = coordinates[count_of_line][0] count_line: list[float] = [] while count_in_line < x: count_line.append(a ** (x - (count_in_line + 1))) count_in_line += 1 matrix.append(count_line) count_of_line += 1 count_of_line = 0 # put the y values into a vector vector: list[float] = [] while count_of_line < x: vector.append(coordinates[count_of_line][1]) count_of_line += 1 count = 0 while count < x: zahlen = 0 while zahlen < x: if count == zahlen: zahlen += 1 if zahlen == x: break bruch = matrix[zahlen][count] / matrix[count][count] for counting_columns, item in enumerate(matrix[count]): # manipulating all the values in the matrix matrix[zahlen][counting_columns] -= item * bruch # manipulating the values in the vector vector[zahlen] -= vector[count] * bruch zahlen += 1 count += 1 count = 0 # make solutions solution: list[str] = [] while count < x: solution.append(str(vector[count] / matrix[count][count])) count += 1 count = 0 solved = "f(x)=" while count < x: remove_e: list[str] = solution[count].split("E") if len(remove_e) > 1: solution[count] = f"{remove_e[0]}*10^{remove_e[1]}" solved += f"x^{x - (count + 1)}*{solution[count]}" if count + 1 != x: solved += "+" count += 1 return solved if __name__ == "__main__": print(points_to_polynomial([])) print(points_to_polynomial([[]])) print(points_to_polynomial([[1, 0], [2, 0], [3, 0]])) print(points_to_polynomial([[1, 1], [2, 1], [3, 1]])) print(points_to_polynomial([[1, 3], [2, 3], [3, 3]])) print(points_to_polynomial([[1, 1], [2, 2], [3, 3]])) print(points_to_polynomial([[1, 1], [2, 4], [3, 9]])) print(points_to_polynomial([[1, 3], [2, 6], [3, 11]])) print(points_to_polynomial([[1, -3], [2, -6], [3, -11]])) print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))
def points_to_polynomial(coordinates: list[list[int]]) -> str: """ coordinates is a two dimensional matrix: [[x, y], [x, y], ...] number of points you want to use >>> print(points_to_polynomial([])) Traceback (most recent call last): ... ValueError: The program cannot work out a fitting polynomial. >>> print(points_to_polynomial([[]])) Traceback (most recent call last): ... ValueError: The program cannot work out a fitting polynomial. >>> print(points_to_polynomial([[1, 0], [2, 0], [3, 0]])) f(x)=x^2*0.0+x^1*-0.0+x^0*0.0 >>> print(points_to_polynomial([[1, 1], [2, 1], [3, 1]])) f(x)=x^2*0.0+x^1*-0.0+x^0*1.0 >>> print(points_to_polynomial([[1, 3], [2, 3], [3, 3]])) f(x)=x^2*0.0+x^1*-0.0+x^0*3.0 >>> print(points_to_polynomial([[1, 1], [2, 2], [3, 3]])) f(x)=x^2*0.0+x^1*1.0+x^0*0.0 >>> print(points_to_polynomial([[1, 1], [2, 4], [3, 9]])) f(x)=x^2*1.0+x^1*-0.0+x^0*0.0 >>> print(points_to_polynomial([[1, 3], [2, 6], [3, 11]])) f(x)=x^2*1.0+x^1*-0.0+x^0*2.0 >>> print(points_to_polynomial([[1, -3], [2, -6], [3, -11]])) f(x)=x^2*-1.0+x^1*-0.0+x^0*-2.0 >>> print(points_to_polynomial([[1, 5], [2, 2], [3, 9]])) f(x)=x^2*5.0+x^1*-18.0+x^0*18.0 """ if len(coordinates) == 0 or not all(len(pair) == 2 for pair in coordinates): raise ValueError("The program cannot work out a fitting polynomial.") if len({tuple(pair) for pair in coordinates}) != len(coordinates): raise ValueError("The program cannot work out a fitting polynomial.") set_x = {x for x, _ in coordinates} if len(set_x) == 1: return f"x={coordinates[0][0]}" if len(set_x) != len(coordinates): raise ValueError("The program cannot work out a fitting polynomial.") x = len(coordinates) count_of_line = 0 matrix: list[list[float]] = [] # put the x and x to the power values in a matrix while count_of_line < x: count_in_line = 0 a = coordinates[count_of_line][0] count_line: list[float] = [] while count_in_line < x: count_line.append(a ** (x - (count_in_line + 1))) count_in_line += 1 matrix.append(count_line) count_of_line += 1 count_of_line = 0 # put the y values into a vector vector: list[float] = [] while count_of_line < x: vector.append(coordinates[count_of_line][1]) count_of_line += 1 count = 0 while count < x: zahlen = 0 while zahlen < x: if count == zahlen: zahlen += 1 if zahlen == x: break bruch = matrix[zahlen][count] / matrix[count][count] for counting_columns, item in enumerate(matrix[count]): # manipulating all the values in the matrix matrix[zahlen][counting_columns] -= item * bruch # manipulating the values in the vector vector[zahlen] -= vector[count] * bruch zahlen += 1 count += 1 count = 0 # make solutions solution: list[str] = [] while count < x: solution.append(str(vector[count] / matrix[count][count])) count += 1 count = 0 solved = "f(x)=" while count < x: remove_e: list[str] = solution[count].split("E") if len(remove_e) > 1: solution[count] = f"{remove_e[0]}*10^{remove_e[1]}" solved += f"x^{x - (count + 1)}*{solution[count]}" if count + 1 != x: solved += "+" count += 1 return solved if __name__ == "__main__": print(points_to_polynomial([])) print(points_to_polynomial([[]])) print(points_to_polynomial([[1, 0], [2, 0], [3, 0]])) print(points_to_polynomial([[1, 1], [2, 1], [3, 1]])) print(points_to_polynomial([[1, 3], [2, 3], [3, 3]])) print(points_to_polynomial([[1, 1], [2, 2], [3, 3]])) print(points_to_polynomial([[1, 1], [2, 4], [3, 9]])) print(points_to_polynomial([[1, 3], [2, 6], [3, 11]])) print(points_to_polynomial([[1, -3], [2, -6], [3, -11]])) print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations import random class Dice: NUM_SIDES = 6 def __init__(self): """Initialize a six sided dice""" self.sides = list(range(1, Dice.NUM_SIDES + 1)) def roll(self): return random.choice(self.sides) def _str_(self): return "Fair Dice" def throw_dice(num_throws: int, num_dice: int = 2) -> list[float]: """ Return probability list of all possible sums when throwing dice. >>> random.seed(0) >>> throw_dice(10, 1) [10.0, 0.0, 30.0, 50.0, 10.0, 0.0] >>> throw_dice(100, 1) [19.0, 17.0, 17.0, 11.0, 23.0, 13.0] >>> throw_dice(1000, 1) [18.8, 15.5, 16.3, 17.6, 14.2, 17.6] >>> throw_dice(10000, 1) [16.35, 16.89, 16.93, 16.6, 16.52, 16.71] >>> throw_dice(10000, 2) [2.74, 5.6, 7.99, 11.26, 13.92, 16.7, 14.44, 10.63, 8.05, 5.92, 2.75] """ dices = [Dice() for i in range(num_dice)] count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1) for _ in range(num_throws): count_of_sum[sum(dice.roll() for dice in dices)] += 1 probability = [round((count * 100) / num_throws, 2) for count in count_of_sum] return probability[num_dice:] # remove probability of sums that never appear if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations import random class Dice: NUM_SIDES = 6 def __init__(self): """Initialize a six sided dice""" self.sides = list(range(1, Dice.NUM_SIDES + 1)) def roll(self): return random.choice(self.sides) def throw_dice(num_throws: int, num_dice: int = 2) -> list[float]: """ Return probability list of all possible sums when throwing dice. >>> random.seed(0) >>> throw_dice(10, 1) [10.0, 0.0, 30.0, 50.0, 10.0, 0.0] >>> throw_dice(100, 1) [19.0, 17.0, 17.0, 11.0, 23.0, 13.0] >>> throw_dice(1000, 1) [18.8, 15.5, 16.3, 17.6, 14.2, 17.6] >>> throw_dice(10000, 1) [16.35, 16.89, 16.93, 16.6, 16.52, 16.71] >>> throw_dice(10000, 2) [2.74, 5.6, 7.99, 11.26, 13.92, 16.7, 14.44, 10.63, 8.05, 5.92, 2.75] """ dices = [Dice() for i in range(num_dice)] count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1) for _ in range(num_throws): count_of_sum[sum(dice.roll() for dice in dices)] += 1 probability = [round((count * 100) / num_throws, 2) for count in count_of_sum] return probability[num_dice:] # remove probability of sums that never appear if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://www.chilimath.com/lessons/advanced-algebra/cramers-rule-with-two-variables # https://en.wikipedia.org/wiki/Cramer%27s_rule def cramers_rule_2x2(equation1: list[int], equation2: list[int]) -> str: """ Solves the system of linear equation in 2 variables. :param: equation1: list of 3 numbers :param: equation2: list of 3 numbers :return: String of result input format : [a1, b1, d1], [a2, b2, d2] determinant = [[a1, b1], [a2, b2]] determinant_x = [[d1, b1], [d2, b2]] determinant_y = [[a1, d1], [a2, d2]] >>> cramers_rule_2x2([2, 3, 0], [5, 1, 0]) 'Trivial solution. (Consistent system) x = 0 and y = 0' >>> cramers_rule_2x2([0, 4, 50], [2, 0, 26]) 'Non-Trivial Solution (Consistent system) x = 13.0, y = 12.5' >>> cramers_rule_2x2([11, 2, 30], [1, 0, 4]) 'Non-Trivial Solution (Consistent system) x = 4.0, y = -7.0' >>> cramers_rule_2x2([4, 7, 1], [1, 2, 0]) 'Non-Trivial Solution (Consistent system) x = 2.0, y = -1.0' >>> cramers_rule_2x2([1, 2, 3], [2, 4, 6]) Traceback (most recent call last): ... ValueError: Infinite solutions. (Consistent system) >>> cramers_rule_2x2([1, 2, 3], [2, 4, 7]) Traceback (most recent call last): ... ValueError: No solution. (Inconsistent system) >>> cramers_rule_2x2([1, 2, 3], [11, 22]) Traceback (most recent call last): ... ValueError: Please enter a valid equation. >>> cramers_rule_2x2([0, 1, 6], [0, 0, 3]) Traceback (most recent call last): ... ValueError: No solution. (Inconsistent system) >>> cramers_rule_2x2([0, 0, 6], [0, 0, 3]) Traceback (most recent call last): ... ValueError: Both a & b of two equations can't be zero. >>> cramers_rule_2x2([1, 2, 3], [1, 2, 3]) Traceback (most recent call last): ... ValueError: Infinite solutions. (Consistent system) >>> cramers_rule_2x2([0, 4, 50], [0, 3, 99]) Traceback (most recent call last): ... ValueError: No solution. (Inconsistent system) """ # Check if the input is valid if not len(equation1) == len(equation2) == 3: raise ValueError("Please enter a valid equation.") if equation1[0] == equation1[1] == equation2[0] == equation2[1] == 0: raise ValueError("Both a & b of two equations can't be zero.") # Extract the coefficients a1, b1, c1 = equation1 a2, b2, c2 = equation2 # Calculate the determinants of the matrices determinant = a1 * b2 - a2 * b1 determinant_x = c1 * b2 - c2 * b1 determinant_y = a1 * c2 - a2 * c1 # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError("Infinite solutions. (Consistent system)") else: raise ValueError("No solution. (Inconsistent system)") else: if determinant_x == determinant_y == 0: return "Trivial solution. (Consistent system) x = 0 and y = 0" else: x = determinant_x / determinant y = determinant_y / determinant return f"Non-Trivial Solution (Consistent system) x = {x}, y = {y}"
# https://www.chilimath.com/lessons/advanced-algebra/cramers-rule-with-two-variables # https://en.wikipedia.org/wiki/Cramer%27s_rule def cramers_rule_2x2(equation1: list[int], equation2: list[int]) -> tuple[float, float]: """ Solves the system of linear equation in 2 variables. :param: equation1: list of 3 numbers :param: equation2: list of 3 numbers :return: String of result input format : [a1, b1, d1], [a2, b2, d2] determinant = [[a1, b1], [a2, b2]] determinant_x = [[d1, b1], [d2, b2]] determinant_y = [[a1, d1], [a2, d2]] >>> cramers_rule_2x2([2, 3, 0], [5, 1, 0]) (0.0, 0.0) >>> cramers_rule_2x2([0, 4, 50], [2, 0, 26]) (13.0, 12.5) >>> cramers_rule_2x2([11, 2, 30], [1, 0, 4]) (4.0, -7.0) >>> cramers_rule_2x2([4, 7, 1], [1, 2, 0]) (2.0, -1.0) >>> cramers_rule_2x2([1, 2, 3], [2, 4, 6]) Traceback (most recent call last): ... ValueError: Infinite solutions. (Consistent system) >>> cramers_rule_2x2([1, 2, 3], [2, 4, 7]) Traceback (most recent call last): ... ValueError: No solution. (Inconsistent system) >>> cramers_rule_2x2([1, 2, 3], [11, 22]) Traceback (most recent call last): ... ValueError: Please enter a valid equation. >>> cramers_rule_2x2([0, 1, 6], [0, 0, 3]) Traceback (most recent call last): ... ValueError: No solution. (Inconsistent system) >>> cramers_rule_2x2([0, 0, 6], [0, 0, 3]) Traceback (most recent call last): ... ValueError: Both a & b of two equations can't be zero. >>> cramers_rule_2x2([1, 2, 3], [1, 2, 3]) Traceback (most recent call last): ... ValueError: Infinite solutions. (Consistent system) >>> cramers_rule_2x2([0, 4, 50], [0, 3, 99]) Traceback (most recent call last): ... ValueError: No solution. (Inconsistent system) """ # Check if the input is valid if not len(equation1) == len(equation2) == 3: raise ValueError("Please enter a valid equation.") if equation1[0] == equation1[1] == equation2[0] == equation2[1] == 0: raise ValueError("Both a & b of two equations can't be zero.") # Extract the coefficients a1, b1, c1 = equation1 a2, b2, c2 = equation2 # Calculate the determinants of the matrices determinant = a1 * b2 - a2 * b1 determinant_x = c1 * b2 - c2 * b1 determinant_y = a1 * c2 - a2 * c1 # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError("Infinite solutions. (Consistent system)") else: raise ValueError("No solution. (Inconsistent system)") else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: x = determinant_x / determinant y = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def password_generator(length: int = 8) -> str: """ Password Generator allows you to generate a random password of length N. >>> len(password_generator()) 8 >>> len(password_generator(length=16)) 16 >>> len(password_generator(257)) 257 >>> len(password_generator(length=0)) 0 >>> len(password_generator(-1)) 0 """ chars = ascii_letters + digits + punctuation return "".join(secrets.choice(chars) for _ in range(length)) # ALTERNATIVE METHODS # chars_incl= characters that must be in password # i= how many letters or characters the password length will be def alternative_password_generator(chars_incl: str, i: int) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(chars_incl) quotient = i // 3 remainder = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) chars = ( chars_incl + random(ascii_letters, quotient + remainder) + random(digits, quotient) + random(punctuation, quotient) ) list_of_chars = list(chars) shuffle(list_of_chars) return "".join(list_of_chars) # random is a generalised function for letters, characters and numbers def random(chars_incl: str, i: int) -> str: return "".join(secrets.choice(chars_incl) for _ in range(i)) def random_number(chars_incl, i): pass # Put your code here... def random_letters(chars_incl, i): pass # Put your code here... def random_characters(chars_incl, i): pass # Put your code here... # This Will Check Whether A Given Password Is Strong Or Not # It Follows The Rule that Length Of Password Should Be At Least 8 Characters # And At Least 1 Lower, 1 Upper, 1 Number And 1 Special Character def strong_password_detector(password: str, min_length: int = 8) -> str: """ >>> strong_password_detector('Hwea7$2!') 'This is a strong Password' >>> strong_password_detector('Sh0r1') 'Your Password must be at least 8 characters long' >>> strong_password_detector('Hello123') 'Password should contain UPPERCASE, lowercase, numbers, special characters' >>> strong_password_detector('Hello1238udfhiaf038fajdvjjf!jaiuFhkqi1') 'This is a strong Password' >>> strong_password_detector('0') 'Your Password must be at least 8 characters long' """ if len(password) < min_length: return "Your Password must be at least 8 characters long" upper = any(char in ascii_uppercase for char in password) lower = any(char in ascii_lowercase for char in password) num = any(char in digits for char in password) spec_char = any(char in punctuation for char in password) if upper and lower and num and spec_char: return "This is a strong Password" else: return ( "Password should contain UPPERCASE, lowercase, " "numbers, special characters" ) def main(): length = int(input("Please indicate the max length of your password: ").strip()) chars_incl = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:", password_generator(length)) print( "Alternative Password generated:", alternative_password_generator(chars_incl, length), ) print("[If you are thinking of using this passsword, You better save it.]") if __name__ == "__main__": main()
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def password_generator(length: int = 8) -> str: """ Password Generator allows you to generate a random password of length N. >>> len(password_generator()) 8 >>> len(password_generator(length=16)) 16 >>> len(password_generator(257)) 257 >>> len(password_generator(length=0)) 0 >>> len(password_generator(-1)) 0 """ chars = ascii_letters + digits + punctuation return "".join(secrets.choice(chars) for _ in range(length)) # ALTERNATIVE METHODS # chars_incl= characters that must be in password # i= how many letters or characters the password length will be def alternative_password_generator(chars_incl: str, i: int) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(chars_incl) quotient = i // 3 remainder = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) chars = ( chars_incl + random(ascii_letters, quotient + remainder) + random(digits, quotient) + random(punctuation, quotient) ) list_of_chars = list(chars) shuffle(list_of_chars) return "".join(list_of_chars) # random is a generalised function for letters, characters and numbers def random(chars_incl: str, i: int) -> str: return "".join(secrets.choice(chars_incl) for _ in range(i)) def random_number(chars_incl, i): pass # Put your code here... def random_letters(chars_incl, i): pass # Put your code here... def random_characters(chars_incl, i): pass # Put your code here... # This Will Check Whether A Given Password Is Strong Or Not # It Follows The Rule that Length Of Password Should Be At Least 8 Characters # And At Least 1 Lower, 1 Upper, 1 Number And 1 Special Character def is_strong_password(password: str, min_length: int = 8) -> bool: """ >>> is_strong_password('Hwea7$2!') True >>> is_strong_password('Sh0r1') False >>> is_strong_password('Hello123') False >>> is_strong_password('Hello1238udfhiaf038fajdvjjf!jaiuFhkqi1') True >>> is_strong_password('0') False """ if len(password) < min_length: # Your Password must be at least 8 characters long return False upper = any(char in ascii_uppercase for char in password) lower = any(char in ascii_lowercase for char in password) num = any(char in digits for char in password) spec_char = any(char in punctuation for char in password) if upper and lower and num and spec_char: return True else: # Passwords should contain UPPERCASE, lowerase # numbers, and special characters return False def main(): length = int(input("Please indicate the max length of your password: ").strip()) chars_incl = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:", password_generator(length)) print( "Alternative Password generated:", alternative_password_generator(chars_incl, length), ) print("[If you are thinking of using this passsword, You better save it.]") if __name__ == "__main__": main()
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import re def dna(dna: str) -> str: """ https://en.wikipedia.org/wiki/DNA Returns the second side of a DNA strand >>> dna("GCTA") 'CGAT' >>> dna("ATGC") 'TACG' >>> dna("CTGA") 'GACT' >>> dna("GFGG") 'Invalid Strand' """ r = len(re.findall("[ATCG]", dna)) != len(dna) val = dna.translate(dna.maketrans("ATCG", "TAGC")) return "Invalid Strand" if r else val if __name__ == "__main__": __import__("doctest").testmod()
import re def dna(dna: str) -> str: """ https://en.wikipedia.org/wiki/DNA Returns the second side of a DNA strand >>> dna("GCTA") 'CGAT' >>> dna("ATGC") 'TACG' >>> dna("CTGA") 'GACT' >>> dna("GFGG") Traceback (most recent call last): ... ValueError: Invalid Strand """ if len(re.findall("[ATCG]", dna)) != len(dna): raise ValueError("Invalid Strand") return dna.translate(dna.maketrans("ATCG", "TAGC")) if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from datetime import datetime import requests def download_video(url: str) -> bytes: base_url = "https://downloadgram.net/wp-json/wppress/video-downloader/video?url=" video_url = requests.get(base_url + url).json()[0]["urls"][0]["src"] return requests.get(video_url).content if __name__ == "__main__": url = input("Enter Video/IGTV url: ").strip() file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4" with open(file_name, "wb") as fp: fp.write(download_video(url)) print(f"Done. Video saved to disk as {file_name}.")
from datetime import datetime import requests def download_video(url: str) -> bytes: base_url = "https://downloadgram.net/wp-json/wppress/video-downloader/video?url=" video_url = requests.get(base_url + url).json()[0]["urls"][0]["src"] return requests.get(video_url).content if __name__ == "__main__": url = input("Enter Video/IGTV url: ").strip() file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4" with open(file_name, "wb") as fp: fp.write(download_video(url)) print(f"Done. Video saved to disk as {file_name}.")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Number letter counts Problem 17: https://projecteuler.net/problem=17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance withBritish usage. """ def solution(n: int = 1000) -> int: """Returns the number of letters used to write all numbers from 1 to n. where n is lower or equals to 1000. >>> solution(1000) 21124 >>> solution(5) 19 """ # number of letters in zero, one, two, ..., nineteen (0 for zero since it's # never said aloud) ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8] # number of letters in twenty, thirty, ..., ninety (0 for numbers less than # 20 due to inconsistency in teens) tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6] count = 0 for i in range(1, n + 1): if i < 1000: if i >= 100: # add number of letters for "n hundred" count += ones_counts[i // 100] + 7 if i % 100 != 0: # add number of letters for "and" if number is not multiple # of 100 count += 3 if 0 < i % 100 < 20: # add number of letters for one, two, three, ..., nineteen # (could be combined with below if not for inconsistency in # teens) count += ones_counts[i % 100] else: # add number of letters for twenty, twenty one, ..., ninety # nine count += ones_counts[i % 10] count += tens_counts[(i % 100 - i % 10) // 10] else: count += ones_counts[i // 1000] + 8 return count if __name__ == "__main__": print(solution(int(input().strip())))
""" Number letter counts Problem 17: https://projecteuler.net/problem=17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance withBritish usage. """ def solution(n: int = 1000) -> int: """Returns the number of letters used to write all numbers from 1 to n. where n is lower or equals to 1000. >>> solution(1000) 21124 >>> solution(5) 19 """ # number of letters in zero, one, two, ..., nineteen (0 for zero since it's # never said aloud) ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8] # number of letters in twenty, thirty, ..., ninety (0 for numbers less than # 20 due to inconsistency in teens) tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6] count = 0 for i in range(1, n + 1): if i < 1000: if i >= 100: # add number of letters for "n hundred" count += ones_counts[i // 100] + 7 if i % 100 != 0: # add number of letters for "and" if number is not multiple # of 100 count += 3 if 0 < i % 100 < 20: # add number of letters for one, two, three, ..., nineteen # (could be combined with below if not for inconsistency in # teens) count += ones_counts[i % 100] else: # add number of letters for twenty, twenty one, ..., ninety # nine count += ones_counts[i % 10] count += tens_counts[(i % 100 - i % 10) // 10] else: count += ones_counts[i // 1000] + 8 return count if __name__ == "__main__": print(solution(int(input().strip())))
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from collections.abc import Iterator from typing import Any class Node: def __init__(self, data: Any): self.data: Any = data self.next: Node | None = None class CircularLinkedList: def __init__(self): self.head = None self.tail = None def __iter__(self) -> Iterator[Any]: node = self.head while self.head: yield node.data node = node.next if node == self.head: break def __len__(self) -> int: return len(tuple(iter(self))) def __repr__(self): return "->".join(str(item) for item in iter(self)) def insert_tail(self, data: Any) -> None: self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: if index < 0 or index > len(self): raise IndexError("list index out of range.") new_node = Node(data) if self.head is None: new_node.next = new_node # first node points itself self.tail = self.head = new_node elif index == 0: # insert at head new_node.next = self.head self.head = self.tail.next = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next new_node.next = temp.next temp.next = new_node if index == len(self) - 1: # insert at tail self.tail = new_node def delete_front(self): return self.delete_nth(0) def delete_tail(self) -> Any: return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: if not 0 <= index < len(self): raise IndexError("list index out of range.") delete_node = self.head if self.head == self.tail: # just one node self.head = self.tail = None elif index == 0: # delete head node self.tail.next = self.tail.next.next self.head = self.head.next else: temp = self.head for _ in range(index - 1): temp = temp.next delete_node = temp.next temp.next = temp.next.next if index == len(self) - 1: # delete at tail self.tail = temp return delete_node.data def is_empty(self) -> bool: return len(self) == 0 def test_circular_linked_list() -> None: """ >>> test_circular_linked_list() """ circular_linked_list = CircularLinkedList() assert len(circular_linked_list) == 0 assert circular_linked_list.is_empty() is True assert str(circular_linked_list) == "" try: circular_linked_list.delete_front() raise AssertionError() # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError() # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1) raise AssertionError() except IndexError: assert True try: circular_linked_list.delete_nth(0) raise AssertionError() except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5): assert len(circular_linked_list) == i circular_linked_list.insert_nth(i, i + 1) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) circular_linked_list.insert_tail(6) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7)) circular_linked_list.insert_head(0) assert str(circular_linked_list) == "->".join(str(i) for i in range(0, 7)) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) assert circular_linked_list.delete_nth(2) == 3 circular_linked_list.insert_nth(2, 3) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations from collections.abc import Iterator from typing import Any class Node: def __init__(self, data: Any): self.data: Any = data self.next: Node | None = None class CircularLinkedList: def __init__(self): self.head = None self.tail = None def __iter__(self) -> Iterator[Any]: node = self.head while self.head: yield node.data node = node.next if node == self.head: break def __len__(self) -> int: return len(tuple(iter(self))) def __repr__(self): return "->".join(str(item) for item in iter(self)) def insert_tail(self, data: Any) -> None: self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: if index < 0 or index > len(self): raise IndexError("list index out of range.") new_node = Node(data) if self.head is None: new_node.next = new_node # first node points itself self.tail = self.head = new_node elif index == 0: # insert at head new_node.next = self.head self.head = self.tail.next = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next new_node.next = temp.next temp.next = new_node if index == len(self) - 1: # insert at tail self.tail = new_node def delete_front(self): return self.delete_nth(0) def delete_tail(self) -> Any: return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: if not 0 <= index < len(self): raise IndexError("list index out of range.") delete_node = self.head if self.head == self.tail: # just one node self.head = self.tail = None elif index == 0: # delete head node self.tail.next = self.tail.next.next self.head = self.head.next else: temp = self.head for _ in range(index - 1): temp = temp.next delete_node = temp.next temp.next = temp.next.next if index == len(self) - 1: # delete at tail self.tail = temp return delete_node.data def is_empty(self) -> bool: return len(self) == 0 def test_circular_linked_list() -> None: """ >>> test_circular_linked_list() """ circular_linked_list = CircularLinkedList() assert len(circular_linked_list) == 0 assert circular_linked_list.is_empty() is True assert str(circular_linked_list) == "" try: circular_linked_list.delete_front() raise AssertionError() # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError() # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1) raise AssertionError() except IndexError: assert True try: circular_linked_list.delete_nth(0) raise AssertionError() except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5): assert len(circular_linked_list) == i circular_linked_list.insert_nth(i, i + 1) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) circular_linked_list.insert_tail(6) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7)) circular_linked_list.insert_head(0) assert str(circular_linked_list) == "->".join(str(i) for i in range(0, 7)) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) assert circular_linked_list.delete_nth(2) == 3 circular_linked_list.insert_nth(2, 3) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import math """ Finding the intensity of light transmitted through a polariser using Malus Law and by taking initial intensity and angle between polariser and axis as input Description : Malus's law, which is named after Étienne-Louis Malus, says that when a perfect polarizer is placed in a polarized beam of light, the irradiance, I, of the light that passes through is given by I=I'cos²θ where I' is the initial intensity and θ is the angle between the light's initial polarization direction and the axis of the polarizer. A beam of unpolarized light can be thought of as containing a uniform mixture of linear polarizations at all possible angles. Since the average value of cos²θ is 1/2, the transmission coefficient becomes I/I' = 1/2 In practice, some light is lost in the polarizer and the actual transmission will be somewhat lower than this, around 38% for Polaroid-type polarizers but considerably higher (>49.9%) for some birefringent prism types. If two polarizers are placed one after another (the second polarizer is generally called an analyzer), the mutual angle between their polarizing axes gives the value of θ in Malus's law. If the two axes are orthogonal, the polarizers are crossed and in theory no light is transmitted, though again practically speaking no polarizer is perfect and the transmission is not exactly zero (for example, crossed Polaroid sheets appear slightly blue in colour because their extinction ratio is better in the red). If a transparent object is placed between the crossed polarizers, any polarization effects present in the sample (such as birefringence) will be shown as an increase in transmission. This effect is used in polarimetry to measure the optical activity of a sample. Real polarizers are also not perfect blockers of the polarization orthogonal to their polarization axis; the ratio of the transmission of the unwanted component to the wanted component is called the extinction ratio, and varies from around 1:500 for Polaroid to about 1:106 for Glan–Taylor prism polarizers. Reference : "https://en.wikipedia.org/wiki/Polarizer#Malus's_law_and_other_properties" """ def malus_law(initial_intensity: float, angle: float) -> float: """ >>> round(malus_law(10,45),2) 5.0 >>> round(malus_law(100,60),2) 25.0 >>> round(malus_law(50,150),2) 37.5 >>> round(malus_law(75,270),2) 0.0 >>> round(malus_law(10,-900),2) Traceback (most recent call last): ... ValueError: In Malus Law, the angle is in the range 0-360 degrees >>> round(malus_law(10,900),2) Traceback (most recent call last): ... ValueError: In Malus Law, the angle is in the range 0-360 degrees >>> round(malus_law(-100,900),2) Traceback (most recent call last): ... ValueError: The value of intensity cannot be negative >>> round(malus_law(100,180),2) 100.0 >>> round(malus_law(100,360),2) 100.0 """ if initial_intensity < 0: raise ValueError("The value of intensity cannot be negative") # handling of negative values of initial intensity if angle < 0 or angle > 360: raise ValueError("In Malus Law, the angle is in the range 0-360 degrees") # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(angle)) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name="malus_law")
import math """ Finding the intensity of light transmitted through a polariser using Malus Law and by taking initial intensity and angle between polariser and axis as input Description : Malus's law, which is named after Étienne-Louis Malus, says that when a perfect polarizer is placed in a polarized beam of light, the irradiance, I, of the light that passes through is given by I=I'cos²θ where I' is the initial intensity and θ is the angle between the light's initial polarization direction and the axis of the polarizer. A beam of unpolarized light can be thought of as containing a uniform mixture of linear polarizations at all possible angles. Since the average value of cos²θ is 1/2, the transmission coefficient becomes I/I' = 1/2 In practice, some light is lost in the polarizer and the actual transmission will be somewhat lower than this, around 38% for Polaroid-type polarizers but considerably higher (>49.9%) for some birefringent prism types. If two polarizers are placed one after another (the second polarizer is generally called an analyzer), the mutual angle between their polarizing axes gives the value of θ in Malus's law. If the two axes are orthogonal, the polarizers are crossed and in theory no light is transmitted, though again practically speaking no polarizer is perfect and the transmission is not exactly zero (for example, crossed Polaroid sheets appear slightly blue in colour because their extinction ratio is better in the red). If a transparent object is placed between the crossed polarizers, any polarization effects present in the sample (such as birefringence) will be shown as an increase in transmission. This effect is used in polarimetry to measure the optical activity of a sample. Real polarizers are also not perfect blockers of the polarization orthogonal to their polarization axis; the ratio of the transmission of the unwanted component to the wanted component is called the extinction ratio, and varies from around 1:500 for Polaroid to about 1:106 for Glan–Taylor prism polarizers. Reference : "https://en.wikipedia.org/wiki/Polarizer#Malus's_law_and_other_properties" """ def malus_law(initial_intensity: float, angle: float) -> float: """ >>> round(malus_law(10,45),2) 5.0 >>> round(malus_law(100,60),2) 25.0 >>> round(malus_law(50,150),2) 37.5 >>> round(malus_law(75,270),2) 0.0 >>> round(malus_law(10,-900),2) Traceback (most recent call last): ... ValueError: In Malus Law, the angle is in the range 0-360 degrees >>> round(malus_law(10,900),2) Traceback (most recent call last): ... ValueError: In Malus Law, the angle is in the range 0-360 degrees >>> round(malus_law(-100,900),2) Traceback (most recent call last): ... ValueError: The value of intensity cannot be negative >>> round(malus_law(100,180),2) 100.0 >>> round(malus_law(100,360),2) 100.0 """ if initial_intensity < 0: raise ValueError("The value of intensity cannot be negative") # handling of negative values of initial intensity if angle < 0 or angle > 360: raise ValueError("In Malus Law, the angle is in the range 0-360 degrees") # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(angle)) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name="malus_law")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another 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! """ from math import factorial 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 """ return sum(int(x) for x in str(factorial(num))) 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! """ from math import factorial 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 """ return sum(int(x) for x in str(factorial(num))) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Uses Pythagoras theorem to calculate the distance between two points in space.""" import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) def test_distance() -> None: """ >>> point1 = Point(2, -1, 7) >>> point2 = Point(1, -3, 5) >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 """ pass if __name__ == "__main__": import doctest doctest.testmod()
"""Uses Pythagoras theorem to calculate the distance between two points in space.""" import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) def test_distance() -> None: """ >>> point1 = Point(2, -1, 7) >>> point2 = Point(1, -3, 5) >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 """ pass if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from collections.abc import 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) >>> h [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5] >>> >>> h.extract_max() 209 >>> h [201, 107, 25, 103, 11, 15, 1, 9, 7, 5] >>> >>> h.insert(100) >>> h [201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11] >>> >>> h.heap_sort() >>> 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 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 collections.abc 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) >>> h [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5] >>> >>> h.extract_max() 209 >>> h [201, 107, 25, 103, 11, 15, 1, 9, 7, 5] >>> >>> h.insert(100) >>> h [201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11] >>> >>> h.heap_sort() >>> 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 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
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://cp-algorithms.com/string/z-function.html Z-function or Z algorithm Efficient algorithm for pattern occurrence in a string Time Complexity: O(n) - where n is the length of the string """ def z_function(input_str: str) -> list[int]: """ For the given string this function computes value for each index, which represents the maximal length substring starting from the index and is the same as the prefix of the same size e.x. for string 'abab' for second index value would be 2 For the value of the first element the algorithm always returns 0 >>> z_function("abracadabra") [0, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1] >>> z_function("aaaa") [0, 3, 2, 1] >>> z_function("zxxzxxz") [0, 0, 0, 4, 0, 0, 1] """ z_result = [0 for i in range(len(input_str))] # initialize interval's left pointer and right pointer left_pointer, right_pointer = 0, 0 for i in range(1, len(input_str)): # case when current index is inside the interval if i <= right_pointer: min_edge = min(right_pointer - i + 1, z_result[i - left_pointer]) z_result[i] = min_edge while go_next(i, z_result, input_str): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: left_pointer, right_pointer = i, i + z_result[i] - 1 return z_result def go_next(i: int, z_result: list[int], s: str) -> bool: """ Check if we have to move forward to the next characters or not """ return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]] def find_pattern(pattern: str, input_str: str) -> int: """ Example of using z-function for pattern occurrence Given function returns the number of times 'pattern' appears in 'input_str' as a substring >>> find_pattern("abr", "abracadabra") 2 >>> find_pattern("a", "aaaa") 4 >>> find_pattern("xz", "zxxzxxz") 2 """ answer = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string z_result = z_function(pattern + input_str) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(pattern): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
""" https://cp-algorithms.com/string/z-function.html Z-function or Z algorithm Efficient algorithm for pattern occurrence in a string Time Complexity: O(n) - where n is the length of the string """ def z_function(input_str: str) -> list[int]: """ For the given string this function computes value for each index, which represents the maximal length substring starting from the index and is the same as the prefix of the same size e.x. for string 'abab' for second index value would be 2 For the value of the first element the algorithm always returns 0 >>> z_function("abracadabra") [0, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1] >>> z_function("aaaa") [0, 3, 2, 1] >>> z_function("zxxzxxz") [0, 0, 0, 4, 0, 0, 1] """ z_result = [0 for i in range(len(input_str))] # initialize interval's left pointer and right pointer left_pointer, right_pointer = 0, 0 for i in range(1, len(input_str)): # case when current index is inside the interval if i <= right_pointer: min_edge = min(right_pointer - i + 1, z_result[i - left_pointer]) z_result[i] = min_edge while go_next(i, z_result, input_str): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: left_pointer, right_pointer = i, i + z_result[i] - 1 return z_result def go_next(i: int, z_result: list[int], s: str) -> bool: """ Check if we have to move forward to the next characters or not """ return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]] def find_pattern(pattern: str, input_str: str) -> int: """ Example of using z-function for pattern occurrence Given function returns the number of times 'pattern' appears in 'input_str' as a substring >>> find_pattern("abr", "abracadabra") 2 >>> find_pattern("a", "aaaa") 4 >>> find_pattern("xz", "zxxzxxz") 2 """ answer = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string z_result = z_function(pattern + input_str) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(pattern): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
B64_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def base64_encode(data: bytes) -> bytes: """Encodes data according to RFC4648. The data is first transformed to binary and appended with binary digits so that its length becomes a multiple of 6, then each 6 binary digits will match a character in the B64_CHARSET string. The number of appended binary digits would later determine how many "=" signs should be added, the padding. For every 2 binary digits added, a "=" sign is added in the output. We can add any binary digits to make it a multiple of 6, for instance, consider the following example: "AA" -> 0010100100101001 -> 001010 010010 1001 As can be seen above, 2 more binary digits should be added, so there's 4 possibilities here: 00, 01, 10 or 11. That being said, Base64 encoding can be used in Steganography to hide data in these appended digits. >>> from base64 import b64encode >>> a = b"This pull request is part of Hacktoberfest20!" >>> b = b"https://tools.ietf.org/html/rfc4648" >>> c = b"A" >>> base64_encode(a) == b64encode(a) True >>> base64_encode(b) == b64encode(b) True >>> base64_encode(c) == b64encode(c) True >>> base64_encode("abc") Traceback (most recent call last): ... TypeError: a bytes-like object is required, not 'str' """ # Make sure the supplied data is a bytes-like object if not isinstance(data, bytes): raise TypeError( f"a bytes-like object is required, not '{data.__class__.__name__}'" ) binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data) padding_needed = len(binary_stream) % 6 != 0 if padding_needed: # The padding that will be added later padding = b"=" * ((6 - len(binary_stream) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(binary_stream) % 6) else: padding = b"" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6], 2)] for index in range(0, len(binary_stream), 6) ).encode() + padding ) def base64_decode(encoded_data: str) -> bytes: """Decodes data according to RFC4648. This does the reverse operation of base64_encode. We first transform the encoded data back to a binary stream, take off the previously appended binary digits according to the padding, at this point we would have a binary stream whose length is multiple of 8, the last step is to convert every 8 bits to a byte. >>> from base64 import b64decode >>> a = "VGhpcyBwdWxsIHJlcXVlc3QgaXMgcGFydCBvZiBIYWNrdG9iZXJmZXN0MjAh" >>> b = "aHR0cHM6Ly90b29scy5pZXRmLm9yZy9odG1sL3JmYzQ2NDg=" >>> c = "QQ==" >>> base64_decode(a) == b64decode(a) True >>> base64_decode(b) == b64decode(b) True >>> base64_decode(c) == b64decode(c) True >>> base64_decode("abc") Traceback (most recent call last): ... AssertionError: Incorrect padding """ # Make sure encoded_data is either a string or a bytes-like object if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str): raise TypeError( "argument should be a bytes-like object or ASCII string, not " f"'{encoded_data.__class__.__name__}'" ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(encoded_data, bytes): try: encoded_data = encoded_data.decode("utf-8") except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters") padding = encoded_data.count("=") # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one encoded_data = encoded_data[:-padding] binary_stream = "".join( bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data )[: -padding * 2] else: binary_stream = "".join( bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data ) data = [ int(binary_stream[index : index + 8], 2) for index in range(0, len(binary_stream), 8) ] return bytes(data) if __name__ == "__main__": import doctest doctest.testmod()
B64_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def base64_encode(data: bytes) -> bytes: """Encodes data according to RFC4648. The data is first transformed to binary and appended with binary digits so that its length becomes a multiple of 6, then each 6 binary digits will match a character in the B64_CHARSET string. The number of appended binary digits would later determine how many "=" signs should be added, the padding. For every 2 binary digits added, a "=" sign is added in the output. We can add any binary digits to make it a multiple of 6, for instance, consider the following example: "AA" -> 0010100100101001 -> 001010 010010 1001 As can be seen above, 2 more binary digits should be added, so there's 4 possibilities here: 00, 01, 10 or 11. That being said, Base64 encoding can be used in Steganography to hide data in these appended digits. >>> from base64 import b64encode >>> a = b"This pull request is part of Hacktoberfest20!" >>> b = b"https://tools.ietf.org/html/rfc4648" >>> c = b"A" >>> base64_encode(a) == b64encode(a) True >>> base64_encode(b) == b64encode(b) True >>> base64_encode(c) == b64encode(c) True >>> base64_encode("abc") Traceback (most recent call last): ... TypeError: a bytes-like object is required, not 'str' """ # Make sure the supplied data is a bytes-like object if not isinstance(data, bytes): raise TypeError( f"a bytes-like object is required, not '{data.__class__.__name__}'" ) binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data) padding_needed = len(binary_stream) % 6 != 0 if padding_needed: # The padding that will be added later padding = b"=" * ((6 - len(binary_stream) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(binary_stream) % 6) else: padding = b"" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6], 2)] for index in range(0, len(binary_stream), 6) ).encode() + padding ) def base64_decode(encoded_data: str) -> bytes: """Decodes data according to RFC4648. This does the reverse operation of base64_encode. We first transform the encoded data back to a binary stream, take off the previously appended binary digits according to the padding, at this point we would have a binary stream whose length is multiple of 8, the last step is to convert every 8 bits to a byte. >>> from base64 import b64decode >>> a = "VGhpcyBwdWxsIHJlcXVlc3QgaXMgcGFydCBvZiBIYWNrdG9iZXJmZXN0MjAh" >>> b = "aHR0cHM6Ly90b29scy5pZXRmLm9yZy9odG1sL3JmYzQ2NDg=" >>> c = "QQ==" >>> base64_decode(a) == b64decode(a) True >>> base64_decode(b) == b64decode(b) True >>> base64_decode(c) == b64decode(c) True >>> base64_decode("abc") Traceback (most recent call last): ... AssertionError: Incorrect padding """ # Make sure encoded_data is either a string or a bytes-like object if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str): raise TypeError( "argument should be a bytes-like object or ASCII string, not " f"'{encoded_data.__class__.__name__}'" ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(encoded_data, bytes): try: encoded_data = encoded_data.decode("utf-8") except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters") padding = encoded_data.count("=") # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one encoded_data = encoded_data[:-padding] binary_stream = "".join( bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data )[: -padding * 2] else: binary_stream = "".join( bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data ) data = [ int(binary_stream[index : index + 8], 2) for index in range(0, len(binary_stream), 8) ] return bytes(data) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import cv2 import numpy as np def get_neighbors_pixel( image: np.ndarray, x_coordinate: int, y_coordinate: int, center: int ) -> int: """ Comparing local neighborhood pixel value with threshold value of centre pixel. Exception is required when neighborhood value of a center pixel value is null. i.e. values present at boundaries. :param image: The image we're working with :param x_coordinate: x-coordinate of the pixel :param y_coordinate: The y coordinate of the pixel :param center: center pixel value :return: The value of the pixel is being returned. """ try: return int(image[x_coordinate][y_coordinate] >= center) except (IndexError, TypeError): return 0 def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int) -> int: """ It takes an image, an x and y coordinate, and returns the decimal value of the local binary patternof the pixel at that coordinate :param image: the image to be processed :param x_coordinate: x coordinate of the pixel :param y_coordinate: the y coordinate of the pixel :return: The decimal value of the binary value of the pixels around the center pixel. """ center = image[x_coordinate][y_coordinate] powers = [1, 2, 4, 8, 16, 32, 64, 128] # skip get_neighbors_pixel if center is null if center is None: return 0 # Starting from the top right, assigning value to pixels clockwise binary_values = [ get_neighbors_pixel(image, x_coordinate - 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate - 1, center), ] # Converting the binary value to decimal. return sum( binary_value * power for binary_value, power in zip(binary_values, powers) ) if __name__ == "__main__": # Reading the image and converting it to grayscale. image = cv2.imread( "digital_image_processing/image_data/lena.jpg", cv2.IMREAD_GRAYSCALE ) # Create a numpy array as the same height and width of read image lbp_image = np.zeros((image.shape[0], image.shape[1])) # Iterating through the image and calculating the # local binary pattern value for each pixel. for i in range(0, image.shape[0]): for j in range(0, image.shape[1]): lbp_image[i][j] = local_binary_value(image, i, j) cv2.imshow("local binary pattern", lbp_image) cv2.waitKey(0) cv2.destroyAllWindows()
import cv2 import numpy as np def get_neighbors_pixel( image: np.ndarray, x_coordinate: int, y_coordinate: int, center: int ) -> int: """ Comparing local neighborhood pixel value with threshold value of centre pixel. Exception is required when neighborhood value of a center pixel value is null. i.e. values present at boundaries. :param image: The image we're working with :param x_coordinate: x-coordinate of the pixel :param y_coordinate: The y coordinate of the pixel :param center: center pixel value :return: The value of the pixel is being returned. """ try: return int(image[x_coordinate][y_coordinate] >= center) except (IndexError, TypeError): return 0 def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int) -> int: """ It takes an image, an x and y coordinate, and returns the decimal value of the local binary patternof the pixel at that coordinate :param image: the image to be processed :param x_coordinate: x coordinate of the pixel :param y_coordinate: the y coordinate of the pixel :return: The decimal value of the binary value of the pixels around the center pixel. """ center = image[x_coordinate][y_coordinate] powers = [1, 2, 4, 8, 16, 32, 64, 128] # skip get_neighbors_pixel if center is null if center is None: return 0 # Starting from the top right, assigning value to pixels clockwise binary_values = [ get_neighbors_pixel(image, x_coordinate - 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate - 1, center), ] # Converting the binary value to decimal. return sum( binary_value * power for binary_value, power in zip(binary_values, powers) ) if __name__ == "__main__": # Reading the image and converting it to grayscale. image = cv2.imread( "digital_image_processing/image_data/lena.jpg", cv2.IMREAD_GRAYSCALE ) # Create a numpy array as the same height and width of read image lbp_image = np.zeros((image.shape[0], image.shape[1])) # Iterating through the image and calculating the # local binary pattern value for each pixel. for i in range(0, image.shape[0]): for j in range(0, image.shape[1]): lbp_image[i][j] = local_binary_value(image, i, j) cv2.imshow("local binary pattern", lbp_image) cv2.waitKey(0) cv2.destroyAllWindows()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import math from timeit import timeit def num_digits(n: int) -> int: """ Find the number of digits in a number. >>> num_digits(12345) 5 >>> num_digits(123) 3 >>> num_digits(0) 1 >>> num_digits(-1) 1 >>> num_digits(-123456) 6 """ digits = 0 n = abs(n) while True: n = n // 10 digits += 1 if n == 0: break return digits def num_digits_fast(n: int) -> int: """ Find the number of digits in a number. abs() is used as logarithm for negative numbers is not defined. >>> num_digits_fast(12345) 5 >>> num_digits_fast(123) 3 >>> num_digits_fast(0) 1 >>> num_digits_fast(-1) 1 >>> num_digits_fast(-123456) 6 """ return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1) def num_digits_faster(n: int) -> int: """ Find the number of digits in a number. abs() is used for negative numbers >>> num_digits_faster(12345) 5 >>> num_digits_faster(123) 3 >>> num_digits_faster(0) 1 >>> num_digits_faster(-1) 1 >>> num_digits_faster(-123456) 6 """ return len(str(abs(n))) def benchmark() -> None: """ Benchmark code for comparing 3 functions, with 3 different length int values. """ print("\nFor small_num = ", small_num, ":") print( "> num_digits()", "\t\tans =", num_digits(small_num), "\ttime =", timeit("z.num_digits(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_fast()", "\tans =", num_digits_fast(small_num), "\ttime =", timeit("z.num_digits_fast(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_faster()", "\tans =", num_digits_faster(small_num), "\ttime =", timeit("z.num_digits_faster(z.small_num)", setup="import __main__ as z"), "seconds", ) print("\nFor medium_num = ", medium_num, ":") print( "> num_digits()", "\t\tans =", num_digits(medium_num), "\ttime =", timeit("z.num_digits(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_fast()", "\tans =", num_digits_fast(medium_num), "\ttime =", timeit("z.num_digits_fast(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_faster()", "\tans =", num_digits_faster(medium_num), "\ttime =", timeit("z.num_digits_faster(z.medium_num)", setup="import __main__ as z"), "seconds", ) print("\nFor large_num = ", large_num, ":") print( "> num_digits()", "\t\tans =", num_digits(large_num), "\ttime =", timeit("z.num_digits(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_fast()", "\tans =", num_digits_fast(large_num), "\ttime =", timeit("z.num_digits_fast(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_faster()", "\tans =", num_digits_faster(large_num), "\ttime =", timeit("z.num_digits_faster(z.large_num)", setup="import __main__ as z"), "seconds", ) if __name__ == "__main__": small_num = 262144 medium_num = 1125899906842624 large_num = 1267650600228229401496703205376 benchmark() import doctest doctest.testmod()
import math from timeit import timeit def num_digits(n: int) -> int: """ Find the number of digits in a number. >>> num_digits(12345) 5 >>> num_digits(123) 3 >>> num_digits(0) 1 >>> num_digits(-1) 1 >>> num_digits(-123456) 6 """ digits = 0 n = abs(n) while True: n = n // 10 digits += 1 if n == 0: break return digits def num_digits_fast(n: int) -> int: """ Find the number of digits in a number. abs() is used as logarithm for negative numbers is not defined. >>> num_digits_fast(12345) 5 >>> num_digits_fast(123) 3 >>> num_digits_fast(0) 1 >>> num_digits_fast(-1) 1 >>> num_digits_fast(-123456) 6 """ return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1) def num_digits_faster(n: int) -> int: """ Find the number of digits in a number. abs() is used for negative numbers >>> num_digits_faster(12345) 5 >>> num_digits_faster(123) 3 >>> num_digits_faster(0) 1 >>> num_digits_faster(-1) 1 >>> num_digits_faster(-123456) 6 """ return len(str(abs(n))) def benchmark() -> None: """ Benchmark code for comparing 3 functions, with 3 different length int values. """ print("\nFor small_num = ", small_num, ":") print( "> num_digits()", "\t\tans =", num_digits(small_num), "\ttime =", timeit("z.num_digits(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_fast()", "\tans =", num_digits_fast(small_num), "\ttime =", timeit("z.num_digits_fast(z.small_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_faster()", "\tans =", num_digits_faster(small_num), "\ttime =", timeit("z.num_digits_faster(z.small_num)", setup="import __main__ as z"), "seconds", ) print("\nFor medium_num = ", medium_num, ":") print( "> num_digits()", "\t\tans =", num_digits(medium_num), "\ttime =", timeit("z.num_digits(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_fast()", "\tans =", num_digits_fast(medium_num), "\ttime =", timeit("z.num_digits_fast(z.medium_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_faster()", "\tans =", num_digits_faster(medium_num), "\ttime =", timeit("z.num_digits_faster(z.medium_num)", setup="import __main__ as z"), "seconds", ) print("\nFor large_num = ", large_num, ":") print( "> num_digits()", "\t\tans =", num_digits(large_num), "\ttime =", timeit("z.num_digits(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_fast()", "\tans =", num_digits_fast(large_num), "\ttime =", timeit("z.num_digits_fast(z.large_num)", setup="import __main__ as z"), "seconds", ) print( "> num_digits_faster()", "\tans =", num_digits_faster(large_num), "\ttime =", timeit("z.num_digits_faster(z.large_num)", setup="import __main__ as z"), "seconds", ) if __name__ == "__main__": small_num = 262144 medium_num = 1125899906842624 large_num = 1267650600228229401496703205376 benchmark() import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Prize Strings Problem 191 A particular school offers cash rewards to children with good attendance and punctuality. If they are absent for three consecutive days or late on more than one occasion then they forfeit their prize. During an n-day period a trinary string is formed for each child consisting of L's (late), O's (on time), and A's (absent). Although there are eighty-one trinary strings for a 4-day period that can be formed, exactly forty-three strings would lead to a prize: OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA LAOO LAOA LAAO How many "prize" strings exist over a 30-day period? References: - The original Project Euler project page: https://projecteuler.net/problem=191 """ cache: dict[tuple[int, int, int], int] = {} def _calculate(days: int, absent: int, late: int) -> int: """ A small helper function for the recursion, mainly to have a clean interface for the solution() function below. It should get called with the number of days (corresponding to the desired length of the 'prize strings'), and the initial values for the number of consecutive absent days and number of total late days. >>> _calculate(days=4, absent=0, late=0) 43 >>> _calculate(days=30, absent=2, late=0) 0 >>> _calculate(days=30, absent=1, late=0) 98950096 """ # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on key = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one state_late = _calculate(days - 1, absent, late + 1) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 state_absent = _calculate(days - 1, absent + 1, 0) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter state_ontime = _calculate(days - 1, absent, 0) prizestrings = state_late + state_absent + state_ontime cache[key] = prizestrings return prizestrings def solution(days: int = 30) -> int: """ Returns the number of possible prize strings for a particular number of days, using a simple recursive function with caching to speed it up. >>> solution() 1918080160 >>> solution(4) 43 """ return _calculate(days, absent=0, late=0) if __name__ == "__main__": print(solution())
""" Prize Strings Problem 191 A particular school offers cash rewards to children with good attendance and punctuality. If they are absent for three consecutive days or late on more than one occasion then they forfeit their prize. During an n-day period a trinary string is formed for each child consisting of L's (late), O's (on time), and A's (absent). Although there are eighty-one trinary strings for a 4-day period that can be formed, exactly forty-three strings would lead to a prize: OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA LAOO LAOA LAAO How many "prize" strings exist over a 30-day period? References: - The original Project Euler project page: https://projecteuler.net/problem=191 """ cache: dict[tuple[int, int, int], int] = {} def _calculate(days: int, absent: int, late: int) -> int: """ A small helper function for the recursion, mainly to have a clean interface for the solution() function below. It should get called with the number of days (corresponding to the desired length of the 'prize strings'), and the initial values for the number of consecutive absent days and number of total late days. >>> _calculate(days=4, absent=0, late=0) 43 >>> _calculate(days=30, absent=2, late=0) 0 >>> _calculate(days=30, absent=1, late=0) 98950096 """ # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on key = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one state_late = _calculate(days - 1, absent, late + 1) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 state_absent = _calculate(days - 1, absent + 1, 0) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter state_ontime = _calculate(days - 1, absent, 0) prizestrings = state_late + state_absent + state_ontime cache[key] = prizestrings return prizestrings def solution(days: int = 30) -> int: """ Returns the number of possible prize strings for a particular number of days, using a simple recursive function with caching to speed it up. >>> solution() 1918080160 >>> solution(4) 43 """ return _calculate(days, absent=0, late=0) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import shutil import requests def get_apod_data(api_key: str, download: bool = False, path: str = ".") -> dict: """ Get the APOD(Astronomical Picture of the day) data Get your API Key from: https://api.nasa.gov/ """ url = "https://api.nasa.gov/planetary/apod" return requests.get(url, params={"api_key": api_key}).json() def save_apod(api_key: str, path: str = ".") -> dict: apod_data = get_apod_data(api_key) img_url = apod_data["url"] img_name = img_url.split("/")[-1] response = requests.get(img_url, stream=True) with open(f"{path}/{img_name}", "wb+") as img_file: shutil.copyfileobj(response.raw, img_file) del response return apod_data def get_archive_data(query: str) -> dict: """ Get the data of a particular query from NASA archives """ url = "https://images-api.nasa.gov/search" return requests.get(url, params={"q": query}).json() if __name__ == "__main__": print(save_apod("YOUR API KEY")) apollo_2011_items = get_archive_data("apollo 2011")["collection"]["items"] print(apollo_2011_items[0]["data"][0]["description"])
import shutil import requests def get_apod_data(api_key: str, download: bool = False, path: str = ".") -> dict: """ Get the APOD(Astronomical Picture of the day) data Get your API Key from: https://api.nasa.gov/ """ url = "https://api.nasa.gov/planetary/apod" return requests.get(url, params={"api_key": api_key}).json() def save_apod(api_key: str, path: str = ".") -> dict: apod_data = get_apod_data(api_key) img_url = apod_data["url"] img_name = img_url.split("/")[-1] response = requests.get(img_url, stream=True) with open(f"{path}/{img_name}", "wb+") as img_file: shutil.copyfileobj(response.raw, img_file) del response return apod_data def get_archive_data(query: str) -> dict: """ Get the data of a particular query from NASA archives """ url = "https://images-api.nasa.gov/search" return requests.get(url, params={"q": query}).json() if __name__ == "__main__": print(save_apod("YOUR API KEY")) apollo_2011_items = get_archive_data("apollo 2011")["collection"]["items"] print(apollo_2011_items[0]["data"][0]["description"])
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another 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 _ 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 _ 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__": import doctest doctest.testmod() 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 _ 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 _ 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__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 74: https://projecteuler.net/problem=74 The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145: 1! + 4! + 5! = 1 + 24 + 120 = 145 Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist: 169 → 363601 → 1454 → 169 871 → 45361 → 871 872 → 45362 → 872 It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example, 69 → 363600 → 1454 → 169 → 363601 (→ 1454) 78 → 45360 → 871 → 45361 (→ 871) 540 → 145 (→ 145) Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms. How many chains, with a starting number below one million, contain exactly sixty non-repeating terms? """ DIGIT_FACTORIALS = { "0": 1, "1": 1, "2": 2, "3": 6, "4": 24, "5": 120, "6": 720, "7": 5040, "8": 40320, "9": 362880, } CACHE_SUM_DIGIT_FACTORIALS = {145: 145} CHAIN_LENGTH_CACHE = { 145: 0, 169: 3, 36301: 3, 1454: 3, 871: 2, 45361: 2, 872: 2, } def sum_digit_factorials(n: int) -> int: """ Return the sum of the factorial of the digits of n. >>> sum_digit_factorials(145) 145 >>> sum_digit_factorials(45361) 871 >>> sum_digit_factorials(540) 145 """ if n in CACHE_SUM_DIGIT_FACTORIALS: return CACHE_SUM_DIGIT_FACTORIALS[n] ret = sum(DIGIT_FACTORIALS[let] for let in str(n)) CACHE_SUM_DIGIT_FACTORIALS[n] = ret return ret def chain_length(n: int, previous: set = None) -> int: """ Calculate the length of the chain of non-repeating terms starting with n. Previous is a set containing the previous member of the chain. >>> chain_length(10101) 11 >>> chain_length(555) 20 >>> chain_length(178924) 39 """ previous = previous or set() if n in CHAIN_LENGTH_CACHE: return CHAIN_LENGTH_CACHE[n] next_number = sum_digit_factorials(n) if next_number in previous: CHAIN_LENGTH_CACHE[n] = 0 return 0 else: previous.add(n) ret = 1 + chain_length(next_number, previous) CHAIN_LENGTH_CACHE[n] = ret return ret def solution(num_terms: int = 60, max_start: int = 1000000) -> int: """ Return the number of chains with a starting number below one million which contain exactly n non-repeating terms. >>> solution(10,1000) 28 """ return sum(1 for i in range(1, max_start) if chain_length(i) == num_terms) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 74: https://projecteuler.net/problem=74 The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145: 1! + 4! + 5! = 1 + 24 + 120 = 145 Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist: 169 → 363601 → 1454 → 169 871 → 45361 → 871 872 → 45362 → 872 It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example, 69 → 363600 → 1454 → 169 → 363601 (→ 1454) 78 → 45360 → 871 → 45361 (→ 871) 540 → 145 (→ 145) Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms. How many chains, with a starting number below one million, contain exactly sixty non-repeating terms? """ DIGIT_FACTORIALS = { "0": 1, "1": 1, "2": 2, "3": 6, "4": 24, "5": 120, "6": 720, "7": 5040, "8": 40320, "9": 362880, } CACHE_SUM_DIGIT_FACTORIALS = {145: 145} CHAIN_LENGTH_CACHE = { 145: 0, 169: 3, 36301: 3, 1454: 3, 871: 2, 45361: 2, 872: 2, } def sum_digit_factorials(n: int) -> int: """ Return the sum of the factorial of the digits of n. >>> sum_digit_factorials(145) 145 >>> sum_digit_factorials(45361) 871 >>> sum_digit_factorials(540) 145 """ if n in CACHE_SUM_DIGIT_FACTORIALS: return CACHE_SUM_DIGIT_FACTORIALS[n] ret = sum(DIGIT_FACTORIALS[let] for let in str(n)) CACHE_SUM_DIGIT_FACTORIALS[n] = ret return ret def chain_length(n: int, previous: set = None) -> int: """ Calculate the length of the chain of non-repeating terms starting with n. Previous is a set containing the previous member of the chain. >>> chain_length(10101) 11 >>> chain_length(555) 20 >>> chain_length(178924) 39 """ previous = previous or set() if n in CHAIN_LENGTH_CACHE: return CHAIN_LENGTH_CACHE[n] next_number = sum_digit_factorials(n) if next_number in previous: CHAIN_LENGTH_CACHE[n] = 0 return 0 else: previous.add(n) ret = 1 + chain_length(next_number, previous) CHAIN_LENGTH_CACHE[n] = ret return ret def solution(num_terms: int = 60, max_start: int = 1000000) -> int: """ Return the number of chains with a starting number below one million which contain exactly n non-repeating terms. >>> solution(10,1000) 28 """ return sum(1 for i in range(1, max_start) if chain_length(i) == num_terms) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def text_justification(word: str, max_width: int) -> list: """ Will format the string such that each line has exactly (max_width) characters and is fully (left and right) justified, and return the list of justified text. example 1: string = "This is an example of text justification." max_width = 16 output = ['This is an', 'example of text', 'justification. '] >>> text_justification("This is an example of text justification.", 16) ['This is an', 'example of text', 'justification. '] example 2: string = "Two roads diverged in a yellow wood" max_width = 16 output = ['Two roads', 'diverged in a', 'yellow wood '] >>> text_justification("Two roads diverged in a yellow wood", 16) ['Two roads', 'diverged in a', 'yellow wood '] Time complexity: O(m*n) Space complexity: O(m*n) """ # Converting string into list of strings split by a space words = word.split() def justify(line: list, width: int, max_width: int) -> str: overall_spaces_count = max_width - width words_count = len(line) if len(line) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: spaces_to_insert_between_words = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] num_spaces_between_words_list = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] spaces_count_in_locations = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(spaces_count_in_locations): num_spaces_between_words_list[i] += 1 aligned_words_list = [] for i in range(spaces_to_insert_between_words): # add the word aligned_words_list.append(line[i]) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * " ") # just add the last word to the sentence aligned_words_list.append(line[-1]) # join the aligned words list to form a justified line return "".join(aligned_words_list) answer = [] line: list[str] = [] width = 0 for word in words: if width + len(word) + len(line) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(word) width += len(word) else: # justify the line and add it to result answer.append(justify(line, width, max_width)) # reset new line and new width line, width = [word], len(word) remaining_spaces = max_width - width - len(line) answer.append(" ".join(line) + (remaining_spaces + 1) * " ") return answer if __name__ == "__main__": from doctest import testmod testmod()
def text_justification(word: str, max_width: int) -> list: """ Will format the string such that each line has exactly (max_width) characters and is fully (left and right) justified, and return the list of justified text. example 1: string = "This is an example of text justification." max_width = 16 output = ['This is an', 'example of text', 'justification. '] >>> text_justification("This is an example of text justification.", 16) ['This is an', 'example of text', 'justification. '] example 2: string = "Two roads diverged in a yellow wood" max_width = 16 output = ['Two roads', 'diverged in a', 'yellow wood '] >>> text_justification("Two roads diverged in a yellow wood", 16) ['Two roads', 'diverged in a', 'yellow wood '] Time complexity: O(m*n) Space complexity: O(m*n) """ # Converting string into list of strings split by a space words = word.split() def justify(line: list, width: int, max_width: int) -> str: overall_spaces_count = max_width - width words_count = len(line) if len(line) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: spaces_to_insert_between_words = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] num_spaces_between_words_list = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] spaces_count_in_locations = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(spaces_count_in_locations): num_spaces_between_words_list[i] += 1 aligned_words_list = [] for i in range(spaces_to_insert_between_words): # add the word aligned_words_list.append(line[i]) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * " ") # just add the last word to the sentence aligned_words_list.append(line[-1]) # join the aligned words list to form a justified line return "".join(aligned_words_list) answer = [] line: list[str] = [] width = 0 for word in words: if width + len(word) + len(line) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(word) width += len(word) else: # justify the line and add it to result answer.append(justify(line, width, max_width)) # reset new line and new width line, width = [word], len(word) remaining_spaces = max_width - width - len(line) answer.append(" ".join(line) + (remaining_spaces + 1) * " ") return answer if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Convert a string of characters to a sequence of numbers corresponding to the character's position in the alphabet. https://www.dcode.fr/letter-number-cipher http://bestcodes.weebly.com/a1z26.html """ from __future__ import annotations def encode(plain: str) -> list[int]: """ >>> encode("myname") [13, 25, 14, 1, 13, 5] """ return [ord(elem) - 96 for elem in plain] def decode(encoded: list[int]) -> str: """ >>> decode([13, 25, 14, 1, 13, 5]) 'myname' """ return "".join(chr(elem + 96) for elem in encoded) def main() -> None: encoded = encode(input("-> ").strip().lower()) print("Encoded: ", encoded) print("Decoded:", decode(encoded)) if __name__ == "__main__": main()
""" Convert a string of characters to a sequence of numbers corresponding to the character's position in the alphabet. https://www.dcode.fr/letter-number-cipher http://bestcodes.weebly.com/a1z26.html """ from __future__ import annotations def encode(plain: str) -> list[int]: """ >>> encode("myname") [13, 25, 14, 1, 13, 5] """ return [ord(elem) - 96 for elem in plain] def decode(encoded: list[int]) -> str: """ >>> decode([13, 25, 14, 1, 13, 5]) 'myname' """ return "".join(chr(elem + 96) for elem in encoded) def main() -> None: encoded = encode(input("-> ").strip().lower()) print("Encoded: ", encoded) print("Decoded:", decode(encoded)) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 from __future__ import annotations import json import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent headers = {"UserAgent": UserAgent().random} def extract_user_profile(script) -> dict: """ May raise json.decoder.JSONDecodeError """ data = script.contents[0] info = json.loads(data[data.find('{"config"') : -1]) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class InstagramUser: """ Class Instagram crawl instagram user information Usage: (doctest failing on GitHub Actions) # >>> instagram_user = InstagramUser("github") # >>> instagram_user.is_verified True # >>> instagram_user.biography 'Built for developers.' """ def __init__(self, username): self.url = f"https://www.instagram.com/{username}/" self.user_data = self.get_json() def get_json(self) -> dict: """ Return a dict of user information """ html = requests.get(self.url, headers=headers).text scripts = BeautifulSoup(html, "html.parser").find_all("script") try: return extract_user_profile(scripts[4]) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3]) def __repr__(self) -> str: return f"{self.__class__.__name__}('{self.username}')" def __str__(self) -> str: return f"{self.fullname} ({self.username}) is {self.biography}" @property def username(self) -> str: return self.user_data["username"] @property def fullname(self) -> str: return self.user_data["full_name"] @property def biography(self) -> str: return self.user_data["biography"] @property def email(self) -> str: return self.user_data["business_email"] @property def website(self) -> str: return self.user_data["external_url"] @property def number_of_followers(self) -> int: return self.user_data["edge_followed_by"]["count"] @property def number_of_followings(self) -> int: return self.user_data["edge_follow"]["count"] @property def number_of_posts(self) -> int: return self.user_data["edge_owner_to_timeline_media"]["count"] @property def profile_picture_url(self) -> str: return self.user_data["profile_pic_url_hd"] @property def is_verified(self) -> bool: return self.user_data["is_verified"] @property def is_private(self) -> bool: return self.user_data["is_private"] def test_instagram_user(username: str = "github") -> None: """ A self running doctest >>> test_instagram_user() """ import os if os.environ.get("CI"): return None # test failing on GitHub Actions instagram_user = InstagramUser(username) assert instagram_user.user_data assert isinstance(instagram_user.user_data, dict) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "[email protected]" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram.") assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() instagram_user = InstagramUser("github") print(instagram_user) print(f"{instagram_user.number_of_posts = }") print(f"{instagram_user.number_of_followers = }") print(f"{instagram_user.number_of_followings = }") print(f"{instagram_user.email = }") print(f"{instagram_user.website = }") print(f"{instagram_user.profile_picture_url = }") print(f"{instagram_user.is_verified = }") print(f"{instagram_user.is_private = }")
#!/usr/bin/env python3 from __future__ import annotations import json import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent headers = {"UserAgent": UserAgent().random} def extract_user_profile(script) -> dict: """ May raise json.decoder.JSONDecodeError """ data = script.contents[0] info = json.loads(data[data.find('{"config"') : -1]) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class InstagramUser: """ Class Instagram crawl instagram user information Usage: (doctest failing on GitHub Actions) # >>> instagram_user = InstagramUser("github") # >>> instagram_user.is_verified True # >>> instagram_user.biography 'Built for developers.' """ def __init__(self, username): self.url = f"https://www.instagram.com/{username}/" self.user_data = self.get_json() def get_json(self) -> dict: """ Return a dict of user information """ html = requests.get(self.url, headers=headers).text scripts = BeautifulSoup(html, "html.parser").find_all("script") try: return extract_user_profile(scripts[4]) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3]) def __repr__(self) -> str: return f"{self.__class__.__name__}('{self.username}')" def __str__(self) -> str: return f"{self.fullname} ({self.username}) is {self.biography}" @property def username(self) -> str: return self.user_data["username"] @property def fullname(self) -> str: return self.user_data["full_name"] @property def biography(self) -> str: return self.user_data["biography"] @property def email(self) -> str: return self.user_data["business_email"] @property def website(self) -> str: return self.user_data["external_url"] @property def number_of_followers(self) -> int: return self.user_data["edge_followed_by"]["count"] @property def number_of_followings(self) -> int: return self.user_data["edge_follow"]["count"] @property def number_of_posts(self) -> int: return self.user_data["edge_owner_to_timeline_media"]["count"] @property def profile_picture_url(self) -> str: return self.user_data["profile_pic_url_hd"] @property def is_verified(self) -> bool: return self.user_data["is_verified"] @property def is_private(self) -> bool: return self.user_data["is_private"] def test_instagram_user(username: str = "github") -> None: """ A self running doctest >>> test_instagram_user() """ import os if os.environ.get("CI"): return None # test failing on GitHub Actions instagram_user = InstagramUser(username) assert instagram_user.user_data assert isinstance(instagram_user.user_data, dict) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "[email protected]" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram.") assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() instagram_user = InstagramUser("github") print(instagram_user) print(f"{instagram_user.number_of_posts = }") print(f"{instagram_user.number_of_followers = }") print(f"{instagram_user.number_of_followings = }") print(f"{instagram_user.email = }") print(f"{instagram_user.website = }") print(f"{instagram_user.profile_picture_url = }") print(f"{instagram_user.is_verified = }") print(f"{instagram_user.is_private = }")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort This is a non-parallelized implementation of odd-even transposition sort. Normally the swaps in each set happen simultaneously, without that the algorithm is no better than bubble sort. """ def odd_even_transposition(arr: list) -> list: """ >>> odd_even_transposition([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> odd_even_transposition([13, 11, 18, 0, -1]) [-1, 0, 11, 13, 18] >>> odd_even_transposition([-.1, 1.1, .1, -2.9]) [-2.9, -0.1, 0.1, 1.1] """ arr_size = len(arr) for _ in range(arr_size): for i in range(_ % 2, arr_size - 1, 2): if arr[i + 1] < arr[i]: arr[i], arr[i + 1] = arr[i + 1], arr[i] return arr if __name__ == "__main__": arr = list(range(10, 0, -1)) print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}")
""" Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort This is a non-parallelized implementation of odd-even transposition sort. Normally the swaps in each set happen simultaneously, without that the algorithm is no better than bubble sort. """ def odd_even_transposition(arr: list) -> list: """ >>> odd_even_transposition([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> odd_even_transposition([13, 11, 18, 0, -1]) [-1, 0, 11, 13, 18] >>> odd_even_transposition([-.1, 1.1, .1, -2.9]) [-2.9, -0.1, 0.1, 1.1] """ arr_size = len(arr) for _ in range(arr_size): for i in range(_ % 2, arr_size - 1, 2): if arr[i + 1] < arr[i]: arr[i], arr[i + 1] = arr[i + 1], arr[i] return arr if __name__ == "__main__": arr = list(range(10, 0, -1)) print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def quick_sort(data: list) -> list: """ >>> for data in ([2, 1, 0], [2.2, 1.1, 0], "quick_sort"): ... quick_sort(data) == sorted(data) True True True """ if len(data) <= 1: return data else: return ( quick_sort([e for e in data[1:] if e <= data[0]]) + [data[0]] + quick_sort([e for e in data[1:] if e > data[0]]) ) if __name__ == "__main__": import doctest doctest.testmod()
def quick_sort(data: list) -> list: """ >>> for data in ([2, 1, 0], [2.2, 1.1, 0], "quick_sort"): ... quick_sort(data) == sorted(data) True True True """ if len(data) <= 1: return data else: return ( quick_sort([e for e in data[1:] if e <= data[0]]) + [data[0]] + quick_sort([e for e in data[1:] if e > data[0]]) ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another 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
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Source : https://computersciencewiki.org/index.php/Max-pooling_/_Pooling # Importing the libraries import numpy as np from PIL import Image # Maxpooling Function def maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform maxpooling on the input array of 2D matrix(image) Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of maxpooled matrix Sample Input Output: >>> maxpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) array([[ 6., 8.], [14., 16.]]) >>> maxpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) array([[241., 180.], [241., 157.]]) """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix maxpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape updated_arr = np.zeros((maxpool_shape, maxpool_shape)) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix updated_arr[mat_i][mat_j] = np.max(arr[i : i + size, j : j + size]) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Averagepooling Function def avgpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform avgpooling on the input array of 2D matrix(image) Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of avgpooled matrix Sample Input Output: >>> avgpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) array([[ 3., 5.], [11., 13.]]) >>> avgpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) array([[161., 102.], [114., 69.]]) """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix avgpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape updated_arr = np.zeros((avgpool_shape, avgpool_shape)) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix updated_arr[mat_i][mat_j] = int(np.average(arr[i : i + size, j : j + size])) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image image = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
# Source : https://computersciencewiki.org/index.php/Max-pooling_/_Pooling # Importing the libraries import numpy as np from PIL import Image # Maxpooling Function def maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform maxpooling on the input array of 2D matrix(image) Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of maxpooled matrix Sample Input Output: >>> maxpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) array([[ 6., 8.], [14., 16.]]) >>> maxpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) array([[241., 180.], [241., 157.]]) """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix maxpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape updated_arr = np.zeros((maxpool_shape, maxpool_shape)) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix updated_arr[mat_i][mat_j] = np.max(arr[i : i + size, j : j + size]) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Averagepooling Function def avgpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform avgpooling on the input array of 2D matrix(image) Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of avgpooled matrix Sample Input Output: >>> avgpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) array([[ 3., 5.], [11., 13.]]) >>> avgpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) array([[161., 102.], [114., 69.]]) """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix avgpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape updated_arr = np.zeros((avgpool_shape, avgpool_shape)) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix updated_arr[mat_i][mat_j] = int(np.average(arr[i : i + size, j : j + size])) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image image = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another 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/Self-organizing_map """ import math class SelfOrganizingMap: def get_winner(self, weights: list[list[float]], sample: list[int]) -> int: """ Compute the winning vector by Euclidean distance >>> SelfOrganizingMap().get_winner([[1, 2, 3], [4, 5, 6]], [1, 2, 3]) 1 """ d0 = 0.0 d1 = 0.0 for i in range(len(sample)): d0 += math.pow((sample[i] - weights[0][i]), 2) d1 += math.pow((sample[i] - weights[1][i]), 2) return 0 if d0 > d1 else 1 return 0 def update( self, weights: list[list[int | float]], sample: list[int], j: int, alpha: float ) -> list[list[int | float]]: """ Update the winning vector. >>> SelfOrganizingMap().update([[1, 2, 3], [4, 5, 6]], [1, 2, 3], 1, 0.1) [[1, 2, 3], [3.7, 4.7, 6]] """ for i in range(len(weights)): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights # Driver code def main() -> None: # Training Examples ( m, n ) training_samples = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) weights = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training self_organizing_map = SelfOrganizingMap() epochs = 3 alpha = 0.5 for _ in range(epochs): for j in range(len(training_samples)): # training sample sample = training_samples[j] # Compute the winning vector winner = self_organizing_map.get_winner(weights, sample) # Update the winning vector weights = self_organizing_map.update(weights, sample, winner, alpha) # classify test sample sample = [0, 0, 0, 1] winner = self_organizing_map.get_winner(weights, sample) # results print(f"Clusters that the test sample belongs to : {winner}") print(f"Weights that have been trained : {weights}") # running the main() function if __name__ == "__main__": main()
""" https://en.wikipedia.org/wiki/Self-organizing_map """ import math class SelfOrganizingMap: def get_winner(self, weights: list[list[float]], sample: list[int]) -> int: """ Compute the winning vector by Euclidean distance >>> SelfOrganizingMap().get_winner([[1, 2, 3], [4, 5, 6]], [1, 2, 3]) 1 """ d0 = 0.0 d1 = 0.0 for i in range(len(sample)): d0 += math.pow((sample[i] - weights[0][i]), 2) d1 += math.pow((sample[i] - weights[1][i]), 2) return 0 if d0 > d1 else 1 return 0 def update( self, weights: list[list[int | float]], sample: list[int], j: int, alpha: float ) -> list[list[int | float]]: """ Update the winning vector. >>> SelfOrganizingMap().update([[1, 2, 3], [4, 5, 6]], [1, 2, 3], 1, 0.1) [[1, 2, 3], [3.7, 4.7, 6]] """ for i in range(len(weights)): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights # Driver code def main() -> None: # Training Examples ( m, n ) training_samples = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) weights = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training self_organizing_map = SelfOrganizingMap() epochs = 3 alpha = 0.5 for _ in range(epochs): for j in range(len(training_samples)): # training sample sample = training_samples[j] # Compute the winning vector winner = self_organizing_map.get_winner(weights, sample) # Update the winning vector weights = self_organizing_map.update(weights, sample, winner, alpha) # classify test sample sample = [0, 0, 0, 1] winner = self_organizing_map.get_winner(weights, sample) # results print(f"Clusters that the test sample belongs to : {winner}") print(f"Weights that have been trained : {weights}") # running the main() function if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from xml.dom import NotFoundErr import requests from bs4 import BeautifulSoup, NavigableString from fake_useragent import UserAgent BASE_URL = "https://ww1.gogoanime2.org" def search_scraper(anime_name: str) -> list: """[summary] Take an url and return list of anime after scraping the site. >>> type(search_scraper("demon_slayer")) <class 'list'> Args: anime_name (str): [Name of anime] Raises: e: [Raises exception on failure] Returns: [list]: [List of animes] """ # concat the name to form the search url. search_url = f"{BASE_URL}/search/{anime_name}" response = requests.get( search_url, headers={"UserAgent": UserAgent().chrome} ) # request the url. # Is the response ok? response.raise_for_status() # parse with soup. soup = BeautifulSoup(response.text, "html.parser") # get list of anime anime_ul = soup.find("ul", {"class": "items"}) anime_li = anime_ul.children # for each anime, insert to list. the name and url. anime_list = [] for anime in anime_li: if not isinstance(anime, NavigableString): try: anime_url, anime_title = ( anime.find("a")["href"], anime.find("a")["title"], ) anime_list.append( { "title": anime_title, "url": anime_url, } ) except (NotFoundErr, KeyError): pass return anime_list def search_anime_episode_list(episode_endpoint: str) -> list: """[summary] Take an url and return list of episodes after scraping the site for an url. >>> type(search_anime_episode_list("/anime/kimetsu-no-yaiba")) <class 'list'> Args: episode_endpoint (str): [Endpoint of episode] Raises: e: [description] Returns: [list]: [List of episodes] """ request_url = f"{BASE_URL}{episode_endpoint}" response = requests.get(url=request_url, headers={"UserAgent": UserAgent().chrome}) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") # With this id. get the episode list. episode_page_ul = soup.find("ul", {"id": "episode_related"}) episode_page_li = episode_page_ul.children episode_list = [] for episode in episode_page_li: try: if not isinstance(episode, NavigableString): episode_list.append( { "title": episode.find("div", {"class": "name"}).text.replace( " ", "" ), "url": episode.find("a")["href"], } ) except (KeyError, NotFoundErr): pass return episode_list def get_anime_episode(episode_endpoint: str) -> list: """[summary] Get click url and download url from episode url >>> type(get_anime_episode("/watch/kimetsu-no-yaiba/1")) <class 'list'> Args: episode_endpoint (str): [Endpoint of episode] Raises: e: [description] Returns: [list]: [List of download and watch url] """ episode_page_url = f"{BASE_URL}{episode_endpoint}" response = requests.get( url=episode_page_url, headers={"User-Agent": UserAgent().chrome} ) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") try: episode_url = soup.find("iframe", {"id": "playerframe"})["src"] download_url = episode_url.replace("/embed/", "/playlist/") + ".m3u8" except (KeyError, NotFoundErr) as e: raise e return [f"{BASE_URL}{episode_url}", f"{BASE_URL}{download_url}"] if __name__ == "__main__": anime_name = input("Enter anime name: ").strip() anime_list = search_scraper(anime_name) print("\n") if len(anime_list) == 0: print("No anime found with this name") else: print(f"Found {len(anime_list)} results: ") for (i, anime) in enumerate(anime_list): anime_title = anime["title"] print(f"{i+1}. {anime_title}") anime_choice = int(input("\nPlease choose from the following list: ").strip()) chosen_anime = anime_list[anime_choice - 1] print(f"You chose {chosen_anime['title']}. Searching for episodes...") episode_list = search_anime_episode_list(chosen_anime["url"]) if len(episode_list) == 0: print("No episode found for this anime") else: print(f"Found {len(episode_list)} results: ") for (i, episode) in enumerate(episode_list): print(f"{i+1}. {episode['title']}") episode_choice = int(input("\nChoose an episode by serial no: ").strip()) chosen_episode = episode_list[episode_choice - 1] print(f"You chose {chosen_episode['title']}. Searching...") episode_url, download_url = get_anime_episode(chosen_episode["url"]) print(f"\nTo watch, ctrl+click on {episode_url}.") print(f"To download, ctrl+click on {download_url}.")
from xml.dom import NotFoundErr import requests from bs4 import BeautifulSoup, NavigableString from fake_useragent import UserAgent BASE_URL = "https://ww1.gogoanime2.org" def search_scraper(anime_name: str) -> list: """[summary] Take an url and return list of anime after scraping the site. >>> type(search_scraper("demon_slayer")) <class 'list'> Args: anime_name (str): [Name of anime] Raises: e: [Raises exception on failure] Returns: [list]: [List of animes] """ # concat the name to form the search url. search_url = f"{BASE_URL}/search/{anime_name}" response = requests.get( search_url, headers={"UserAgent": UserAgent().chrome} ) # request the url. # Is the response ok? response.raise_for_status() # parse with soup. soup = BeautifulSoup(response.text, "html.parser") # get list of anime anime_ul = soup.find("ul", {"class": "items"}) anime_li = anime_ul.children # for each anime, insert to list. the name and url. anime_list = [] for anime in anime_li: if not isinstance(anime, NavigableString): try: anime_url, anime_title = ( anime.find("a")["href"], anime.find("a")["title"], ) anime_list.append( { "title": anime_title, "url": anime_url, } ) except (NotFoundErr, KeyError): pass return anime_list def search_anime_episode_list(episode_endpoint: str) -> list: """[summary] Take an url and return list of episodes after scraping the site for an url. >>> type(search_anime_episode_list("/anime/kimetsu-no-yaiba")) <class 'list'> Args: episode_endpoint (str): [Endpoint of episode] Raises: e: [description] Returns: [list]: [List of episodes] """ request_url = f"{BASE_URL}{episode_endpoint}" response = requests.get(url=request_url, headers={"UserAgent": UserAgent().chrome}) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") # With this id. get the episode list. episode_page_ul = soup.find("ul", {"id": "episode_related"}) episode_page_li = episode_page_ul.children episode_list = [] for episode in episode_page_li: try: if not isinstance(episode, NavigableString): episode_list.append( { "title": episode.find("div", {"class": "name"}).text.replace( " ", "" ), "url": episode.find("a")["href"], } ) except (KeyError, NotFoundErr): pass return episode_list def get_anime_episode(episode_endpoint: str) -> list: """[summary] Get click url and download url from episode url >>> type(get_anime_episode("/watch/kimetsu-no-yaiba/1")) <class 'list'> Args: episode_endpoint (str): [Endpoint of episode] Raises: e: [description] Returns: [list]: [List of download and watch url] """ episode_page_url = f"{BASE_URL}{episode_endpoint}" response = requests.get( url=episode_page_url, headers={"User-Agent": UserAgent().chrome} ) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") try: episode_url = soup.find("iframe", {"id": "playerframe"})["src"] download_url = episode_url.replace("/embed/", "/playlist/") + ".m3u8" except (KeyError, NotFoundErr) as e: raise e return [f"{BASE_URL}{episode_url}", f"{BASE_URL}{download_url}"] if __name__ == "__main__": anime_name = input("Enter anime name: ").strip() anime_list = search_scraper(anime_name) print("\n") if len(anime_list) == 0: print("No anime found with this name") else: print(f"Found {len(anime_list)} results: ") for (i, anime) in enumerate(anime_list): anime_title = anime["title"] print(f"{i+1}. {anime_title}") anime_choice = int(input("\nPlease choose from the following list: ").strip()) chosen_anime = anime_list[anime_choice - 1] print(f"You chose {chosen_anime['title']}. Searching for episodes...") episode_list = search_anime_episode_list(chosen_anime["url"]) if len(episode_list) == 0: print("No episode found for this anime") else: print(f"Found {len(episode_list)} results: ") for (i, episode) in enumerate(episode_list): print(f"{i+1}. {episode['title']}") episode_choice = int(input("\nChoose an episode by serial no: ").strip()) chosen_episode = episode_list[episode_choice - 1] print(f"You chose {chosen_episode['title']}. Searching...") episode_url, download_url = get_anime_episode(chosen_episode["url"]) print(f"\nTo watch, ctrl+click on {episode_url}.") print(f"To download, ctrl+click on {download_url}.")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem Description: Given a binary tree, return its mirror. """ def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int): if not root or root not in binary_tree_mirror_dictionary: return left_child, right_child = binary_tree_mirror_dictionary[root][:2] binary_tree_mirror_dictionary[root] = [right_child, left_child] binary_tree_mirror_dict(binary_tree_mirror_dictionary, left_child) binary_tree_mirror_dict(binary_tree_mirror_dictionary, right_child) def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict: """ >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 7: [8,9]}, 1) {1: [3, 2], 2: [5, 4], 3: [7, 6], 7: [9, 8]} >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 1) {1: [3, 2], 2: [5, 4], 3: [7, 6], 4: [11, 10]} >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 5) Traceback (most recent call last): ... ValueError: root 5 is not present in the binary_tree >>> binary_tree_mirror({}, 5) Traceback (most recent call last): ... ValueError: binary tree cannot be empty """ if not binary_tree: raise ValueError("binary tree cannot be empty") if root not in binary_tree: raise ValueError(f"root {root} is not present in the binary_tree") binary_tree_mirror_dictionary = dict(binary_tree) binary_tree_mirror_dict(binary_tree_mirror_dictionary, root) return binary_tree_mirror_dictionary if __name__ == "__main__": binary_tree = {1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]} print(f"Binary tree: {binary_tree}") binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 5) print(f"Binary tree mirror: {binary_tree_mirror_dictionary}")
""" Problem Description: Given a binary tree, return its mirror. """ def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int): if not root or root not in binary_tree_mirror_dictionary: return left_child, right_child = binary_tree_mirror_dictionary[root][:2] binary_tree_mirror_dictionary[root] = [right_child, left_child] binary_tree_mirror_dict(binary_tree_mirror_dictionary, left_child) binary_tree_mirror_dict(binary_tree_mirror_dictionary, right_child) def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict: """ >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 7: [8,9]}, 1) {1: [3, 2], 2: [5, 4], 3: [7, 6], 7: [9, 8]} >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 1) {1: [3, 2], 2: [5, 4], 3: [7, 6], 4: [11, 10]} >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 5) Traceback (most recent call last): ... ValueError: root 5 is not present in the binary_tree >>> binary_tree_mirror({}, 5) Traceback (most recent call last): ... ValueError: binary tree cannot be empty """ if not binary_tree: raise ValueError("binary tree cannot be empty") if root not in binary_tree: raise ValueError(f"root {root} is not present in the binary_tree") binary_tree_mirror_dictionary = dict(binary_tree) binary_tree_mirror_dict(binary_tree_mirror_dictionary, root) return binary_tree_mirror_dictionary if __name__ == "__main__": binary_tree = {1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]} print(f"Binary tree: {binary_tree}") binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 5) print(f"Binary tree mirror: {binary_tree_mirror_dictionary}")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Approximates the area under the curve using the trapezoidal rule """ from __future__ import annotations from collections.abc import Callable def trapezoidal_area( fnc: Callable[[int | float], int | float], x_start: int | float, x_end: int | float, steps: int = 100, ) -> float: """ Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases the accuracy :return: a float representing the length of the curve >>> def f(x): ... return 5 >>> f"{trapezoidal_area(f, 12.0, 14.0, 1000):.3f}" '10.000' >>> def f(x): ... return 9*x**2 >>> f"{trapezoidal_area(f, -4.0, 0, 10000):.4f}" '192.0000' >>> f"{trapezoidal_area(f, -4.0, 4.0, 10000):.4f}" '384.0000' """ x1 = x_start fx1 = fnc(x_start) area = 0.0 for _ in range(steps): # Approximates small segments of curve as linear and solve # for trapezoidal area x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) area += abs(fx2 + fx1) * (x2 - x1) / 2 # Increment step x1 = x2 fx1 = fx2 return area if __name__ == "__main__": def f(x): return x**3 + x**2 print("f(x) = x^3 + x^2") print("The area between the curve, x = -5, x = 5 and the x axis is:") i = 10 while i <= 100000: print(f"with {i} steps: {trapezoidal_area(f, -5, 5, i)}") i *= 10
""" Approximates the area under the curve using the trapezoidal rule """ from __future__ import annotations from collections.abc import Callable def trapezoidal_area( fnc: Callable[[int | float], int | float], x_start: int | float, x_end: int | float, steps: int = 100, ) -> float: """ Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases the accuracy :return: a float representing the length of the curve >>> def f(x): ... return 5 >>> f"{trapezoidal_area(f, 12.0, 14.0, 1000):.3f}" '10.000' >>> def f(x): ... return 9*x**2 >>> f"{trapezoidal_area(f, -4.0, 0, 10000):.4f}" '192.0000' >>> f"{trapezoidal_area(f, -4.0, 4.0, 10000):.4f}" '384.0000' """ x1 = x_start fx1 = fnc(x_start) area = 0.0 for _ in range(steps): # Approximates small segments of curve as linear and solve # for trapezoidal area x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) area += abs(fx2 + fx1) * (x2 - x1) / 2 # Increment step x1 = x2 fx1 = fx2 return area if __name__ == "__main__": def f(x): return x**3 + x**2 print("f(x) = x^3 + x^2") print("The area between the curve, x = -5, x = 5 and the x axis is:") i = 10 while i <= 100000: print(f"with {i} steps: {trapezoidal_area(f, -5, 5, i)}") i *= 10
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from PIL import Image """ Mean thresholding algorithm for image processing https://en.wikipedia.org/wiki/Thresholding_(image_processing) """ def mean_threshold(image: Image) -> Image: """ image: is a grayscale PIL image object """ height, width = image.size mean = 0 pixels = image.load() for i in range(width): for j in range(height): pixel = pixels[j, i] mean += pixel mean //= width * height for j in range(width): for i in range(height): pixels[i, j] = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": image = mean_threshold(Image.open("path_to_image").convert("L")) image.save("output_image_path")
from PIL import Image """ Mean thresholding algorithm for image processing https://en.wikipedia.org/wiki/Thresholding_(image_processing) """ def mean_threshold(image: Image) -> Image: """ image: is a grayscale PIL image object """ height, width = image.size mean = 0 pixels = image.load() for i in range(width): for j in range(height): pixel = pixels[j, i] mean += pixel mean //= width * height for j in range(width): for i in range(height): pixels[i, j] = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": image = mean_threshold(Image.open("path_to_image").convert("L")) image.save("output_image_path")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def base16_encode(data: bytes) -> str: """ Encodes the given bytes into base16. >>> base16_encode(b'Hello World!') '48656C6C6F20576F726C6421' >>> base16_encode(b'HELLO WORLD!') '48454C4C4F20574F524C4421' >>> base16_encode(b'') '' """ # Turn the data into a list of integers (where each integer is a byte), # Then turn each byte into its hexadecimal representation, make sure # it is uppercase, and then join everything together and return it. return "".join([hex(byte)[2:].zfill(2).upper() for byte in list(data)]) def base16_decode(data: str) -> bytes: """ Decodes the given base16 encoded data into bytes. >>> base16_decode('48656C6C6F20576F726C6421') b'Hello World!' >>> base16_decode('48454C4C4F20574F524C4421') b'HELLO WORLD!' >>> base16_decode('') b'' >>> base16_decode('486') Traceback (most recent call last): ... ValueError: Base16 encoded data is invalid: Data does not have an even number of hex digits. >>> base16_decode('48656c6c6f20576f726c6421') Traceback (most recent call last): ... ValueError: Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters. >>> base16_decode('This is not base64 encoded data.') Traceback (most recent call last): ... ValueError: Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters. """ # Check data validity, following RFC3548 # https://www.ietf.org/rfc/rfc3548.txt if (len(data) % 2) != 0: raise ValueError( """Base16 encoded data is invalid: Data does not have an even number of hex digits.""" ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(data) <= set("0123456789ABCDEF"): raise ValueError( """Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters.""" ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1], 16) for i in range(0, len(data), 2)) if __name__ == "__main__": import doctest doctest.testmod()
def base16_encode(data: bytes) -> str: """ Encodes the given bytes into base16. >>> base16_encode(b'Hello World!') '48656C6C6F20576F726C6421' >>> base16_encode(b'HELLO WORLD!') '48454C4C4F20574F524C4421' >>> base16_encode(b'') '' """ # Turn the data into a list of integers (where each integer is a byte), # Then turn each byte into its hexadecimal representation, make sure # it is uppercase, and then join everything together and return it. return "".join([hex(byte)[2:].zfill(2).upper() for byte in list(data)]) def base16_decode(data: str) -> bytes: """ Decodes the given base16 encoded data into bytes. >>> base16_decode('48656C6C6F20576F726C6421') b'Hello World!' >>> base16_decode('48454C4C4F20574F524C4421') b'HELLO WORLD!' >>> base16_decode('') b'' >>> base16_decode('486') Traceback (most recent call last): ... ValueError: Base16 encoded data is invalid: Data does not have an even number of hex digits. >>> base16_decode('48656c6c6f20576f726c6421') Traceback (most recent call last): ... ValueError: Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters. >>> base16_decode('This is not base64 encoded data.') Traceback (most recent call last): ... ValueError: Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters. """ # Check data validity, following RFC3548 # https://www.ietf.org/rfc/rfc3548.txt if (len(data) % 2) != 0: raise ValueError( """Base16 encoded data is invalid: Data does not have an even number of hex digits.""" ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(data) <= set("0123456789ABCDEF"): raise ValueError( """Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters.""" ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1], 16) for i in range(0, len(data), 2)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another 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/Check_digit#Algorithms """ def get_check_digit(barcode: int) -> int: """ Returns the last digit of barcode by excluding the last digit first and then computing to reach the actual last digit from the remaining 12 digits. >>> get_check_digit(8718452538119) 9 >>> get_check_digit(87184523) 5 >>> get_check_digit(87193425381086) 9 >>> [get_check_digit(x) for x in range(0, 100, 10)] [0, 7, 4, 1, 8, 5, 2, 9, 6, 3] """ barcode //= 10 # exclude the last digit checker = False s = 0 # extract and check each digit while barcode != 0: mult = 1 if checker else 3 s += mult * (barcode % 10) barcode //= 10 checker = not checker return (10 - (s % 10)) % 10 def is_valid(barcode: int) -> bool: """ Checks for length of barcode and last-digit Returns boolean value of validity of barcode >>> is_valid(8718452538119) True >>> is_valid(87184525) False >>> is_valid(87193425381089) False >>> is_valid(0) False >>> is_valid(dwefgiweuf) Traceback (most recent call last): ... NameError: name 'dwefgiweuf' is not defined """ return len(str(barcode)) == 13 and get_check_digit(barcode) == barcode % 10 def get_barcode(barcode: str) -> int: """ Returns the barcode as an integer >>> get_barcode("8718452538119") 8718452538119 >>> get_barcode("dwefgiweuf") Traceback (most recent call last): ... ValueError: Barcode 'dwefgiweuf' has alphabetic characters. """ if str(barcode).isalpha(): raise ValueError(f"Barcode '{barcode}' has alphabetic characters.") elif int(barcode) < 0: raise ValueError("The entered barcode has a negative value. Try again.") else: return int(barcode) if __name__ == "__main__": import doctest doctest.testmod() """ Enter a barcode. """ barcode = get_barcode(input("Barcode: ").strip()) if is_valid(barcode): print(f"'{barcode}' is a valid barcode.") else: print(f"'{barcode}' is NOT a valid barcode.")
""" https://en.wikipedia.org/wiki/Check_digit#Algorithms """ def get_check_digit(barcode: int) -> int: """ Returns the last digit of barcode by excluding the last digit first and then computing to reach the actual last digit from the remaining 12 digits. >>> get_check_digit(8718452538119) 9 >>> get_check_digit(87184523) 5 >>> get_check_digit(87193425381086) 9 >>> [get_check_digit(x) for x in range(0, 100, 10)] [0, 7, 4, 1, 8, 5, 2, 9, 6, 3] """ barcode //= 10 # exclude the last digit checker = False s = 0 # extract and check each digit while barcode != 0: mult = 1 if checker else 3 s += mult * (barcode % 10) barcode //= 10 checker = not checker return (10 - (s % 10)) % 10 def is_valid(barcode: int) -> bool: """ Checks for length of barcode and last-digit Returns boolean value of validity of barcode >>> is_valid(8718452538119) True >>> is_valid(87184525) False >>> is_valid(87193425381089) False >>> is_valid(0) False >>> is_valid(dwefgiweuf) Traceback (most recent call last): ... NameError: name 'dwefgiweuf' is not defined """ return len(str(barcode)) == 13 and get_check_digit(barcode) == barcode % 10 def get_barcode(barcode: str) -> int: """ Returns the barcode as an integer >>> get_barcode("8718452538119") 8718452538119 >>> get_barcode("dwefgiweuf") Traceback (most recent call last): ... ValueError: Barcode 'dwefgiweuf' has alphabetic characters. """ if str(barcode).isalpha(): raise ValueError(f"Barcode '{barcode}' has alphabetic characters.") elif int(barcode) < 0: raise ValueError("The entered barcode has a negative value. Try again.") else: return int(barcode) if __name__ == "__main__": import doctest doctest.testmod() """ Enter a barcode. """ barcode = get_barcode(input("Barcode: ").strip()) if is_valid(barcode): print(f"'{barcode}' is a valid barcode.") else: print(f"'{barcode}' is NOT a valid barcode.")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 """ Build quantum teleportation circuit using three quantum bits and 1 classical bit. The main idea is to send one qubit from Alice to Bob using the entanglement properties. This experiment run in IBM Q simulator with 1000 shots. . References: https://en.wikipedia.org/wiki/Quantum_teleportation https://qiskit.org/textbook/ch-algorithms/teleportation.html """ import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def quantum_teleportation( theta: float = np.pi / 2, phi: float = np.pi / 2, lam: float = np.pi / 2 ) -> qiskit.result.counts.Counts: """ # >>> quantum_teleportation() #{'00': 500, '11': 500} # ideally # ┌─────────────────┐ ┌───┐ #qr_0: ┤ U(π/2,π/2,π/2) ├───────■──┤ H ├─■───────── # └──────┬───┬──────┘ ┌─┴─┐└───┘ │ #qr_1: ───────┤ H ├─────────■──┤ X ├──────┼───■───── # └───┘ ┌─┴─┐└───┘ │ ┌─┴─┐┌─┐ #qr_2: ───────────────────┤ X ├───────────■─┤ X ├┤M├ # └───┘ └───┘└╥┘ #cr: 1/═══════════════════════════════════════════╩═ Args: theta (float): Single qubit rotation U Gate theta parameter. Default to np.pi/2 phi (float): Single qubit rotation U Gate phi parameter. Default to np.pi/2 lam (float): Single qubit rotation U Gate lam parameter. Default to np.pi/2 Returns: qiskit.result.counts.Counts: Teleported qubit counts. """ qr = QuantumRegister(3, "qr") # Define the number of quantum bits cr = ClassicalRegister(1, "cr") # Define the number of classical bits quantum_circuit = QuantumCircuit(qr, cr) # Define the quantum circuit. # Build the circuit quantum_circuit.u(theta, phi, lam, 0) # Quantum State to teleport quantum_circuit.h(1) # add hadamard gate quantum_circuit.cx( 1, 2 ) # add control gate with qubit 1 as control and 2 as target. quantum_circuit.cx(0, 1) quantum_circuit.h(0) quantum_circuit.cz(0, 2) # add control z gate. quantum_circuit.cx(1, 2) quantum_circuit.measure([2], [0]) # measure the qubit. # Simulate the circuit using qasm simulator backend = Aer.get_backend("aer_simulator") job = execute(quantum_circuit, backend, shots=1000) return job.result().get_counts(quantum_circuit) if __name__ == "__main__": print( "Total count for teleported state is: " f"{quantum_teleportation(np.pi/2, np.pi/2, np.pi/2)}" )
#!/usr/bin/env python3 """ Build quantum teleportation circuit using three quantum bits and 1 classical bit. The main idea is to send one qubit from Alice to Bob using the entanglement properties. This experiment run in IBM Q simulator with 1000 shots. . References: https://en.wikipedia.org/wiki/Quantum_teleportation https://qiskit.org/textbook/ch-algorithms/teleportation.html """ import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def quantum_teleportation( theta: float = np.pi / 2, phi: float = np.pi / 2, lam: float = np.pi / 2 ) -> qiskit.result.counts.Counts: """ # >>> quantum_teleportation() #{'00': 500, '11': 500} # ideally # ┌─────────────────┐ ┌───┐ #qr_0: ┤ U(π/2,π/2,π/2) ├───────■──┤ H ├─■───────── # └──────┬───┬──────┘ ┌─┴─┐└───┘ │ #qr_1: ───────┤ H ├─────────■──┤ X ├──────┼───■───── # └───┘ ┌─┴─┐└───┘ │ ┌─┴─┐┌─┐ #qr_2: ───────────────────┤ X ├───────────■─┤ X ├┤M├ # └───┘ └───┘└╥┘ #cr: 1/═══════════════════════════════════════════╩═ Args: theta (float): Single qubit rotation U Gate theta parameter. Default to np.pi/2 phi (float): Single qubit rotation U Gate phi parameter. Default to np.pi/2 lam (float): Single qubit rotation U Gate lam parameter. Default to np.pi/2 Returns: qiskit.result.counts.Counts: Teleported qubit counts. """ qr = QuantumRegister(3, "qr") # Define the number of quantum bits cr = ClassicalRegister(1, "cr") # Define the number of classical bits quantum_circuit = QuantumCircuit(qr, cr) # Define the quantum circuit. # Build the circuit quantum_circuit.u(theta, phi, lam, 0) # Quantum State to teleport quantum_circuit.h(1) # add hadamard gate quantum_circuit.cx( 1, 2 ) # add control gate with qubit 1 as control and 2 as target. quantum_circuit.cx(0, 1) quantum_circuit.h(0) quantum_circuit.cz(0, 2) # add control z gate. quantum_circuit.cx(1, 2) quantum_circuit.measure([2], [0]) # measure the qubit. # Simulate the circuit using qasm simulator backend = Aer.get_backend("aer_simulator") job = execute(quantum_circuit, backend, shots=1000) return job.result().get_counts(quantum_circuit) if __name__ == "__main__": print( "Total count for teleported state is: " f"{quantum_teleportation(np.pi/2, np.pi/2, np.pi/2)}" )
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 135: https://projecteuler.net/problem=135 Given the positive integers, x, y, and z, are consecutive terms of an arithmetic progression, the least value of the positive integer, n, for which the equation, x2 − y2 − z2 = n, has exactly two solutions is n = 27: 342 − 272 − 202 = 122 − 92 − 62 = 27 It turns out that n = 1155 is the least value which has exactly ten solutions. How many values of n less than one million have exactly ten distinct solutions? Taking x,y,z of the form a+d,a,a-d respectively, the given equation reduces to a*(4d-a)=n. Calculating no of solutions for every n till 1 million by fixing a ,and n must be multiple of a. Total no of steps=n*(1/1+1/2+1/3+1/4..+1/n) ,so roughly O(nlogn) time complexity. """ def solution(limit: int = 1000000) -> int: """ returns the values of n less than or equal to the limit have exactly ten distinct solutions. >>> solution(100) 0 >>> solution(10000) 45 >>> solution(50050) 292 """ limit = limit + 1 frequency = [0] * limit for first_term in range(1, limit): for n in range(first_term, limit, first_term): common_difference = first_term + n / first_term if common_difference % 4: # d must be divisble by 4 continue else: common_difference /= 4 if ( first_term > common_difference and first_term < 4 * common_difference ): # since x,y,z are positive integers frequency[n] += 1 # so z>0 and a>d ,also 4d<a count = sum(1 for x in frequency[1:limit] if x == 10) return count if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 135: https://projecteuler.net/problem=135 Given the positive integers, x, y, and z, are consecutive terms of an arithmetic progression, the least value of the positive integer, n, for which the equation, x2 − y2 − z2 = n, has exactly two solutions is n = 27: 342 − 272 − 202 = 122 − 92 − 62 = 27 It turns out that n = 1155 is the least value which has exactly ten solutions. How many values of n less than one million have exactly ten distinct solutions? Taking x,y,z of the form a+d,a,a-d respectively, the given equation reduces to a*(4d-a)=n. Calculating no of solutions for every n till 1 million by fixing a ,and n must be multiple of a. Total no of steps=n*(1/1+1/2+1/3+1/4..+1/n) ,so roughly O(nlogn) time complexity. """ def solution(limit: int = 1000000) -> int: """ returns the values of n less than or equal to the limit have exactly ten distinct solutions. >>> solution(100) 0 >>> solution(10000) 45 >>> solution(50050) 292 """ limit = limit + 1 frequency = [0] * limit for first_term in range(1, limit): for n in range(first_term, limit, first_term): common_difference = first_term + n / first_term if common_difference % 4: # d must be divisble by 4 continue else: common_difference /= 4 if ( first_term > common_difference and first_term < 4 * common_difference ): # since x,y,z are positive integers frequency[n] += 1 # so z>0 and a>d ,also 4d<a count = sum(1 for x in frequency[1:limit] if x == 10) return count if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another 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 # 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 __repr__(self): return f"{self.__class__.__name__}.{self.name}" 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, y = point return degrees(atan2(y - miny, x - minx)) 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)) via_angle %= 360 target_angle = degrees(atan2(y2 - y0, x2 - x0)) 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 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) 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)) 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 # 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 __repr__(self): return f"{self.__class__.__name__}.{self.name}" 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, y = point return degrees(atan2(y - miny, x - minx)) 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)) via_angle %= 360 target_angle = degrees(atan2(y2 - y0, x2 - x0)) 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 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) 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)) 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
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another 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
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Breadth-first_search pseudo-code: breadth_first_search(graph G, start vertex s): // all nodes initially unexplored mark s as explored let Q = queue data structure, initialized with s while Q is non-empty: remove the first node of Q, call it v for each edge(v, w): // for w in graph[v] if w unexplored: mark w as explored add w to Q (at the end) """ from __future__ import annotations from collections import deque from queue import Queue from timeit import timeit G = { "A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B"], "E": ["B", "F"], "F": ["C", "E"], } def breadth_first_search(graph: dict, start: str) -> list[str]: """ Implementation of breadth first search using queue.Queue. >>> ''.join(breadth_first_search(G, 'A')) 'ABCDEF' """ explored = {start} result = [start] queue: Queue = Queue() queue.put(start) while not queue.empty(): v = queue.get() for w in graph[v]: if w not in explored: explored.add(w) result.append(w) queue.put(w) return result def breadth_first_search_with_deque(graph: dict, start: str) -> list[str]: """ Implementation of breadth first search using collection.queue. >>> ''.join(breadth_first_search_with_deque(G, 'A')) 'ABCDEF' """ visited = {start} result = [start] queue = deque([start]) while queue: v = queue.popleft() for child in graph[v]: if child not in visited: visited.add(child) result.append(child) queue.append(child) return result def benchmark_function(name: str) -> None: setup = f"from __main__ import G, {name}" number = 10000 res = timeit(f"{name}(G, 'A')", setup=setup, number=number) print(f"{name:<35} finished {number} runs in {res:.5f} seconds") if __name__ == "__main__": import doctest doctest.testmod() benchmark_function("breadth_first_search") benchmark_function("breadth_first_search_with_deque") # breadth_first_search finished 10000 runs in 0.20999 seconds # breadth_first_search_with_deque finished 10000 runs in 0.01421 seconds
""" https://en.wikipedia.org/wiki/Breadth-first_search pseudo-code: breadth_first_search(graph G, start vertex s): // all nodes initially unexplored mark s as explored let Q = queue data structure, initialized with s while Q is non-empty: remove the first node of Q, call it v for each edge(v, w): // for w in graph[v] if w unexplored: mark w as explored add w to Q (at the end) """ from __future__ import annotations from collections import deque from queue import Queue from timeit import timeit G = { "A": ["B", "C"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B"], "E": ["B", "F"], "F": ["C", "E"], } def breadth_first_search(graph: dict, start: str) -> list[str]: """ Implementation of breadth first search using queue.Queue. >>> ''.join(breadth_first_search(G, 'A')) 'ABCDEF' """ explored = {start} result = [start] queue: Queue = Queue() queue.put(start) while not queue.empty(): v = queue.get() for w in graph[v]: if w not in explored: explored.add(w) result.append(w) queue.put(w) return result def breadth_first_search_with_deque(graph: dict, start: str) -> list[str]: """ Implementation of breadth first search using collection.queue. >>> ''.join(breadth_first_search_with_deque(G, 'A')) 'ABCDEF' """ visited = {start} result = [start] queue = deque([start]) while queue: v = queue.popleft() for child in graph[v]: if child not in visited: visited.add(child) result.append(child) queue.append(child) return result def benchmark_function(name: str) -> None: setup = f"from __main__ import G, {name}" number = 10000 res = timeit(f"{name}(G, 'A')", setup=setup, number=number) print(f"{name:<35} finished {number} runs in {res:.5f} seconds") if __name__ == "__main__": import doctest doctest.testmod() benchmark_function("breadth_first_search") benchmark_function("breadth_first_search_with_deque") # breadth_first_search finished 10000 runs in 0.20999 seconds # breadth_first_search_with_deque finished 10000 runs in 0.01421 seconds
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Arithmetic mean Reference: https://en.wikipedia.org/wiki/Arithmetic_mean Arithmetic series Reference: https://en.wikipedia.org/wiki/Arithmetic_series (The URL above will redirect you to arithmetic progression) """ def is_arithmetic_series(series: list) -> bool: """ checking whether the input series is arithmetic series or not >>> is_arithmetic_series([2, 4, 6]) True >>> is_arithmetic_series([3, 6, 12, 24]) False >>> is_arithmetic_series([1, 2, 3]) True >>> is_arithmetic_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> is_arithmetic_series([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True common_diff = series[1] - series[0] for index in range(len(series) - 1): if series[index + 1] - series[index] != common_diff: return False return True def arithmetic_mean(series: list) -> float: """ return the arithmetic mean of series >>> arithmetic_mean([2, 4, 6]) 4.0 >>> arithmetic_mean([3, 6, 9, 12]) 7.5 >>> arithmetic_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> arithmetic_mean([4, 8, 1]) 4.333333333333333 >>> arithmetic_mean([1, 2, 3]) 2.0 >>> arithmetic_mean([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 0 for val in series: answer += val return answer / len(series) if __name__ == "__main__": import doctest doctest.testmod()
""" Arithmetic mean Reference: https://en.wikipedia.org/wiki/Arithmetic_mean Arithmetic series Reference: https://en.wikipedia.org/wiki/Arithmetic_series (The URL above will redirect you to arithmetic progression) """ def is_arithmetic_series(series: list) -> bool: """ checking whether the input series is arithmetic series or not >>> is_arithmetic_series([2, 4, 6]) True >>> is_arithmetic_series([3, 6, 12, 24]) False >>> is_arithmetic_series([1, 2, 3]) True >>> is_arithmetic_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> is_arithmetic_series([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True common_diff = series[1] - series[0] for index in range(len(series) - 1): if series[index + 1] - series[index] != common_diff: return False return True def arithmetic_mean(series: list) -> float: """ return the arithmetic mean of series >>> arithmetic_mean([2, 4, 6]) 4.0 >>> arithmetic_mean([3, 6, 9, 12]) 7.5 >>> arithmetic_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> arithmetic_mean([4, 8, 1]) 4.333333333333333 >>> arithmetic_mean([1, 2, 3]) 2.0 >>> arithmetic_mean([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 0 for val in series: answer += val return answer / len(series) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def snake_to_camel_case(input_str: str, use_pascal: bool = False) -> str: """ Transforms a snake_case given string to camelCase (or PascalCase if indicated) (defaults to not use Pascal) >>> snake_to_camel_case("some_random_string") 'someRandomString' >>> snake_to_camel_case("some_random_string", use_pascal=True) 'SomeRandomString' >>> snake_to_camel_case("some_random_string_with_numbers_123") 'someRandomStringWithNumbers123' >>> snake_to_camel_case("some_random_string_with_numbers_123", use_pascal=True) 'SomeRandomStringWithNumbers123' >>> snake_to_camel_case(123) Traceback (most recent call last): ... ValueError: Expected string as input, found <class 'int'> >>> snake_to_camel_case("some_string", use_pascal="True") Traceback (most recent call last): ... ValueError: Expected boolean as use_pascal parameter, found <class 'str'> """ if not isinstance(input_str, str): raise ValueError(f"Expected string as input, found {type(input_str)}") if not isinstance(use_pascal, bool): raise ValueError( f"Expected boolean as use_pascal parameter, found {type(use_pascal)}" ) words = input_str.split("_") start_index = 0 if use_pascal else 1 words_to_capitalize = words[start_index:] capitalized_words = [word[0].upper() + word[1:] for word in words_to_capitalize] initial_word = "" if use_pascal else words[0] return "".join([initial_word] + capitalized_words) if __name__ == "__main__": from doctest import testmod testmod()
def snake_to_camel_case(input_str: str, use_pascal: bool = False) -> str: """ Transforms a snake_case given string to camelCase (or PascalCase if indicated) (defaults to not use Pascal) >>> snake_to_camel_case("some_random_string") 'someRandomString' >>> snake_to_camel_case("some_random_string", use_pascal=True) 'SomeRandomString' >>> snake_to_camel_case("some_random_string_with_numbers_123") 'someRandomStringWithNumbers123' >>> snake_to_camel_case("some_random_string_with_numbers_123", use_pascal=True) 'SomeRandomStringWithNumbers123' >>> snake_to_camel_case(123) Traceback (most recent call last): ... ValueError: Expected string as input, found <class 'int'> >>> snake_to_camel_case("some_string", use_pascal="True") Traceback (most recent call last): ... ValueError: Expected boolean as use_pascal parameter, found <class 'str'> """ if not isinstance(input_str, str): raise ValueError(f"Expected string as input, found {type(input_str)}") if not isinstance(use_pascal, bool): raise ValueError( f"Expected boolean as use_pascal parameter, found {type(use_pascal)}" ) words = input_str.split("_") start_index = 0 if use_pascal else 1 words_to_capitalize = words[start_index:] capitalized_words = [word[0].upper() + word[1:] for word in words_to_capitalize] initial_word = "" if use_pascal else words[0] return "".join([initial_word] + capitalized_words) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The RGB color model is an additive color model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors. The name of the model comes from the initials of the three additive primary colors, red, green, and blue. Meanwhile, the HSV representation models how colors appear under light. In it, colors are represented using three components: hue, saturation and (brightness-)value. This file provides functions for converting colors from one representation to the other. (description adapted from https://en.wikipedia.org/wiki/RGB_color_model and https://en.wikipedia.org/wiki/HSL_and_HSV). """ def hsv_to_rgb(hue: float, saturation: float, value: float) -> list[int]: """ Conversion from the HSV-representation to the RGB-representation. Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html >>> hsv_to_rgb(0, 0, 0) [0, 0, 0] >>> hsv_to_rgb(0, 0, 1) [255, 255, 255] >>> hsv_to_rgb(0, 1, 1) [255, 0, 0] >>> hsv_to_rgb(60, 1, 1) [255, 255, 0] >>> hsv_to_rgb(120, 1, 1) [0, 255, 0] >>> hsv_to_rgb(240, 1, 1) [0, 0, 255] >>> hsv_to_rgb(300, 1, 1) [255, 0, 255] >>> hsv_to_rgb(180, 0.5, 0.5) [64, 128, 128] >>> hsv_to_rgb(234, 0.14, 0.88) [193, 196, 224] >>> hsv_to_rgb(330, 0.75, 0.5) [128, 32, 80] """ if hue < 0 or hue > 360: raise Exception("hue should be between 0 and 360") if saturation < 0 or saturation > 1: raise Exception("saturation should be between 0 and 1") if value < 0 or value > 1: raise Exception("value should be between 0 and 1") chroma = value * saturation hue_section = hue / 60 second_largest_component = chroma * (1 - abs(hue_section % 2 - 1)) match_value = value - chroma if hue_section >= 0 and hue_section <= 1: red = round(255 * (chroma + match_value)) green = round(255 * (second_largest_component + match_value)) blue = round(255 * (match_value)) elif hue_section > 1 and hue_section <= 2: red = round(255 * (second_largest_component + match_value)) green = round(255 * (chroma + match_value)) blue = round(255 * (match_value)) elif hue_section > 2 and hue_section <= 3: red = round(255 * (match_value)) green = round(255 * (chroma + match_value)) blue = round(255 * (second_largest_component + match_value)) elif hue_section > 3 and hue_section <= 4: red = round(255 * (match_value)) green = round(255 * (second_largest_component + match_value)) blue = round(255 * (chroma + match_value)) elif hue_section > 4 and hue_section <= 5: red = round(255 * (second_largest_component + match_value)) green = round(255 * (match_value)) blue = round(255 * (chroma + match_value)) else: red = round(255 * (chroma + match_value)) green = round(255 * (match_value)) blue = round(255 * (second_largest_component + match_value)) return [red, green, blue] def rgb_to_hsv(red: int, green: int, blue: int) -> list[float]: """ Conversion from the RGB-representation to the HSV-representation. The tested values are the reverse values from the hsv_to_rgb-doctests. Function "approximately_equal_hsv" is needed because of small deviations due to rounding for the RGB-values. >>> approximately_equal_hsv(rgb_to_hsv(0, 0, 0), [0, 0, 0]) True >>> approximately_equal_hsv(rgb_to_hsv(255, 255, 255), [0, 0, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(255, 0, 0), [0, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(255, 255, 0), [60, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(0, 255, 0), [120, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(0, 0, 255), [240, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(255, 0, 255), [300, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(64, 128, 128), [180, 0.5, 0.5]) True >>> approximately_equal_hsv(rgb_to_hsv(193, 196, 224), [234, 0.14, 0.88]) True >>> approximately_equal_hsv(rgb_to_hsv(128, 32, 80), [330, 0.75, 0.5]) True """ if red < 0 or red > 255: raise Exception("red should be between 0 and 255") if green < 0 or green > 255: raise Exception("green should be between 0 and 255") if blue < 0 or blue > 255: raise Exception("blue should be between 0 and 255") float_red = red / 255 float_green = green / 255 float_blue = blue / 255 value = max(max(float_red, float_green), float_blue) chroma = value - min(min(float_red, float_green), float_blue) saturation = 0 if value == 0 else chroma / value if chroma == 0: hue = 0.0 elif value == float_red: hue = 60 * (0 + (float_green - float_blue) / chroma) elif value == float_green: hue = 60 * (2 + (float_blue - float_red) / chroma) else: hue = 60 * (4 + (float_red - float_green) / chroma) hue = (hue + 360) % 360 return [hue, saturation, value] def approximately_equal_hsv(hsv_1: list[float], hsv_2: list[float]) -> bool: """ Utility-function to check that two hsv-colors are approximately equal >>> approximately_equal_hsv([0, 0, 0], [0, 0, 0]) True >>> approximately_equal_hsv([180, 0.5, 0.3], [179.9999, 0.500001, 0.30001]) True >>> approximately_equal_hsv([0, 0, 0], [1, 0, 0]) False >>> approximately_equal_hsv([180, 0.5, 0.3], [179.9999, 0.6, 0.30001]) False """ check_hue = abs(hsv_1[0] - hsv_2[0]) < 0.2 check_saturation = abs(hsv_1[1] - hsv_2[1]) < 0.002 check_value = abs(hsv_1[2] - hsv_2[2]) < 0.002 return check_hue and check_saturation and check_value
""" The RGB color model is an additive color model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors. The name of the model comes from the initials of the three additive primary colors, red, green, and blue. Meanwhile, the HSV representation models how colors appear under light. In it, colors are represented using three components: hue, saturation and (brightness-)value. This file provides functions for converting colors from one representation to the other. (description adapted from https://en.wikipedia.org/wiki/RGB_color_model and https://en.wikipedia.org/wiki/HSL_and_HSV). """ def hsv_to_rgb(hue: float, saturation: float, value: float) -> list[int]: """ Conversion from the HSV-representation to the RGB-representation. Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html >>> hsv_to_rgb(0, 0, 0) [0, 0, 0] >>> hsv_to_rgb(0, 0, 1) [255, 255, 255] >>> hsv_to_rgb(0, 1, 1) [255, 0, 0] >>> hsv_to_rgb(60, 1, 1) [255, 255, 0] >>> hsv_to_rgb(120, 1, 1) [0, 255, 0] >>> hsv_to_rgb(240, 1, 1) [0, 0, 255] >>> hsv_to_rgb(300, 1, 1) [255, 0, 255] >>> hsv_to_rgb(180, 0.5, 0.5) [64, 128, 128] >>> hsv_to_rgb(234, 0.14, 0.88) [193, 196, 224] >>> hsv_to_rgb(330, 0.75, 0.5) [128, 32, 80] """ if hue < 0 or hue > 360: raise Exception("hue should be between 0 and 360") if saturation < 0 or saturation > 1: raise Exception("saturation should be between 0 and 1") if value < 0 or value > 1: raise Exception("value should be between 0 and 1") chroma = value * saturation hue_section = hue / 60 second_largest_component = chroma * (1 - abs(hue_section % 2 - 1)) match_value = value - chroma if hue_section >= 0 and hue_section <= 1: red = round(255 * (chroma + match_value)) green = round(255 * (second_largest_component + match_value)) blue = round(255 * (match_value)) elif hue_section > 1 and hue_section <= 2: red = round(255 * (second_largest_component + match_value)) green = round(255 * (chroma + match_value)) blue = round(255 * (match_value)) elif hue_section > 2 and hue_section <= 3: red = round(255 * (match_value)) green = round(255 * (chroma + match_value)) blue = round(255 * (second_largest_component + match_value)) elif hue_section > 3 and hue_section <= 4: red = round(255 * (match_value)) green = round(255 * (second_largest_component + match_value)) blue = round(255 * (chroma + match_value)) elif hue_section > 4 and hue_section <= 5: red = round(255 * (second_largest_component + match_value)) green = round(255 * (match_value)) blue = round(255 * (chroma + match_value)) else: red = round(255 * (chroma + match_value)) green = round(255 * (match_value)) blue = round(255 * (second_largest_component + match_value)) return [red, green, blue] def rgb_to_hsv(red: int, green: int, blue: int) -> list[float]: """ Conversion from the RGB-representation to the HSV-representation. The tested values are the reverse values from the hsv_to_rgb-doctests. Function "approximately_equal_hsv" is needed because of small deviations due to rounding for the RGB-values. >>> approximately_equal_hsv(rgb_to_hsv(0, 0, 0), [0, 0, 0]) True >>> approximately_equal_hsv(rgb_to_hsv(255, 255, 255), [0, 0, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(255, 0, 0), [0, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(255, 255, 0), [60, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(0, 255, 0), [120, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(0, 0, 255), [240, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(255, 0, 255), [300, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(64, 128, 128), [180, 0.5, 0.5]) True >>> approximately_equal_hsv(rgb_to_hsv(193, 196, 224), [234, 0.14, 0.88]) True >>> approximately_equal_hsv(rgb_to_hsv(128, 32, 80), [330, 0.75, 0.5]) True """ if red < 0 or red > 255: raise Exception("red should be between 0 and 255") if green < 0 or green > 255: raise Exception("green should be between 0 and 255") if blue < 0 or blue > 255: raise Exception("blue should be between 0 and 255") float_red = red / 255 float_green = green / 255 float_blue = blue / 255 value = max(max(float_red, float_green), float_blue) chroma = value - min(min(float_red, float_green), float_blue) saturation = 0 if value == 0 else chroma / value if chroma == 0: hue = 0.0 elif value == float_red: hue = 60 * (0 + (float_green - float_blue) / chroma) elif value == float_green: hue = 60 * (2 + (float_blue - float_red) / chroma) else: hue = 60 * (4 + (float_red - float_green) / chroma) hue = (hue + 360) % 360 return [hue, saturation, value] def approximately_equal_hsv(hsv_1: list[float], hsv_2: list[float]) -> bool: """ Utility-function to check that two hsv-colors are approximately equal >>> approximately_equal_hsv([0, 0, 0], [0, 0, 0]) True >>> approximately_equal_hsv([180, 0.5, 0.3], [179.9999, 0.500001, 0.30001]) True >>> approximately_equal_hsv([0, 0, 0], [1, 0, 0]) False >>> approximately_equal_hsv([180, 0.5, 0.3], [179.9999, 0.6, 0.30001]) False """ check_hue = abs(hsv_1[0] - hsv_2[0]) < 0.2 check_saturation = abs(hsv_1[1] - hsv_2[1]) < 0.002 check_value = abs(hsv_1[2] - hsv_2[2]) < 0.002 return check_hue and check_saturation and check_value
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import requests APPID = "" # <-- Put your OpenWeatherMap appid here! URL_BASE = "https://api.openweathermap.org/data/2.5/" def current_weather(q: str = "Chicago", appid: str = APPID) -> dict: """https://openweathermap.org/api""" return requests.get(URL_BASE + "weather", params=locals()).json() def weather_forecast(q: str = "Kolkata, India", appid: str = APPID) -> dict: """https://openweathermap.org/forecast5""" return requests.get(URL_BASE + "forecast", params=locals()).json() def weather_onecall(lat: float = 55.68, lon: float = 12.57, appid: str = APPID) -> dict: """https://openweathermap.org/api/one-call-api""" return requests.get(URL_BASE + "onecall", params=locals()).json() if __name__ == "__main__": from pprint import pprint while True: location = input("Enter a location:").strip() if location: pprint(current_weather(location)) else: break
import requests APPID = "" # <-- Put your OpenWeatherMap appid here! URL_BASE = "https://api.openweathermap.org/data/2.5/" def current_weather(q: str = "Chicago", appid: str = APPID) -> dict: """https://openweathermap.org/api""" return requests.get(URL_BASE + "weather", params=locals()).json() def weather_forecast(q: str = "Kolkata, India", appid: str = APPID) -> dict: """https://openweathermap.org/forecast5""" return requests.get(URL_BASE + "forecast", params=locals()).json() def weather_onecall(lat: float = 55.68, lon: float = 12.57, appid: str = APPID) -> dict: """https://openweathermap.org/api/one-call-api""" return requests.get(URL_BASE + "onecall", params=locals()).json() if __name__ == "__main__": from pprint import pprint while True: location = input("Enter a location:").strip() if location: pprint(current_weather(location)) else: break
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 75: https://projecteuler.net/problem=75 It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples. 12 cm: (3,4,5) 24 cm: (6,8,10) 30 cm: (5,12,13) 36 cm: (9,12,15) 40 cm: (8,15,17) 48 cm: (12,16,20) In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided right angle triangle, and other lengths allow more than one solution to be found; for example, using 120 cm it is possible to form exactly three different integer sided right angle triangles. 120 cm: (30,40,50), (20,48,52), (24,45,51) Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can exactly one integer sided right angle triangle be formed? Solution: we generate all pythagorean triples using Euclid's formula and keep track of the frequencies of the perimeters. Reference: https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple """ from collections import defaultdict from math import gcd from typing import DefaultDict def solution(limit: int = 1500000) -> int: """ Return the number of values of L <= limit such that a wire of length L can be formmed into an integer sided right angle triangle in exactly one way. >>> solution(50) 6 >>> solution(1000) 112 >>> solution(50000) 5502 """ frequencies: DefaultDict = defaultdict(int) euclid_m = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1, euclid_m, 2): if gcd(euclid_m, euclid_n) > 1: continue primitive_perimeter = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(primitive_perimeter, limit + 1, primitive_perimeter): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 75: https://projecteuler.net/problem=75 It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples. 12 cm: (3,4,5) 24 cm: (6,8,10) 30 cm: (5,12,13) 36 cm: (9,12,15) 40 cm: (8,15,17) 48 cm: (12,16,20) In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided right angle triangle, and other lengths allow more than one solution to be found; for example, using 120 cm it is possible to form exactly three different integer sided right angle triangles. 120 cm: (30,40,50), (20,48,52), (24,45,51) Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can exactly one integer sided right angle triangle be formed? Solution: we generate all pythagorean triples using Euclid's formula and keep track of the frequencies of the perimeters. Reference: https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple """ from collections import defaultdict from math import gcd from typing import DefaultDict def solution(limit: int = 1500000) -> int: """ Return the number of values of L <= limit such that a wire of length L can be formmed into an integer sided right angle triangle in exactly one way. >>> solution(50) 6 >>> solution(1000) 112 >>> solution(50000) 5502 """ frequencies: DefaultDict = defaultdict(int) euclid_m = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1, euclid_m, 2): if gcd(euclid_m, euclid_n) > 1: continue primitive_perimeter = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(primitive_perimeter, limit + 1, primitive_perimeter): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python # # Sort large text files in a minimum amount of memory # import argparse import os class FileSplitter: BLOCK_FILENAME_FORMAT = "block_{0}.dat" def __init__(self, filename): self.filename = filename self.block_filenames = [] def write_block(self, data, block_number): filename = self.BLOCK_FILENAME_FORMAT.format(block_number) with open(filename, "w") as file: file.write(data) self.block_filenames.append(filename) def get_block_filenames(self): return self.block_filenames def split(self, block_size, sort_key=None): i = 0 with open(self.filename) as file: while True: lines = file.readlines(block_size) if lines == []: break if sort_key is None: lines.sort() else: lines.sort(key=sort_key) self.write_block("".join(lines), i) i += 1 def cleanup(self): map(os.remove, self.block_filenames) class NWayMerge: def select(self, choices): min_index = -1 min_str = None for i in range(len(choices)): if min_str is None or choices[i] < min_str: min_index = i return min_index class FilesArray: def __init__(self, files): self.files = files self.empty = set() self.num_buffers = len(files) self.buffers = {i: None for i in range(self.num_buffers)} def get_dict(self): return { i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty } def refresh(self): for i in range(self.num_buffers): if self.buffers[i] is None and i not in self.empty: self.buffers[i] = self.files[i].readline() if self.buffers[i] == "": self.empty.add(i) self.files[i].close() if len(self.empty) == self.num_buffers: return False return True def unshift(self, index): value = self.buffers[index] self.buffers[index] = None return value class FileMerger: def __init__(self, merge_strategy): self.merge_strategy = merge_strategy def merge(self, filenames, outfilename, buffer_size): buffers = FilesArray(self.get_file_handles(filenames, buffer_size)) with open(outfilename, "w", buffer_size) as outfile: while buffers.refresh(): min_index = self.merge_strategy.select(buffers.get_dict()) outfile.write(buffers.unshift(min_index)) def get_file_handles(self, filenames, buffer_size): files = {} for i in range(len(filenames)): files[i] = open(filenames[i], "r", buffer_size) return files class ExternalSort: def __init__(self, block_size): self.block_size = block_size def sort(self, filename, sort_key=None): num_blocks = self.get_number_blocks(filename, self.block_size) splitter = FileSplitter(filename) splitter.split(self.block_size, sort_key) merger = FileMerger(NWayMerge()) buffer_size = self.block_size / (num_blocks + 1) merger.merge(splitter.get_block_filenames(), filename + ".out", buffer_size) splitter.cleanup() def get_number_blocks(self, filename, block_size): return (os.stat(filename).st_size / block_size) + 1 def parse_memory(string): if string[-1].lower() == "k": return int(string[:-1]) * 1024 elif string[-1].lower() == "m": return int(string[:-1]) * 1024 * 1024 elif string[-1].lower() == "g": return int(string[:-1]) * 1024 * 1024 * 1024 else: return int(string) def main(): parser = argparse.ArgumentParser() parser.add_argument( "-m", "--mem", help="amount of memory to use for sorting", default="100M" ) parser.add_argument( "filename", metavar="<filename>", nargs=1, help="name of file to sort" ) args = parser.parse_args() sorter = ExternalSort(parse_memory(args.mem)) sorter.sort(args.filename[0]) if __name__ == "__main__": main()
#!/usr/bin/env python # # Sort large text files in a minimum amount of memory # import argparse import os class FileSplitter: BLOCK_FILENAME_FORMAT = "block_{0}.dat" def __init__(self, filename): self.filename = filename self.block_filenames = [] def write_block(self, data, block_number): filename = self.BLOCK_FILENAME_FORMAT.format(block_number) with open(filename, "w") as file: file.write(data) self.block_filenames.append(filename) def get_block_filenames(self): return self.block_filenames def split(self, block_size, sort_key=None): i = 0 with open(self.filename) as file: while True: lines = file.readlines(block_size) if lines == []: break if sort_key is None: lines.sort() else: lines.sort(key=sort_key) self.write_block("".join(lines), i) i += 1 def cleanup(self): map(os.remove, self.block_filenames) class NWayMerge: def select(self, choices): min_index = -1 min_str = None for i in range(len(choices)): if min_str is None or choices[i] < min_str: min_index = i return min_index class FilesArray: def __init__(self, files): self.files = files self.empty = set() self.num_buffers = len(files) self.buffers = {i: None for i in range(self.num_buffers)} def get_dict(self): return { i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty } def refresh(self): for i in range(self.num_buffers): if self.buffers[i] is None and i not in self.empty: self.buffers[i] = self.files[i].readline() if self.buffers[i] == "": self.empty.add(i) self.files[i].close() if len(self.empty) == self.num_buffers: return False return True def unshift(self, index): value = self.buffers[index] self.buffers[index] = None return value class FileMerger: def __init__(self, merge_strategy): self.merge_strategy = merge_strategy def merge(self, filenames, outfilename, buffer_size): buffers = FilesArray(self.get_file_handles(filenames, buffer_size)) with open(outfilename, "w", buffer_size) as outfile: while buffers.refresh(): min_index = self.merge_strategy.select(buffers.get_dict()) outfile.write(buffers.unshift(min_index)) def get_file_handles(self, filenames, buffer_size): files = {} for i in range(len(filenames)): files[i] = open(filenames[i], "r", buffer_size) return files class ExternalSort: def __init__(self, block_size): self.block_size = block_size def sort(self, filename, sort_key=None): num_blocks = self.get_number_blocks(filename, self.block_size) splitter = FileSplitter(filename) splitter.split(self.block_size, sort_key) merger = FileMerger(NWayMerge()) buffer_size = self.block_size / (num_blocks + 1) merger.merge(splitter.get_block_filenames(), filename + ".out", buffer_size) splitter.cleanup() def get_number_blocks(self, filename, block_size): return (os.stat(filename).st_size / block_size) + 1 def parse_memory(string): if string[-1].lower() == "k": return int(string[:-1]) * 1024 elif string[-1].lower() == "m": return int(string[:-1]) * 1024 * 1024 elif string[-1].lower() == "g": return int(string[:-1]) * 1024 * 1024 * 1024 else: return int(string) def main(): parser = argparse.ArgumentParser() parser.add_argument( "-m", "--mem", help="amount of memory to use for sorting", default="100M" ) parser.add_argument( "filename", metavar="<filename>", nargs=1, help="name of file to sort" ) args = parser.parse_args() sorter = ExternalSort(parse_memory(args.mem)) sorter.sort(args.filename[0]) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another 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(post_fix): 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(post_fix))) for x in post_fix: 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(post_fix): 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(post_fix))) for x in post_fix: 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
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Simple multithreaded algorithm to show how the 4 phases of a genetic algorithm works (Evaluation, Selection, Crossover and Mutation) https://en.wikipedia.org/wiki/Genetic_algorithm Author: D4rkia """ from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. N_POPULATION = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. N_SELECTED = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. MUTATION_PROBABILITY = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int, str]: """ Verify that the target contains no genes besides the ones inside genes variable. >>> from string import ascii_lowercase >>> basic("doctest", ascii_lowercase, debug=False)[2] 'doctest' >>> genes = list(ascii_lowercase) >>> genes.remove("e") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e'] is not in genes list, evolution cannot converge >>> genes.remove("s") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e', 's'] is not in genes list, evolution cannot converge >>> genes.remove("t") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e', 's', 't'] is not in genes list, evolution cannot converge """ # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: raise ValueError(f"{N_POPULATION} must be bigger than {N_SELECTED}") # Verify that the target contains no genes besides the ones inside genes variable. not_in_genes_list = sorted({c for c in target if c not in genes}) if not_in_genes_list: raise ValueError( f"{not_in_genes_list} is not in genes list, evolution cannot converge" ) # Generate random starting population. population = [] for _ in range(N_POPULATION): population.append("".join([random.choice(genes) for i in range(len(target))])) # Just some logs to know what the algorithms is doing. generation, total_population = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(population) # Random population created. Now it's time to evaluate. def evaluate(item: str, main_target: str = target) -> tuple[str, float]: """ Evaluate how similar the item is with the target by just counting each char in the right position >>> evaluate("Helxo Worlx", Hello World) ["Helxo Worlx", 9] """ score = len( [g for position, g in enumerate(item) if g == main_target[position]] ) return (item, float(score)) # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. population_score = [evaluate(item) for item in population] # Check if there is a matching evolution. population_score = sorted(population_score, key=lambda x: x[1], reverse=True) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f"\nGeneration: {generation}" f"\nTotal Population:{total_population}" f"\nBest score: {population_score[0][1]}" f"\nBest string: {population_score[0][0]}" ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. population_best = population[: int(N_POPULATION / 3)] population.clear() population.extend(population_best) # Normalize population score to be between 0 and 1. population_score = [ (item, score / len(target)) for item, score in population_score ] # Select, crossover and mutate a new population. def select(parent_1: tuple[str, float]) -> list[str]: """Select the second parent and generate new population""" pop = [] # Generate more children proportionally to the fitness score. child_n = int(parent_1[1] * 100) + 1 child_n = 10 if child_n >= 10 else child_n for _ in range(child_n): parent_2 = population_score[ # noqa: B023 random.randint(0, N_SELECTED) ][0] child_1, child_2 = crossover(parent_1[0], parent_2) # Append new string to the population list. pop.append(mutate(child_1)) pop.append(mutate(child_2)) return pop def crossover(parent_1: str, parent_2: str) -> tuple[str, str]: """Slice and combine two string at a random point.""" random_slice = random.randint(0, len(parent_1) - 1) child_1 = parent_1[:random_slice] + parent_2[random_slice:] child_2 = parent_2[:random_slice] + parent_1[random_slice:] return (child_1, child_2) def mutate(child: str) -> str: """Mutate a random gene of a child with another one from the list.""" child_list = list(child) if random.uniform(0, 1) < MUTATION_PROBABILITY: child_list[random.randint(0, len(child)) - 1] = random.choice(genes) return "".join(child_list) # This is selection for i in range(N_SELECTED): population.extend(select(population_score[int(i)])) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(population) > N_POPULATION: break if __name__ == "__main__": target_str = ( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) genes_list = list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) generation, population, target = basic(target_str, genes_list) print( f"\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}" )
""" Simple multithreaded algorithm to show how the 4 phases of a genetic algorithm works (Evaluation, Selection, Crossover and Mutation) https://en.wikipedia.org/wiki/Genetic_algorithm Author: D4rkia """ from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. N_POPULATION = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. N_SELECTED = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. MUTATION_PROBABILITY = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int, str]: """ Verify that the target contains no genes besides the ones inside genes variable. >>> from string import ascii_lowercase >>> basic("doctest", ascii_lowercase, debug=False)[2] 'doctest' >>> genes = list(ascii_lowercase) >>> genes.remove("e") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e'] is not in genes list, evolution cannot converge >>> genes.remove("s") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e', 's'] is not in genes list, evolution cannot converge >>> genes.remove("t") >>> basic("test", genes) Traceback (most recent call last): ... ValueError: ['e', 's', 't'] is not in genes list, evolution cannot converge """ # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: raise ValueError(f"{N_POPULATION} must be bigger than {N_SELECTED}") # Verify that the target contains no genes besides the ones inside genes variable. not_in_genes_list = sorted({c for c in target if c not in genes}) if not_in_genes_list: raise ValueError( f"{not_in_genes_list} is not in genes list, evolution cannot converge" ) # Generate random starting population. population = [] for _ in range(N_POPULATION): population.append("".join([random.choice(genes) for i in range(len(target))])) # Just some logs to know what the algorithms is doing. generation, total_population = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(population) # Random population created. Now it's time to evaluate. def evaluate(item: str, main_target: str = target) -> tuple[str, float]: """ Evaluate how similar the item is with the target by just counting each char in the right position >>> evaluate("Helxo Worlx", Hello World) ["Helxo Worlx", 9] """ score = len( [g for position, g in enumerate(item) if g == main_target[position]] ) return (item, float(score)) # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. population_score = [evaluate(item) for item in population] # Check if there is a matching evolution. population_score = sorted(population_score, key=lambda x: x[1], reverse=True) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f"\nGeneration: {generation}" f"\nTotal Population:{total_population}" f"\nBest score: {population_score[0][1]}" f"\nBest string: {population_score[0][0]}" ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. population_best = population[: int(N_POPULATION / 3)] population.clear() population.extend(population_best) # Normalize population score to be between 0 and 1. population_score = [ (item, score / len(target)) for item, score in population_score ] # Select, crossover and mutate a new population. def select(parent_1: tuple[str, float]) -> list[str]: """Select the second parent and generate new population""" pop = [] # Generate more children proportionally to the fitness score. child_n = int(parent_1[1] * 100) + 1 child_n = 10 if child_n >= 10 else child_n for _ in range(child_n): parent_2 = population_score[ # noqa: B023 random.randint(0, N_SELECTED) ][0] child_1, child_2 = crossover(parent_1[0], parent_2) # Append new string to the population list. pop.append(mutate(child_1)) pop.append(mutate(child_2)) return pop def crossover(parent_1: str, parent_2: str) -> tuple[str, str]: """Slice and combine two string at a random point.""" random_slice = random.randint(0, len(parent_1) - 1) child_1 = parent_1[:random_slice] + parent_2[random_slice:] child_2 = parent_2[:random_slice] + parent_1[random_slice:] return (child_1, child_2) def mutate(child: str) -> str: """Mutate a random gene of a child with another one from the list.""" child_list = list(child) if random.uniform(0, 1) < MUTATION_PROBABILITY: child_list[random.randint(0, len(child)) - 1] = random.choice(genes) return "".join(child_list) # This is selection for i in range(N_SELECTED): population.extend(select(population_score[int(i)])) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(population) > N_POPULATION: break if __name__ == "__main__": target_str = ( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) genes_list = list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) generation, population, target = basic(target_str, genes_list) print( f"\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}" )
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Multiple image resizing techniques """ import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class NearestNeighbour: """ Simplest and fastest version of image resizing. Source: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation """ def __init__(self, img, dst_width: int, dst_height: int): if dst_width < 0 or dst_height < 0: raise ValueError("Destination width/height should be > 0") self.img = img self.src_w = img.shape[1] self.src_h = img.shape[0] self.dst_w = dst_width self.dst_h = dst_height self.ratio_x = self.src_w / self.dst_w self.ratio_y = self.src_h / self.dst_h self.output = self.output_img = ( np.ones((self.dst_h, self.dst_w, 3), np.uint8) * 255 ) def process(self): for i in range(self.dst_h): for j in range(self.dst_w): self.output[i][j] = self.img[self.get_y(i)][self.get_x(j)] def get_x(self, x: int) -> int: """ Get parent X coordinate for destination X :param x: Destination X coordinate :return: Parent X coordinate based on `x ratio` >>> nn = NearestNeighbour(imread("digital_image_processing/image_data/lena.jpg", ... 1), 100, 100) >>> nn.ratio_x = 0.5 >>> nn.get_x(4) 2 """ return int(self.ratio_x * x) def get_y(self, y: int) -> int: """ Get parent Y coordinate for destination Y :param y: Destination X coordinate :return: Parent X coordinate based on `y ratio` >>> nn = NearestNeighbour(imread("digital_image_processing/image_data/lena.jpg", ... 1), 100, 100) >>> nn.ratio_y = 0.5 >>> nn.get_y(4) 2 """ return int(self.ratio_y * y) if __name__ == "__main__": dst_w, dst_h = 800, 600 im = imread("image_data/lena.jpg", 1) n = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( f"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output ) waitKey(0) destroyAllWindows()
""" Multiple image resizing techniques """ import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class NearestNeighbour: """ Simplest and fastest version of image resizing. Source: https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation """ def __init__(self, img, dst_width: int, dst_height: int): if dst_width < 0 or dst_height < 0: raise ValueError("Destination width/height should be > 0") self.img = img self.src_w = img.shape[1] self.src_h = img.shape[0] self.dst_w = dst_width self.dst_h = dst_height self.ratio_x = self.src_w / self.dst_w self.ratio_y = self.src_h / self.dst_h self.output = self.output_img = ( np.ones((self.dst_h, self.dst_w, 3), np.uint8) * 255 ) def process(self): for i in range(self.dst_h): for j in range(self.dst_w): self.output[i][j] = self.img[self.get_y(i)][self.get_x(j)] def get_x(self, x: int) -> int: """ Get parent X coordinate for destination X :param x: Destination X coordinate :return: Parent X coordinate based on `x ratio` >>> nn = NearestNeighbour(imread("digital_image_processing/image_data/lena.jpg", ... 1), 100, 100) >>> nn.ratio_x = 0.5 >>> nn.get_x(4) 2 """ return int(self.ratio_x * x) def get_y(self, y: int) -> int: """ Get parent Y coordinate for destination Y :param y: Destination X coordinate :return: Parent X coordinate based on `y ratio` >>> nn = NearestNeighbour(imread("digital_image_processing/image_data/lena.jpg", ... 1), 100, 100) >>> nn.ratio_y = 0.5 >>> nn.get_y(4) 2 """ return int(self.ratio_y * y) if __name__ == "__main__": dst_w, dst_h = 800, 600 im = imread("image_data/lena.jpg", 1) n = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( f"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output ) waitKey(0) destroyAllWindows()
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations import requests valid_terms = set( """approved_at_utc approved_by author_flair_background_color author_flair_css_class author_flair_richtext author_flair_template_id author_fullname author_premium can_mod_post category clicked content_categories created_utc downs edited gilded gildings hidden hide_score is_created_from_ads_ui is_meta is_original_content is_reddit_media_domain is_video link_flair_css_class link_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title name permalink pwls quarantine saved score secure_media secure_media_embed selftext subreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type total_awards_received ups upvote_ratio url user_reports""".split() ) def get_subreddit_data( subreddit: str, limit: int = 1, age: str = "new", wanted_data: list | None = None ) -> dict: """ subreddit : Subreddit to query limit : Number of posts to fetch age : ["new", "top", "hot"] wanted_data : Get only the required data in the list """ wanted_data = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(wanted_data) - valid_terms)): raise ValueError(f"Invalid search term: {invalid_search_terms}") response = requests.get( f"https://reddit.com/r/{subreddit}/{age}.json?limit={limit}", headers={"User-agent": "A random string"}, ) if response.status_code == 429: raise requests.HTTPError data = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(limit)} data_dict = {} for id_ in range(limit): data_dict[id_] = { item: data["data"]["children"][id_]["data"][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("learnpython", wanted_data=["title", "url", "selftext"]))
from __future__ import annotations import requests valid_terms = set( """approved_at_utc approved_by author_flair_background_color author_flair_css_class author_flair_richtext author_flair_template_id author_fullname author_premium can_mod_post category clicked content_categories created_utc downs edited gilded gildings hidden hide_score is_created_from_ads_ui is_meta is_original_content is_reddit_media_domain is_video link_flair_css_class link_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title name permalink pwls quarantine saved score secure_media secure_media_embed selftext subreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type total_awards_received ups upvote_ratio url user_reports""".split() ) def get_subreddit_data( subreddit: str, limit: int = 1, age: str = "new", wanted_data: list | None = None ) -> dict: """ subreddit : Subreddit to query limit : Number of posts to fetch age : ["new", "top", "hot"] wanted_data : Get only the required data in the list """ wanted_data = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(wanted_data) - valid_terms)): raise ValueError(f"Invalid search term: {invalid_search_terms}") response = requests.get( f"https://reddit.com/r/{subreddit}/{age}.json?limit={limit}", headers={"User-agent": "A random string"}, ) if response.status_code == 429: raise requests.HTTPError data = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(limit)} data_dict = {} for id_ in range(limit): data_dict[id_] = { item: data["data"]["children"][id_]["data"][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("learnpython", wanted_data=["title", "url", "selftext"]))
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Algorithms to determine if a string is palindrome test_data = { "MALAYALAM": True, "String": False, "rotor": True, "level": True, "A": True, "BB": True, "ABC": False, "amanaplanacanalpanama": True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def is_palindrome(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome(key) is value for key, value in test_data.items()) True """ start_i = 0 end_i = len(s) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def is_palindrome_recursive(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_recursive(key) is value for key, value in test_data.items()) True """ if len(s) <= 1: return True if s[0] == s[len(s) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False def is_palindrome_slice(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_slice(key) is value for key, value in test_data.items()) True """ return s == s[::-1] if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f"{key:21} {value}") print("a man a plan a canal panama")
# Algorithms to determine if a string is palindrome test_data = { "MALAYALAM": True, "String": False, "rotor": True, "level": True, "A": True, "BB": True, "ABC": False, "amanaplanacanalpanama": True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def is_palindrome(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome(key) is value for key, value in test_data.items()) True """ start_i = 0 end_i = len(s) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def is_palindrome_recursive(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_recursive(key) is value for key, value in test_data.items()) True """ if len(s) <= 1: return True if s[0] == s[len(s) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False def is_palindrome_slice(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_slice(key) is value for key, value in test_data.items()) True """ return s == s[::-1] if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f"{key:21} {value}") print("a man a plan a canal panama")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Python implementation of a sort algorithm. Best Case Scenario : O(n) Worst Case Scenario : O(n^2) because native Python functions:min, max and remove are already O(n) """ def merge_sort(collection): """Pure implementation of the fastest merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: a collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_sort([]) [] >>> merge_sort([-2, -5, -45]) [-45, -5, -2] """ start, end = [], [] while len(collection) > 1: min_one, max_one = min(collection), max(collection) start.append(min_one) end.append(max_one) collection.remove(min_one) collection.remove(max_one) end.reverse() return start + collection + end if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
""" Python implementation of a sort algorithm. Best Case Scenario : O(n) Worst Case Scenario : O(n^2) because native Python functions:min, max and remove are already O(n) """ def merge_sort(collection): """Pure implementation of the fastest merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: a collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_sort([]) [] >>> merge_sort([-2, -5, -45]) [-45, -5, -2] """ start, end = [], [] while len(collection) > 1: min_one, max_one = min(collection), max(collection) start.append(min_one) end.append(max_one) collection.remove(min_one) collection.remove(max_one) end.reverse() return start + collection + end if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#
#
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Question: Given a binary matrix mat of size n * m, find out the maximum size square sub-matrix with all 1s. --- Example 1: Input: n = 2, m = 2 mat = [[1, 1], [1, 1]] Output: 2 Explanation: The maximum size of the square sub-matrix is 2. The matrix itself is the maximum sized sub-matrix in this case. --- Example 2 Input: n = 2, m = 2 mat = [[0, 0], [0, 0]] Output: 0 Explanation: There is no 1 in the matrix. Approach: We initialize another matrix (dp) with the same dimensions as the original one initialized with all 0’s. dp_array(i,j) represents the side length of the maximum square whose bottom right corner is the cell with index (i,j) in the original matrix. Starting from index (0,0), for every 1 found in the original matrix, we update the value of the current element as dp_array(i,j)=dp_array(dp(i−1,j),dp_array(i−1,j−1),dp_array(i,j−1)) + 1. """ def largest_square_area_in_matrix_top_down_approch( rows: int, cols: int, mat: list[list[int]] ) -> int: """ Function updates the largest_square_area[0], if recursive call found square with maximum area. We aren't using dp_array here, so the time complexity would be exponential. >>> largest_square_area_in_matrix_top_down_approch(2, 2, [[1,1], [1,1]]) 2 >>> largest_square_area_in_matrix_top_down_approch(2, 2, [[0,0], [0,0]]) 0 """ def update_area_of_max_square(row: int, col: int) -> int: # BASE CASE if row >= rows or col >= cols: return 0 right = update_area_of_max_square(row, col + 1) diagonal = update_area_of_max_square(row + 1, col + 1) down = update_area_of_max_square(row + 1, col) if mat[row][col]: sub_problem_sol = 1 + min([right, diagonal, down]) largest_square_area[0] = max(largest_square_area[0], sub_problem_sol) return sub_problem_sol else: return 0 largest_square_area = [0] update_area_of_max_square(0, 0) return largest_square_area[0] def largest_square_area_in_matrix_top_down_approch_with_dp( rows: int, cols: int, mat: list[list[int]] ) -> int: """ Function updates the largest_square_area[0], if recursive call found square with maximum area. We are using dp_array here, so the time complexity would be O(N^2). >>> largest_square_area_in_matrix_top_down_approch_with_dp(2, 2, [[1,1], [1,1]]) 2 >>> largest_square_area_in_matrix_top_down_approch_with_dp(2, 2, [[0,0], [0,0]]) 0 """ def update_area_of_max_square_using_dp_array( row: int, col: int, dp_array: list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] right = update_area_of_max_square_using_dp_array(row, col + 1, dp_array) diagonal = update_area_of_max_square_using_dp_array(row + 1, col + 1, dp_array) down = update_area_of_max_square_using_dp_array(row + 1, col, dp_array) if mat[row][col]: sub_problem_sol = 1 + min([right, diagonal, down]) largest_square_area[0] = max(largest_square_area[0], sub_problem_sol) dp_array[row][col] = sub_problem_sol return sub_problem_sol else: return 0 largest_square_area = [0] dp_array = [[-1] * cols for _ in range(rows)] update_area_of_max_square_using_dp_array(0, 0, dp_array) return largest_square_area[0] def largest_square_area_in_matrix_bottom_up( rows: int, cols: int, mat: list[list[int]] ) -> int: """ Function updates the largest_square_area, using bottom up approach. >>> largest_square_area_in_matrix_bottom_up(2, 2, [[1,1], [1,1]]) 2 >>> largest_square_area_in_matrix_bottom_up(2, 2, [[0,0], [0,0]]) 0 """ dp_array = [[0] * (cols + 1) for _ in range(rows + 1)] largest_square_area = 0 for row in range(rows - 1, -1, -1): for col in range(cols - 1, -1, -1): right = dp_array[row][col + 1] diagonal = dp_array[row + 1][col + 1] bottom = dp_array[row + 1][col] if mat[row][col] == 1: dp_array[row][col] = 1 + min(right, diagonal, bottom) largest_square_area = max(dp_array[row][col], largest_square_area) else: dp_array[row][col] = 0 return largest_square_area def largest_square_area_in_matrix_bottom_up_space_optimization( rows: int, cols: int, mat: list[list[int]] ) -> int: """ Function updates the largest_square_area, using bottom up approach. with space optimization. >>> largest_square_area_in_matrix_bottom_up_space_optimization(2, 2, [[1,1], [1,1]]) 2 >>> largest_square_area_in_matrix_bottom_up_space_optimization(2, 2, [[0,0], [0,0]]) 0 """ current_row = [0] * (cols + 1) next_row = [0] * (cols + 1) largest_square_area = 0 for row in range(rows - 1, -1, -1): for col in range(cols - 1, -1, -1): right = current_row[col + 1] diagonal = next_row[col + 1] bottom = next_row[col] if mat[row][col] == 1: current_row[col] = 1 + min(right, diagonal, bottom) largest_square_area = max(current_row[col], largest_square_area) else: current_row[col] = 0 next_row = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
""" Question: Given a binary matrix mat of size n * m, find out the maximum size square sub-matrix with all 1s. --- Example 1: Input: n = 2, m = 2 mat = [[1, 1], [1, 1]] Output: 2 Explanation: The maximum size of the square sub-matrix is 2. The matrix itself is the maximum sized sub-matrix in this case. --- Example 2 Input: n = 2, m = 2 mat = [[0, 0], [0, 0]] Output: 0 Explanation: There is no 1 in the matrix. Approach: We initialize another matrix (dp) with the same dimensions as the original one initialized with all 0’s. dp_array(i,j) represents the side length of the maximum square whose bottom right corner is the cell with index (i,j) in the original matrix. Starting from index (0,0), for every 1 found in the original matrix, we update the value of the current element as dp_array(i,j)=dp_array(dp(i−1,j),dp_array(i−1,j−1),dp_array(i,j−1)) + 1. """ def largest_square_area_in_matrix_top_down_approch( rows: int, cols: int, mat: list[list[int]] ) -> int: """ Function updates the largest_square_area[0], if recursive call found square with maximum area. We aren't using dp_array here, so the time complexity would be exponential. >>> largest_square_area_in_matrix_top_down_approch(2, 2, [[1,1], [1,1]]) 2 >>> largest_square_area_in_matrix_top_down_approch(2, 2, [[0,0], [0,0]]) 0 """ def update_area_of_max_square(row: int, col: int) -> int: # BASE CASE if row >= rows or col >= cols: return 0 right = update_area_of_max_square(row, col + 1) diagonal = update_area_of_max_square(row + 1, col + 1) down = update_area_of_max_square(row + 1, col) if mat[row][col]: sub_problem_sol = 1 + min([right, diagonal, down]) largest_square_area[0] = max(largest_square_area[0], sub_problem_sol) return sub_problem_sol else: return 0 largest_square_area = [0] update_area_of_max_square(0, 0) return largest_square_area[0] def largest_square_area_in_matrix_top_down_approch_with_dp( rows: int, cols: int, mat: list[list[int]] ) -> int: """ Function updates the largest_square_area[0], if recursive call found square with maximum area. We are using dp_array here, so the time complexity would be O(N^2). >>> largest_square_area_in_matrix_top_down_approch_with_dp(2, 2, [[1,1], [1,1]]) 2 >>> largest_square_area_in_matrix_top_down_approch_with_dp(2, 2, [[0,0], [0,0]]) 0 """ def update_area_of_max_square_using_dp_array( row: int, col: int, dp_array: list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] right = update_area_of_max_square_using_dp_array(row, col + 1, dp_array) diagonal = update_area_of_max_square_using_dp_array(row + 1, col + 1, dp_array) down = update_area_of_max_square_using_dp_array(row + 1, col, dp_array) if mat[row][col]: sub_problem_sol = 1 + min([right, diagonal, down]) largest_square_area[0] = max(largest_square_area[0], sub_problem_sol) dp_array[row][col] = sub_problem_sol return sub_problem_sol else: return 0 largest_square_area = [0] dp_array = [[-1] * cols for _ in range(rows)] update_area_of_max_square_using_dp_array(0, 0, dp_array) return largest_square_area[0] def largest_square_area_in_matrix_bottom_up( rows: int, cols: int, mat: list[list[int]] ) -> int: """ Function updates the largest_square_area, using bottom up approach. >>> largest_square_area_in_matrix_bottom_up(2, 2, [[1,1], [1,1]]) 2 >>> largest_square_area_in_matrix_bottom_up(2, 2, [[0,0], [0,0]]) 0 """ dp_array = [[0] * (cols + 1) for _ in range(rows + 1)] largest_square_area = 0 for row in range(rows - 1, -1, -1): for col in range(cols - 1, -1, -1): right = dp_array[row][col + 1] diagonal = dp_array[row + 1][col + 1] bottom = dp_array[row + 1][col] if mat[row][col] == 1: dp_array[row][col] = 1 + min(right, diagonal, bottom) largest_square_area = max(dp_array[row][col], largest_square_area) else: dp_array[row][col] = 0 return largest_square_area def largest_square_area_in_matrix_bottom_up_space_optimization( rows: int, cols: int, mat: list[list[int]] ) -> int: """ Function updates the largest_square_area, using bottom up approach. with space optimization. >>> largest_square_area_in_matrix_bottom_up_space_optimization(2, 2, [[1,1], [1,1]]) 2 >>> largest_square_area_in_matrix_bottom_up_space_optimization(2, 2, [[0,0], [0,0]]) 0 """ current_row = [0] * (cols + 1) next_row = [0] * (cols + 1) largest_square_area = 0 for row in range(rows - 1, -1, -1): for col in range(cols - 1, -1, -1): right = current_row[col + 1] diagonal = next_row[col + 1] bottom = next_row[col] if mat[row][col] == 1: current_row[col] = 1 + min(right, diagonal, bottom) largest_square_area = max(current_row[col], largest_square_area) else: current_row[col] = 0 next_row = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,945
Raise error not string
### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-11-02T16:49:17Z"
"2022-11-06T14:54:44Z"
51708530b6a46a5e53d12e750521a11c6bf5c986
daa1c7529ac6491338adb81622d5041a4ba1f446
Raise error not string. ### Describe your change: Replaces string errors with raising exceptions * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from collections.abc import Sequence def max_subarray_sum(nums: Sequence[int]) -> int: """Return the maximum possible sum amongst all non - empty subarrays. Raises: ValueError: when nums is empty. >>> max_subarray_sum([1,2,3,4,-2]) 10 >>> max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4]) 6 """ if not nums: raise ValueError("Input sequence should not be empty") curr_max = ans = nums[0] nums_len = len(nums) for i in range(1, nums_len): num = nums[i] curr_max = max(curr_max + num, num) ans = max(curr_max, ans) return ans if __name__ == "__main__": n = int(input("Enter number of elements : ").strip()) array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n] print(max_subarray_sum(array))
from collections.abc import Sequence def max_subarray_sum(nums: Sequence[int]) -> int: """Return the maximum possible sum amongst all non - empty subarrays. Raises: ValueError: when nums is empty. >>> max_subarray_sum([1,2,3,4,-2]) 10 >>> max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4]) 6 """ if not nums: raise ValueError("Input sequence should not be empty") curr_max = ans = nums[0] nums_len = len(nums) for i in range(1, nums_len): num = nums[i] curr_max = max(curr_max + num, num) ans = max(curr_max, ans) return ans if __name__ == "__main__": n = int(input("Enter number of elements : ").strip()) array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n] print(max_subarray_sum(array))
-1