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
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Implementation of median filter algorithm """ from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import divide, int8, multiply, ravel, sort, zeros_like def median_filter(gray_img, mask=3): """ :param gray_img: gray image :param mask: mask size :return: image with median filter """ # set image borders bd = int(mask / 2) # copy image size median_img = zeros_like(gray_img) for i in range(bd, gray_img.shape[0] - bd): for j in range(bd, gray_img.shape[1] - bd): # get mask according with mask kernel = ravel(gray_img[i - bd : i + bd + 1, j - bd : j + bd + 1]) # calculate mask median median = sort(kernel)[int8(divide((multiply(mask, mask)), 2) + 1)] median_img[i, j] = median return median_img if __name__ == "__main__": # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size median3x3 = median_filter(gray, 3) median5x5 = median_filter(gray, 5) # show result images imshow("median filter with 3x3 mask", median3x3) imshow("median filter with 5x5 mask", median5x5) waitKey(0)
""" Implementation of median filter algorithm """ from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import divide, int8, multiply, ravel, sort, zeros_like def median_filter(gray_img, mask=3): """ :param gray_img: gray image :param mask: mask size :return: image with median filter """ # set image borders bd = int(mask / 2) # copy image size median_img = zeros_like(gray_img) for i in range(bd, gray_img.shape[0] - bd): for j in range(bd, gray_img.shape[1] - bd): # get mask according with mask kernel = ravel(gray_img[i - bd : i + bd + 1, j - bd : j + bd + 1]) # calculate mask median median = sort(kernel)[int8(divide((multiply(mask, mask)), 2) + 1)] median_img[i, j] = median return median_img if __name__ == "__main__": # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size median3x3 = median_filter(gray, 3) median5x5 = median_filter(gray, 5) # show result images imshow("median filter with 3x3 mask", median3x3) imshow("median filter with 5x5 mask", median5x5) waitKey(0)
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Mish Activation Function Use Case: Improved version of the ReLU activation function used in Computer Vision. For more detailed information, you can refer to the following link: https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Mish """ import numpy as np def mish(vector: np.ndarray) -> np.ndarray: """ Implements the Mish activation function. Parameters: vector (np.ndarray): The input array for Mish activation. Returns: np.ndarray: The input array after applying the Mish activation. Formula: f(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + e^x)) Examples: >>> mish(vector=np.array([2.3,0.6,-2,-3.8])) array([ 2.26211893, 0.46613649, -0.25250148, -0.08405831]) >>> mish(np.array([-9.2, -0.3, 0.45, -4.56])) array([-0.00092952, -0.15113318, 0.33152014, -0.04745745]) """ return vector * np.tanh(np.log(1 + np.exp(vector))) if __name__ == "__main__": import doctest doctest.testmod()
""" Mish Activation Function Use Case: Improved version of the ReLU activation function used in Computer Vision. For more detailed information, you can refer to the following link: https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Mish """ import numpy as np def mish(vector: np.ndarray) -> np.ndarray: """ Implements the Mish activation function. Parameters: vector (np.ndarray): The input array for Mish activation. Returns: np.ndarray: The input array after applying the Mish activation. Formula: f(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + e^x)) Examples: >>> mish(vector=np.array([2.3,0.6,-2,-3.8])) array([ 2.26211893, 0.46613649, -0.25250148, -0.08405831]) >>> mish(np.array([-9.2, -0.3, 0.45, -4.56])) array([-0.00092952, -0.15113318, 0.33152014, -0.04745745]) """ return vector * np.tanh(np.log(1 + np.exp(vector))) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
from __future__ import annotations import re def natural_sort(input_list: list[str]) -> list[str]: """ Sort the given list of strings in the way that humans expect. The normal Python sort algorithm sorts lexicographically, so you might not get the results that you expect... >>> example1 = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] >>> sorted(example1) ['1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '2 ft 7 in', '7 ft 6 in'] >>> # The natural sort algorithm sort based on meaning and not computer code point. >>> natural_sort(example1) ['1 ft 5 in', '2 ft 7 in', '2 ft 11 in', '7 ft 6 in', '10 ft 2 in'] >>> example2 = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9'] >>> sorted(example2) ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9'] >>> natural_sort(example2) ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13'] """ def alphanum_key(key): return [int(s) if s.isdigit() else s.lower() for s in re.split("([0-9]+)", key)] return sorted(input_list, key=alphanum_key) if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations import re def natural_sort(input_list: list[str]) -> list[str]: """ Sort the given list of strings in the way that humans expect. The normal Python sort algorithm sorts lexicographically, so you might not get the results that you expect... >>> example1 = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] >>> sorted(example1) ['1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '2 ft 7 in', '7 ft 6 in'] >>> # The natural sort algorithm sort based on meaning and not computer code point. >>> natural_sort(example1) ['1 ft 5 in', '2 ft 7 in', '2 ft 11 in', '7 ft 6 in', '10 ft 2 in'] >>> example2 = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9'] >>> sorted(example2) ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9'] >>> natural_sort(example2) ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13'] """ def alphanum_key(key): return [int(s) if s.isdigit() else s.lower() for s in re.split("([0-9]+)", key)] return sorted(input_list, key=alphanum_key) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
from __future__ import annotations def median(nums: list) -> int | float: """ Find median of a list of numbers. Wiki: https://en.wikipedia.org/wiki/Median >>> median([0]) 0 >>> median([4, 1, 3, 2]) 2.5 >>> median([2, 70, 6, 50, 20, 8, 4]) 8 Args: nums: List of nums Returns: Median. """ # The sorted function returns list[SupportsRichComparisonT@sorted] # which does not support `+` sorted_list: list[int] = sorted(nums) length = len(sorted_list) mid_index = length >> 1 return ( (sorted_list[mid_index] + sorted_list[mid_index - 1]) / 2 if length % 2 == 0 else sorted_list[mid_index] ) def main(): import doctest doctest.testmod() if __name__ == "__main__": main()
from __future__ import annotations def median(nums: list) -> int | float: """ Find median of a list of numbers. Wiki: https://en.wikipedia.org/wiki/Median >>> median([0]) 0 >>> median([4, 1, 3, 2]) 2.5 >>> median([2, 70, 6, 50, 20, 8, 4]) 8 Args: nums: List of nums Returns: Median. """ # The sorted function returns list[SupportsRichComparisonT@sorted] # which does not support `+` sorted_list: list[int] = sorted(nums) length = len(sorted_list) mid_index = length >> 1 return ( (sorted_list[mid_index] + sorted_list[mid_index - 1]) / 2 if length % 2 == 0 else sorted_list[mid_index] ) def main(): import doctest doctest.testmod() if __name__ == "__main__": main()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" https://en.wikipedia.org/wiki/Cocktail_shaker_sort """ def cocktail_shaker_sort(unsorted: list) -> list: """ Pure implementation of the cocktail shaker sort algorithm in Python. >>> cocktail_shaker_sort([4, 5, 2, 1, 2]) [1, 2, 2, 4, 5] >>> cocktail_shaker_sort([-4, 5, 0, 1, 2, 11]) [-4, 0, 1, 2, 5, 11] >>> cocktail_shaker_sort([0.1, -2.4, 4.4, 2.2]) [-2.4, 0.1, 2.2, 4.4] >>> cocktail_shaker_sort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> cocktail_shaker_sort([-4, -5, -24, -7, -11]) [-24, -11, -7, -5, -4] """ for i in range(len(unsorted) - 1, 0, -1): swapped = False for j in range(i, 0, -1): if unsorted[j] < unsorted[j - 1]: unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j] swapped = True for j in range(i): if unsorted[j] > unsorted[j + 1]: unsorted[j], unsorted[j + 1] = unsorted[j + 1], unsorted[j] swapped = True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{cocktail_shaker_sort(unsorted) = }")
""" https://en.wikipedia.org/wiki/Cocktail_shaker_sort """ def cocktail_shaker_sort(unsorted: list) -> list: """ Pure implementation of the cocktail shaker sort algorithm in Python. >>> cocktail_shaker_sort([4, 5, 2, 1, 2]) [1, 2, 2, 4, 5] >>> cocktail_shaker_sort([-4, 5, 0, 1, 2, 11]) [-4, 0, 1, 2, 5, 11] >>> cocktail_shaker_sort([0.1, -2.4, 4.4, 2.2]) [-2.4, 0.1, 2.2, 4.4] >>> cocktail_shaker_sort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> cocktail_shaker_sort([-4, -5, -24, -7, -11]) [-24, -11, -7, -5, -4] """ for i in range(len(unsorted) - 1, 0, -1): swapped = False for j in range(i, 0, -1): if unsorted[j] < unsorted[j - 1]: unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j] swapped = True for j in range(i): if unsorted[j] > unsorted[j + 1]: unsorted[j], unsorted[j + 1] = unsorted[j + 1], unsorted[j] swapped = True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{cocktail_shaker_sort(unsorted) = }")
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
import doctest import projectq from projectq.ops import H, Measure def get_random_number(quantum_engine: projectq.cengines._main.MainEngine) -> int: """ >>> isinstance(get_random_number(projectq.MainEngine()), int) True """ qubit = quantum_engine.allocate_qubit() H | qubit Measure | qubit return int(qubit) if __name__ == "__main__": doctest.testmod() # initialises a new quantum backend quantum_engine = projectq.MainEngine() # Generate a list of 10 random numbers random_numbers_list = [get_random_number(quantum_engine) for _ in range(10)] # Flushes the quantum engine from memory quantum_engine.flush() print("Random numbers", random_numbers_list)
import doctest import projectq from projectq.ops import H, Measure def get_random_number(quantum_engine: projectq.cengines._main.MainEngine) -> int: """ >>> isinstance(get_random_number(projectq.MainEngine()), int) True """ qubit = quantum_engine.allocate_qubit() H | qubit Measure | qubit return int(qubit) if __name__ == "__main__": doctest.testmod() # initialises a new quantum backend quantum_engine = projectq.MainEngine() # Generate a list of 10 random numbers random_numbers_list = [get_random_number(quantum_engine) for _ in range(10)] # Flushes the quantum engine from memory quantum_engine.flush() print("Random numbers", random_numbers_list)
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" In this problem, we want to determine all possible permutations of the given sequence. We use backtracking to solve this problem. Time complexity: O(n! * n), where n denotes the length of the given sequence. """ from __future__ import annotations def generate_all_permutations(sequence: list[int | str]) -> None: create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))]) def create_state_space_tree( sequence: list[int | str], current_sequence: list[int | str], index: int, index_used: list[int], ) -> None: """ Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly len(sequence) - index children. It terminates when it reaches the end of the given sequence. """ if index == len(sequence): print(current_sequence) return for i in range(len(sequence)): if not index_used[i]: current_sequence.append(sequence[i]) index_used[i] = True create_state_space_tree(sequence, current_sequence, index + 1, index_used) current_sequence.pop() index_used[i] = False """ remove the comment to take an input from the user print("Enter the elements") sequence = list(map(int, input().split())) """ sequence: list[int | str] = [3, 1, 2, 4] generate_all_permutations(sequence) sequence_2: list[int | str] = ["A", "B", "C"] generate_all_permutations(sequence_2)
""" In this problem, we want to determine all possible permutations of the given sequence. We use backtracking to solve this problem. Time complexity: O(n! * n), where n denotes the length of the given sequence. """ from __future__ import annotations def generate_all_permutations(sequence: list[int | str]) -> None: create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))]) def create_state_space_tree( sequence: list[int | str], current_sequence: list[int | str], index: int, index_used: list[int], ) -> None: """ Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly len(sequence) - index children. It terminates when it reaches the end of the given sequence. """ if index == len(sequence): print(current_sequence) return for i in range(len(sequence)): if not index_used[i]: current_sequence.append(sequence[i]) index_used[i] = True create_state_space_tree(sequence, current_sequence, index + 1, index_used) current_sequence.pop() index_used[i] = False """ remove the comment to take an input from the user print("Enter the elements") sequence = list(map(int, input().split())) """ sequence: list[int | str] = [3, 1, 2, 4] generate_all_permutations(sequence) sequence_2: list[int | str] = ["A", "B", "C"] generate_all_permutations(sequence_2)
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" A Hamming number is a positive integer of the form 2^i*3^j*5^k, for some non-negative integers i, j, and k. They are often referred to as regular numbers. More info at: https://en.wikipedia.org/wiki/Regular_number. """ def hamming(n_element: int) -> list: """ This function creates an ordered list of n length as requested, and afterwards returns the last value of the list. It must be given a positive integer. :param n_element: The number of elements on the list :return: The nth element of the list >>> hamming(5) [1, 2, 3, 4, 5] >>> hamming(10) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] >>> hamming(15) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] """ n_element = int(n_element) if n_element < 1: my_error = ValueError("a should be a positive number") raise my_error hamming_list = [1] i, j, k = (0, 0, 0) index = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2, hamming_list[j] * 3, hamming_list[k] * 5) ) index += 1 return hamming_list if __name__ == "__main__": n = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") hamming_numbers = hamming(int(n)) print("-----------------------------------------------------") print(f"The list with nth numbers is: {hamming_numbers}") print("-----------------------------------------------------")
""" A Hamming number is a positive integer of the form 2^i*3^j*5^k, for some non-negative integers i, j, and k. They are often referred to as regular numbers. More info at: https://en.wikipedia.org/wiki/Regular_number. """ def hamming(n_element: int) -> list: """ This function creates an ordered list of n length as requested, and afterwards returns the last value of the list. It must be given a positive integer. :param n_element: The number of elements on the list :return: The nth element of the list >>> hamming(5) [1, 2, 3, 4, 5] >>> hamming(10) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] >>> hamming(15) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] """ n_element = int(n_element) if n_element < 1: my_error = ValueError("a should be a positive number") raise my_error hamming_list = [1] i, j, k = (0, 0, 0) index = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2, hamming_list[j] * 3, hamming_list[k] * 5) ) index += 1 return hamming_list if __name__ == "__main__": n = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") hamming_numbers = hamming(int(n)) print("-----------------------------------------------------") print(f"The list with nth numbers is: {hamming_numbers}") print("-----------------------------------------------------")
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Project Euler Problem 131: https://projecteuler.net/problem=131 There are some prime values, p, for which there exists a positive integer, n, such that the expression n^3 + n^2p is a perfect cube. For example, when p = 19, 8^3 + 8^2 x 19 = 12^3. What is perhaps most surprising is that for each prime with this property the value of n is unique, and there are only four such primes below one-hundred. How many primes below one million have this remarkable property? """ from math import isqrt def is_prime(number: int) -> bool: """ Determines whether number is prime >>> is_prime(3) True >>> is_prime(4) False """ return all(number % divisor != 0 for divisor in range(2, isqrt(number) + 1)) def solution(max_prime: int = 10**6) -> int: """ Returns number of primes below max_prime with the property >>> solution(100) 4 """ primes_count = 0 cube_index = 1 prime_candidate = 7 while prime_candidate < max_prime: primes_count += is_prime(prime_candidate) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 131: https://projecteuler.net/problem=131 There are some prime values, p, for which there exists a positive integer, n, such that the expression n^3 + n^2p is a perfect cube. For example, when p = 19, 8^3 + 8^2 x 19 = 12^3. What is perhaps most surprising is that for each prime with this property the value of n is unique, and there are only four such primes below one-hundred. How many primes below one million have this remarkable property? """ from math import isqrt def is_prime(number: int) -> bool: """ Determines whether number is prime >>> is_prime(3) True >>> is_prime(4) False """ return all(number % divisor != 0 for divisor in range(2, isqrt(number) + 1)) def solution(max_prime: int = 10**6) -> int: """ Returns number of primes below max_prime with the property >>> solution(100) 4 """ primes_count = 0 cube_index = 1 prime_candidate = 7 while prime_candidate < max_prime: primes_count += is_prime(prime_candidate) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" A hexagonal number sequence is a sequence of figurate numbers where the nth hexagonal number hβ‚™ is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots, when the hexagons are overlaid so that they share one vertex. Calculates the hexagonal numbers sequence with a formula hβ‚™ = n(2n-1) where: hβ‚™ --> is nth element of the sequence n --> is the number of element in the sequence reference-->"Hexagonal number" Wikipedia <https://en.wikipedia.org/wiki/Hexagonal_number> """ def hexagonal_numbers(length: int) -> list[int]: """ :param len: max number of elements :type len: int :return: Hexagonal numbers as a list Tests: >>> hexagonal_numbers(10) [0, 1, 6, 15, 28, 45, 66, 91, 120, 153] >>> hexagonal_numbers(5) [0, 1, 6, 15, 28] >>> hexagonal_numbers(0) Traceback (most recent call last): ... ValueError: Length must be a positive integer. """ if length <= 0 or not isinstance(length, int): raise ValueError("Length must be a positive integer.") return [n * (2 * n - 1) for n in range(length)] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
""" A hexagonal number sequence is a sequence of figurate numbers where the nth hexagonal number hβ‚™ is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots, when the hexagons are overlaid so that they share one vertex. Calculates the hexagonal numbers sequence with a formula hβ‚™ = n(2n-1) where: hβ‚™ --> is nth element of the sequence n --> is the number of element in the sequence reference-->"Hexagonal number" Wikipedia <https://en.wikipedia.org/wiki/Hexagonal_number> """ def hexagonal_numbers(length: int) -> list[int]: """ :param len: max number of elements :type len: int :return: Hexagonal numbers as a list Tests: >>> hexagonal_numbers(10) [0, 1, 6, 15, 28, 45, 66, 91, 120, 153] >>> hexagonal_numbers(5) [0, 1, 6, 15, 28] >>> hexagonal_numbers(0) Traceback (most recent call last): ... ValueError: Length must be a positive integer. """ if length <= 0 or not isinstance(length, int): raise ValueError("Length must be a positive integer.") return [n * (2 * n - 1) for n in range(length)] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
beautifulsoup4 fake_useragent imageio keras lxml matplotlib numpy opencv-python pandas pillow projectq qiskit ; python_version < '3.12' qiskit-aer ; python_version < '3.12' requests rich scikit-fuzzy scikit-learn statsmodels sympy tensorflow ; python_version < '3.12' texttable tweepy xgboost yulewalker
beautifulsoup4 fake_useragent imageio keras lxml matplotlib numpy opencv-python pandas pillow projectq qiskit ; python_version < '3.12' qiskit-aer ; python_version < '3.12' requests rich scikit-fuzzy scikit-learn statsmodels sympy tensorflow ; python_version < '3.12' texttable tweepy xgboost yulewalker
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
from json import loads from pathlib import Path import numpy as np from yulewalker import yulewalk from audio_filters.butterworth_filter import make_highpass from audio_filters.iir_filter import IIRFilter data = loads((Path(__file__).resolve().parent / "loudness_curve.json").read_text()) class EqualLoudnessFilter: r""" An equal-loudness filter which compensates for the human ear's non-linear response to sound. This filter corrects this by cascading a yulewalk filter and a butterworth filter. Designed for use with samplerate of 44.1kHz and above. If you're using a lower samplerate, use with caution. Code based on matlab implementation at https://bit.ly/3eqh2HU (url shortened for ruff) Target curve: https://i.imgur.com/3g2VfaM.png Yulewalk response: https://i.imgur.com/J9LnJ4C.png Butterworth and overall response: https://i.imgur.com/3g2VfaM.png Images and original matlab implementation by David Robinson, 2001 """ def __init__(self, samplerate: int = 44100) -> None: self.yulewalk_filter = IIRFilter(10) self.butterworth_filter = make_highpass(150, samplerate) # pad the data to nyquist curve_freqs = np.array(data["frequencies"] + [max(20000.0, samplerate / 2)]) curve_gains = np.array(data["gains"] + [140]) # Convert to angular frequency freqs_normalized = curve_freqs / samplerate * 2 # Invert the curve and normalize to 0dB gains_normalized = np.power(10, (np.min(curve_gains) - curve_gains) / 20) # Scipy's `yulewalk` function is a stub, so we're using the # `yulewalker` library instead. # This function computes the coefficients using a least-squares # fit to the specified curve. ya, yb = yulewalk(10, freqs_normalized, gains_normalized) self.yulewalk_filter.set_coefficients(ya, yb) def process(self, sample: float) -> float: """ Process a single sample through both filters >>> filt = EqualLoudnessFilter() >>> filt.process(0.0) 0.0 """ tmp = self.yulewalk_filter.process(sample) return self.butterworth_filter.process(tmp)
from json import loads from pathlib import Path import numpy as np from yulewalker import yulewalk from audio_filters.butterworth_filter import make_highpass from audio_filters.iir_filter import IIRFilter data = loads((Path(__file__).resolve().parent / "loudness_curve.json").read_text()) class EqualLoudnessFilter: r""" An equal-loudness filter which compensates for the human ear's non-linear response to sound. This filter corrects this by cascading a yulewalk filter and a butterworth filter. Designed for use with samplerate of 44.1kHz and above. If you're using a lower samplerate, use with caution. Code based on matlab implementation at https://bit.ly/3eqh2HU (url shortened for ruff) Target curve: https://i.imgur.com/3g2VfaM.png Yulewalk response: https://i.imgur.com/J9LnJ4C.png Butterworth and overall response: https://i.imgur.com/3g2VfaM.png Images and original matlab implementation by David Robinson, 2001 """ def __init__(self, samplerate: int = 44100) -> None: self.yulewalk_filter = IIRFilter(10) self.butterworth_filter = make_highpass(150, samplerate) # pad the data to nyquist curve_freqs = np.array(data["frequencies"] + [max(20000.0, samplerate / 2)]) curve_gains = np.array(data["gains"] + [140]) # Convert to angular frequency freqs_normalized = curve_freqs / samplerate * 2 # Invert the curve and normalize to 0dB gains_normalized = np.power(10, (np.min(curve_gains) - curve_gains) / 20) # Scipy's `yulewalk` function is a stub, so we're using the # `yulewalker` library instead. # This function computes the coefficients using a least-squares # fit to the specified curve. ya, yb = yulewalk(10, freqs_normalized, gains_normalized) self.yulewalk_filter.set_coefficients(ya, yb) def process(self, sample: float) -> float: """ Process a single sample through both filters >>> filt = EqualLoudnessFilter() >>> filt.process(0.0) 0.0 """ tmp = self.yulewalk_filter.process(sample) return self.butterworth_filter.process(tmp)
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Self Powers Problem 48 The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. """ def solution(): """ Returns the last 10 digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. >>> solution() '9110846700' """ total = 0 for i in range(1, 1001): total += i**i return str(total)[-10:] if __name__ == "__main__": print(solution())
""" Self Powers Problem 48 The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. """ def solution(): """ Returns the last 10 digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. >>> solution() '9110846700' """ total = 0 for i in range(1, 1001): total += i**i return str(total)[-10:] if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" A Trie/Prefix Tree is a kind of search tree used to provide quick lookup of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity making it impractical in practice. It however provides O(max(search_string, length of longest word)) lookup time making it an optimal approach when space is not an issue. """ class TrieNode: def __init__(self) -> None: self.nodes: dict[str, TrieNode] = {} # Mapping from char to TrieNode self.is_leaf = False def insert_many(self, words: list[str]) -> None: """ Inserts a list of words into the Trie :param words: list of string words :return: None """ for word in words: self.insert(word) def insert(self, word: str) -> None: """ Inserts a word into the Trie :param word: word to be inserted :return: None """ curr = self for char in word: if char not in curr.nodes: curr.nodes[char] = TrieNode() curr = curr.nodes[char] curr.is_leaf = True def find(self, word: str) -> bool: """ Tries to find word in a Trie :param word: word to look for :return: Returns True if word is found, False otherwise """ curr = self for char in word: if char not in curr.nodes: return False curr = curr.nodes[char] return curr.is_leaf def delete(self, word: str) -> None: """ Deletes a word in a Trie :param word: word to delete :return: None """ def _delete(curr: TrieNode, word: str, index: int) -> bool: if index == len(word): # If word does not exist if not curr.is_leaf: return False curr.is_leaf = False return len(curr.nodes) == 0 char = word[index] char_node = curr.nodes.get(char) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted delete_curr = _delete(char_node, word, index + 1) if delete_curr: del curr.nodes[char] return len(curr.nodes) == 0 return delete_curr _delete(self, word, 0) def print_words(node: TrieNode, word: str) -> None: """ Prints all the words in a Trie :param node: root node of Trie :param word: Word variable should be empty at start :return: None """ if node.is_leaf: print(word, end=" ") for key, value in node.nodes.items(): print_words(value, word + key) def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = TrieNode() root.insert_many(words) # print_words(root, "") assert all(root.find(word) for word in words) assert root.find("banana") assert not root.find("bandanas") assert not root.find("apps") assert root.find("apple") assert root.find("all") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_trie() def main() -> None: """ >>> pytests() """ print_results("Testing trie functionality", test_trie()) if __name__ == "__main__": main()
""" A Trie/Prefix Tree is a kind of search tree used to provide quick lookup of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity making it impractical in practice. It however provides O(max(search_string, length of longest word)) lookup time making it an optimal approach when space is not an issue. """ class TrieNode: def __init__(self) -> None: self.nodes: dict[str, TrieNode] = {} # Mapping from char to TrieNode self.is_leaf = False def insert_many(self, words: list[str]) -> None: """ Inserts a list of words into the Trie :param words: list of string words :return: None """ for word in words: self.insert(word) def insert(self, word: str) -> None: """ Inserts a word into the Trie :param word: word to be inserted :return: None """ curr = self for char in word: if char not in curr.nodes: curr.nodes[char] = TrieNode() curr = curr.nodes[char] curr.is_leaf = True def find(self, word: str) -> bool: """ Tries to find word in a Trie :param word: word to look for :return: Returns True if word is found, False otherwise """ curr = self for char in word: if char not in curr.nodes: return False curr = curr.nodes[char] return curr.is_leaf def delete(self, word: str) -> None: """ Deletes a word in a Trie :param word: word to delete :return: None """ def _delete(curr: TrieNode, word: str, index: int) -> bool: if index == len(word): # If word does not exist if not curr.is_leaf: return False curr.is_leaf = False return len(curr.nodes) == 0 char = word[index] char_node = curr.nodes.get(char) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted delete_curr = _delete(char_node, word, index + 1) if delete_curr: del curr.nodes[char] return len(curr.nodes) == 0 return delete_curr _delete(self, word, 0) def print_words(node: TrieNode, word: str) -> None: """ Prints all the words in a Trie :param node: root node of Trie :param word: Word variable should be empty at start :return: None """ if node.is_leaf: print(word, end=" ") for key, value in node.nodes.items(): print_words(value, word + key) def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = TrieNode() root.insert_many(words) # print_words(root, "") assert all(root.find(word) for word in words) assert root.find("banana") assert not root.find("bandanas") assert not root.find("apps") assert root.find("apple") assert root.find("all") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_trie() def main() -> None: """ >>> pytests() """ print_results("Testing trie functionality", test_trie()) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Author : Alexander Pantyukhin Date : November 30, 2022 Task: Given two int numbers. Return True these numbers have opposite signs or False otherwise. Implementation notes: Use bit manipulation. Use XOR for two numbers. """ def different_signs(num1: int, num2: int) -> bool: """ Return True if numbers have opposite signs False otherwise. >>> different_signs(1, -1) True >>> different_signs(1, 1) False >>> different_signs(1000000000000000000000000000, -1000000000000000000000000000) True >>> different_signs(-1000000000000000000000000000, 1000000000000000000000000000) True >>> different_signs(50, 278) False >>> different_signs(0, 2) False >>> different_signs(2, 0) False """ return num1 ^ num2 < 0 if __name__ == "__main__": import doctest doctest.testmod()
""" Author : Alexander Pantyukhin Date : November 30, 2022 Task: Given two int numbers. Return True these numbers have opposite signs or False otherwise. Implementation notes: Use bit manipulation. Use XOR for two numbers. """ def different_signs(num1: int, num2: int) -> bool: """ Return True if numbers have opposite signs False otherwise. >>> different_signs(1, -1) True >>> different_signs(1, 1) False >>> different_signs(1000000000000000000000000000, -1000000000000000000000000000) True >>> different_signs(-1000000000000000000000000000, 1000000000000000000000000000) True >>> different_signs(50, 278) False >>> different_signs(0, 2) False >>> different_signs(2, 0) False """ return num1 ^ num2 < 0 if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 Γ— 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ total_sum = 0 temp_sum = 0 with open(os.path.dirname(__file__) + "/p022_names.txt") as file: name = str(file.readlines()[0]) name = name.replace('"', "").split(",") name.sort() for i in range(len(name)): for j in name[i]: temp_sum += ord(j) - ord("A") + 1 total_sum += (i + 1) * temp_sum temp_sum = 0 return total_sum if __name__ == "__main__": print(solution())
""" Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 Γ— 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ total_sum = 0 temp_sum = 0 with open(os.path.dirname(__file__) + "/p022_names.txt") as file: name = str(file.readlines()[0]) name = name.replace('"', "").split(",") name.sort() for i in range(len(name)): for j in name[i]: temp_sum += ord(j) - ord("A") + 1 total_sum += (i + 1) * temp_sum temp_sum = 0 return total_sum if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
#!/bin/python3 # Doomsday algorithm info: https://en.wikipedia.org/wiki/Doomsday_rule DOOMSDAY_LEAP = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] DOOMSDAY_NOT_LEAP = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] WEEK_DAY_NAMES = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def get_week_day(year: int, month: int, day: int) -> str: """Returns the week-day name out of a given date. >>> get_week_day(2020, 10, 24) 'Saturday' >>> get_week_day(2017, 10, 24) 'Tuesday' >>> get_week_day(2019, 5, 3) 'Friday' >>> get_week_day(1970, 9, 16) 'Wednesday' >>> get_week_day(1870, 8, 13) 'Saturday' >>> get_week_day(2040, 3, 14) 'Wednesday' """ # minimal input check: assert len(str(year)) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: century = year // 100 century_anchor = (5 * (century % 4) + 2) % 7 centurian = year % 100 centurian_m = centurian % 12 dooms_day = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 day_anchor = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) week_day = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
#!/bin/python3 # Doomsday algorithm info: https://en.wikipedia.org/wiki/Doomsday_rule DOOMSDAY_LEAP = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] DOOMSDAY_NOT_LEAP = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] WEEK_DAY_NAMES = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def get_week_day(year: int, month: int, day: int) -> str: """Returns the week-day name out of a given date. >>> get_week_day(2020, 10, 24) 'Saturday' >>> get_week_day(2017, 10, 24) 'Tuesday' >>> get_week_day(2019, 5, 3) 'Friday' >>> get_week_day(1970, 9, 16) 'Wednesday' >>> get_week_day(1870, 8, 13) 'Saturday' >>> get_week_day(2040, 3, 14) 'Wednesday' """ # minimal input check: assert len(str(year)) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: century = year // 100 century_anchor = (5 * (century % 4) + 2) % 7 centurian = year % 100 centurian_m = centurian % 12 dooms_day = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 day_anchor = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) week_day = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Convert International System of Units (SI) and Binary prefixes """ from __future__ import annotations from enum import Enum class SIUnit(Enum): yotta = 24 zetta = 21 exa = 18 peta = 15 tera = 12 giga = 9 mega = 6 kilo = 3 hecto = 2 deca = 1 deci = -1 centi = -2 milli = -3 micro = -6 nano = -9 pico = -12 femto = -15 atto = -18 zepto = -21 yocto = -24 class BinaryUnit(Enum): yotta = 8 zetta = 7 exa = 6 peta = 5 tera = 4 giga = 3 mega = 2 kilo = 1 def convert_si_prefix( known_amount: float, known_prefix: str | SIUnit, unknown_prefix: str | SIUnit, ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Binary_prefix Wikipedia reference: https://en.wikipedia.org/wiki/International_System_of_Units >>> convert_si_prefix(1, SIUnit.giga, SIUnit.mega) 1000 >>> convert_si_prefix(1, SIUnit.mega, SIUnit.giga) 0.001 >>> convert_si_prefix(1, SIUnit.kilo, SIUnit.kilo) 1 >>> convert_si_prefix(1, 'giga', 'mega') 1000 >>> convert_si_prefix(1, 'gIGa', 'mEGa') 1000 """ if isinstance(known_prefix, str): known_prefix = SIUnit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = SIUnit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 10 ** (known_prefix.value - unknown_prefix.value) ) return unknown_amount def convert_binary_prefix( known_amount: float, known_prefix: str | BinaryUnit, unknown_prefix: str | BinaryUnit, ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Metric_prefix >>> convert_binary_prefix(1, BinaryUnit.giga, BinaryUnit.mega) 1024 >>> convert_binary_prefix(1, BinaryUnit.mega, BinaryUnit.giga) 0.0009765625 >>> convert_binary_prefix(1, BinaryUnit.kilo, BinaryUnit.kilo) 1 >>> convert_binary_prefix(1, 'giga', 'mega') 1024 >>> convert_binary_prefix(1, 'gIGa', 'mEGa') 1024 """ if isinstance(known_prefix, str): known_prefix = BinaryUnit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = BinaryUnit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 2 ** ((known_prefix.value - unknown_prefix.value) * 10) ) return unknown_amount if __name__ == "__main__": import doctest doctest.testmod()
""" Convert International System of Units (SI) and Binary prefixes """ from __future__ import annotations from enum import Enum class SIUnit(Enum): yotta = 24 zetta = 21 exa = 18 peta = 15 tera = 12 giga = 9 mega = 6 kilo = 3 hecto = 2 deca = 1 deci = -1 centi = -2 milli = -3 micro = -6 nano = -9 pico = -12 femto = -15 atto = -18 zepto = -21 yocto = -24 class BinaryUnit(Enum): yotta = 8 zetta = 7 exa = 6 peta = 5 tera = 4 giga = 3 mega = 2 kilo = 1 def convert_si_prefix( known_amount: float, known_prefix: str | SIUnit, unknown_prefix: str | SIUnit, ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Binary_prefix Wikipedia reference: https://en.wikipedia.org/wiki/International_System_of_Units >>> convert_si_prefix(1, SIUnit.giga, SIUnit.mega) 1000 >>> convert_si_prefix(1, SIUnit.mega, SIUnit.giga) 0.001 >>> convert_si_prefix(1, SIUnit.kilo, SIUnit.kilo) 1 >>> convert_si_prefix(1, 'giga', 'mega') 1000 >>> convert_si_prefix(1, 'gIGa', 'mEGa') 1000 """ if isinstance(known_prefix, str): known_prefix = SIUnit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = SIUnit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 10 ** (known_prefix.value - unknown_prefix.value) ) return unknown_amount def convert_binary_prefix( known_amount: float, known_prefix: str | BinaryUnit, unknown_prefix: str | BinaryUnit, ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Metric_prefix >>> convert_binary_prefix(1, BinaryUnit.giga, BinaryUnit.mega) 1024 >>> convert_binary_prefix(1, BinaryUnit.mega, BinaryUnit.giga) 0.0009765625 >>> convert_binary_prefix(1, BinaryUnit.kilo, BinaryUnit.kilo) 1 >>> convert_binary_prefix(1, 'giga', 'mega') 1024 >>> convert_binary_prefix(1, 'gIGa', 'mEGa') 1024 """ if isinstance(known_prefix, str): known_prefix = BinaryUnit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = BinaryUnit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 2 ** ((known_prefix.value - unknown_prefix.value) * 10) ) return unknown_amount if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
from __future__ import annotations def find_min_iterative(nums: list[int | float]) -> int | float: """ Find Minimum Number in a List :param nums: contains elements :return: min number in list >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_min_iterative(nums) == min(nums) True True True True >>> find_min_iterative([0, 1, 2, 3, 4, 5, -3, 24, -56]) -56 >>> find_min_iterative([]) Traceback (most recent call last): ... ValueError: find_min_iterative() arg is an empty sequence """ if len(nums) == 0: raise ValueError("find_min_iterative() arg is an empty sequence") min_num = nums[0] for num in nums: min_num = min(min_num, num) return min_num # Divide and Conquer algorithm def find_min_recursive(nums: list[int | float], left: int, right: int) -> int | float: """ find min value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: min in nums >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_min_recursive(nums, 0, len(nums) - 1) == min(nums) True True True True >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] >>> find_min_recursive(nums, 0, len(nums) - 1) == min(nums) True >>> find_min_recursive([], 0, 0) Traceback (most recent call last): ... ValueError: find_min_recursive() arg is an empty sequence >>> find_min_recursive(nums, 0, len(nums)) == min(nums) Traceback (most recent call last): ... IndexError: list index out of range >>> find_min_recursive(nums, -len(nums), -1) == min(nums) True >>> find_min_recursive(nums, -len(nums) - 1, -1) == min(nums) Traceback (most recent call last): ... IndexError: list index out of range """ if len(nums) == 0: raise ValueError("find_min_recursive() arg is an empty sequence") if ( left >= len(nums) or left < -len(nums) or right >= len(nums) or right < -len(nums) ): raise IndexError("list index out of range") if left == right: return nums[left] mid = (left + right) >> 1 # the middle left_min = find_min_recursive(nums, left, mid) # find min in range[left, mid] right_min = find_min_recursive( nums, mid + 1, right ) # find min in range[mid + 1, right] return left_min if left_min <= right_min else right_min if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
from __future__ import annotations def find_min_iterative(nums: list[int | float]) -> int | float: """ Find Minimum Number in a List :param nums: contains elements :return: min number in list >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_min_iterative(nums) == min(nums) True True True True >>> find_min_iterative([0, 1, 2, 3, 4, 5, -3, 24, -56]) -56 >>> find_min_iterative([]) Traceback (most recent call last): ... ValueError: find_min_iterative() arg is an empty sequence """ if len(nums) == 0: raise ValueError("find_min_iterative() arg is an empty sequence") min_num = nums[0] for num in nums: min_num = min(min_num, num) return min_num # Divide and Conquer algorithm def find_min_recursive(nums: list[int | float], left: int, right: int) -> int | float: """ find min value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: min in nums >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_min_recursive(nums, 0, len(nums) - 1) == min(nums) True True True True >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] >>> find_min_recursive(nums, 0, len(nums) - 1) == min(nums) True >>> find_min_recursive([], 0, 0) Traceback (most recent call last): ... ValueError: find_min_recursive() arg is an empty sequence >>> find_min_recursive(nums, 0, len(nums)) == min(nums) Traceback (most recent call last): ... IndexError: list index out of range >>> find_min_recursive(nums, -len(nums), -1) == min(nums) True >>> find_min_recursive(nums, -len(nums) - 1, -1) == min(nums) Traceback (most recent call last): ... IndexError: list index out of range """ if len(nums) == 0: raise ValueError("find_min_recursive() arg is an empty sequence") if ( left >= len(nums) or left < -len(nums) or right >= len(nums) or right < -len(nums) ): raise IndexError("list index out of range") if left == right: return nums[left] mid = (left + right) >> 1 # the middle left_min = find_min_recursive(nums, left, mid) # find min in range[left, mid] right_min = find_min_recursive( nums, mid + 1, right ) # find min in range[mid + 1, right] return left_min if left_min <= right_min else right_min if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" This module contains the functions to calculate the focal length, object distance and image distance of a mirror. The mirror formula is an equation that relates the object distance (u), image distance (v), and focal length (f) of a spherical mirror. It is commonly used in optics to determine the position and characteristics of an image formed by a mirror. It is expressed using the formulae : ------------------- | 1/f = 1/v + 1/u | ------------------- Where, f = Focal length of the spherical mirror (metre) v = Image distance from the mirror (metre) u = Object distance from the mirror (metre) The signs of the distances are taken with respect to the sign convention. The sign convention is as follows: 1) Object is always placed to the left of mirror 2) Distances measured in the direction of the incident ray are positive and the distances measured in the direction opposite to that of the incident rays are negative. 3) All distances are measured from the pole of the mirror. There are a few assumptions that are made while using the mirror formulae. They are as follows: 1) Thin Mirror: The mirror is assumed to be thin, meaning its thickness is negligible compared to its radius of curvature. This assumption allows us to treat the mirror as a two-dimensional surface. 2) Spherical Mirror: The mirror is assumed to have a spherical shape. While this assumption may not hold exactly for all mirrors, it is a reasonable approximation for most practical purposes. 3) Small Angles: The angles involved in the derivation are assumed to be small. This assumption allows us to use the small-angle approximation, where the tangent of a small angle is approximately equal to the angle itself. It simplifies the calculations and makes the derivation more manageable. 4) Paraxial Rays: The mirror formula is derived using paraxial rays, which are rays that are close to the principal axis and make small angles with it. This assumption ensures that the rays are close enough to the principal axis, making the calculations more accurate. 5) Reflection and Refraction Laws: The derivation assumes that the laws of reflection and refraction hold. These laws state that the angle of incidence is equal to the angle of reflection for reflection, and the incident and refracted rays lie in the same plane and obey Snell's law for refraction. (Description and Assumptions adapted from https://www.collegesearch.in/articles/mirror-formula-derivation) (Sign Convention adapted from https://www.toppr.com/ask/content/concept/sign-convention-for-mirrors-210189/) """ def focal_length(distance_of_object: float, distance_of_image: float) -> float: """ >>> from math import isclose >>> isclose(focal_length(10, 20), 6.66666666666666) True >>> from math import isclose >>> isclose(focal_length(9.5, 6.7), 3.929012346) True >>> focal_length(0, 20) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Invalid inputs. Enter non zero values with respect to the sign convention. """ if distance_of_object == 0 or distance_of_image == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) focal_length = 1 / ((1 / distance_of_object) + (1 / distance_of_image)) return focal_length def object_distance(focal_length: float, distance_of_image: float) -> float: """ >>> from math import isclose >>> isclose(object_distance(30, 20), -60.0) True >>> from math import isclose >>> isclose(object_distance(10.5, 11.7), 102.375) True >>> object_distance(90, 0) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Invalid inputs. Enter non zero values with respect to the sign convention. """ if distance_of_image == 0 or focal_length == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) object_distance = 1 / ((1 / focal_length) - (1 / distance_of_image)) return object_distance def image_distance(focal_length: float, distance_of_object: float) -> float: """ >>> from math import isclose >>> isclose(image_distance(10, 40), 13.33333333) True >>> from math import isclose >>> isclose(image_distance(1.5, 6.7), 1.932692308) True >>> image_distance(0, 0) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Invalid inputs. Enter non zero values with respect to the sign convention. """ if distance_of_object == 0 or focal_length == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) image_distance = 1 / ((1 / focal_length) - (1 / distance_of_object)) return image_distance
""" This module contains the functions to calculate the focal length, object distance and image distance of a mirror. The mirror formula is an equation that relates the object distance (u), image distance (v), and focal length (f) of a spherical mirror. It is commonly used in optics to determine the position and characteristics of an image formed by a mirror. It is expressed using the formulae : ------------------- | 1/f = 1/v + 1/u | ------------------- Where, f = Focal length of the spherical mirror (metre) v = Image distance from the mirror (metre) u = Object distance from the mirror (metre) The signs of the distances are taken with respect to the sign convention. The sign convention is as follows: 1) Object is always placed to the left of mirror 2) Distances measured in the direction of the incident ray are positive and the distances measured in the direction opposite to that of the incident rays are negative. 3) All distances are measured from the pole of the mirror. There are a few assumptions that are made while using the mirror formulae. They are as follows: 1) Thin Mirror: The mirror is assumed to be thin, meaning its thickness is negligible compared to its radius of curvature. This assumption allows us to treat the mirror as a two-dimensional surface. 2) Spherical Mirror: The mirror is assumed to have a spherical shape. While this assumption may not hold exactly for all mirrors, it is a reasonable approximation for most practical purposes. 3) Small Angles: The angles involved in the derivation are assumed to be small. This assumption allows us to use the small-angle approximation, where the tangent of a small angle is approximately equal to the angle itself. It simplifies the calculations and makes the derivation more manageable. 4) Paraxial Rays: The mirror formula is derived using paraxial rays, which are rays that are close to the principal axis and make small angles with it. This assumption ensures that the rays are close enough to the principal axis, making the calculations more accurate. 5) Reflection and Refraction Laws: The derivation assumes that the laws of reflection and refraction hold. These laws state that the angle of incidence is equal to the angle of reflection for reflection, and the incident and refracted rays lie in the same plane and obey Snell's law for refraction. (Description and Assumptions adapted from https://www.collegesearch.in/articles/mirror-formula-derivation) (Sign Convention adapted from https://www.toppr.com/ask/content/concept/sign-convention-for-mirrors-210189/) """ def focal_length(distance_of_object: float, distance_of_image: float) -> float: """ >>> from math import isclose >>> isclose(focal_length(10, 20), 6.66666666666666) True >>> from math import isclose >>> isclose(focal_length(9.5, 6.7), 3.929012346) True >>> focal_length(0, 20) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Invalid inputs. Enter non zero values with respect to the sign convention. """ if distance_of_object == 0 or distance_of_image == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) focal_length = 1 / ((1 / distance_of_object) + (1 / distance_of_image)) return focal_length def object_distance(focal_length: float, distance_of_image: float) -> float: """ >>> from math import isclose >>> isclose(object_distance(30, 20), -60.0) True >>> from math import isclose >>> isclose(object_distance(10.5, 11.7), 102.375) True >>> object_distance(90, 0) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Invalid inputs. Enter non zero values with respect to the sign convention. """ if distance_of_image == 0 or focal_length == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) object_distance = 1 / ((1 / focal_length) - (1 / distance_of_image)) return object_distance def image_distance(focal_length: float, distance_of_object: float) -> float: """ >>> from math import isclose >>> isclose(image_distance(10, 40), 13.33333333) True >>> from math import isclose >>> isclose(image_distance(1.5, 6.7), 1.932692308) True >>> image_distance(0, 0) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Invalid inputs. Enter non zero values with respect to the sign convention. """ if distance_of_object == 0 or focal_length == 0: raise ValueError( "Invalid inputs. Enter non zero values with respect to the sign convention." ) image_distance = 1 / ((1 / focal_length) - (1 / distance_of_object)) return image_distance
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
# XGBoost Classifier Example import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def data_handling(data: dict) -> tuple: # Split dataset into features and target # data is features """ >>> data_handling(({'data':'[5.1, 3.5, 1.4, 0.2]','target':([0])})) ('[5.1, 3.5, 1.4, 0.2]', [0]) >>> data_handling( ... {'data': '[4.9, 3.0, 1.4, 0.2], [4.7, 3.2, 1.3, 0.2]', 'target': ([0, 0])} ... ) ('[4.9, 3.0, 1.4, 0.2], [4.7, 3.2, 1.3, 0.2]', [0, 0]) """ return (data["data"], data["target"]) def xgboost(features: np.ndarray, target: np.ndarray) -> XGBClassifier: """ # THIS TEST IS BROKEN!! >>> xgboost(np.array([[5.1, 3.6, 1.4, 0.2]]), np.array([0])) XGBClassifier(base_score=0.5, booster='gbtree', callbacks=None, colsample_bylevel=1, colsample_bynode=1, colsample_bytree=1, early_stopping_rounds=None, enable_categorical=False, eval_metric=None, gamma=0, gpu_id=-1, grow_policy='depthwise', importance_type=None, interaction_constraints='', learning_rate=0.300000012, max_bin=256, max_cat_to_onehot=4, max_delta_step=0, max_depth=6, max_leaves=0, min_child_weight=1, missing=nan, monotone_constraints='()', n_estimators=100, n_jobs=0, num_parallel_tree=1, predictor='auto', random_state=0, reg_alpha=0, reg_lambda=1, ...) """ classifier = XGBClassifier() classifier.fit(features, target) return classifier def main() -> None: """ >>> main() Url for the algorithm: https://xgboost.readthedocs.io/en/stable/ Iris type dataset is used to demonstrate algorithm. """ # Load Iris dataset iris = load_iris() features, targets = data_handling(iris) x_train, x_test, y_train, y_test = train_test_split( features, targets, test_size=0.25 ) names = iris["target_names"] # Create an XGBoost Classifier from the training data xgboost_classifier = xgboost(x_train, y_train) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( xgboost_classifier, x_test, y_test, display_labels=names, cmap="Blues", normalize="true", ) plt.title("Normalized Confusion Matrix - IRIS Dataset") plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
# XGBoost Classifier Example import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def data_handling(data: dict) -> tuple: # Split dataset into features and target # data is features """ >>> data_handling(({'data':'[5.1, 3.5, 1.4, 0.2]','target':([0])})) ('[5.1, 3.5, 1.4, 0.2]', [0]) >>> data_handling( ... {'data': '[4.9, 3.0, 1.4, 0.2], [4.7, 3.2, 1.3, 0.2]', 'target': ([0, 0])} ... ) ('[4.9, 3.0, 1.4, 0.2], [4.7, 3.2, 1.3, 0.2]', [0, 0]) """ return (data["data"], data["target"]) def xgboost(features: np.ndarray, target: np.ndarray) -> XGBClassifier: """ # THIS TEST IS BROKEN!! >>> xgboost(np.array([[5.1, 3.6, 1.4, 0.2]]), np.array([0])) XGBClassifier(base_score=0.5, booster='gbtree', callbacks=None, colsample_bylevel=1, colsample_bynode=1, colsample_bytree=1, early_stopping_rounds=None, enable_categorical=False, eval_metric=None, gamma=0, gpu_id=-1, grow_policy='depthwise', importance_type=None, interaction_constraints='', learning_rate=0.300000012, max_bin=256, max_cat_to_onehot=4, max_delta_step=0, max_depth=6, max_leaves=0, min_child_weight=1, missing=nan, monotone_constraints='()', n_estimators=100, n_jobs=0, num_parallel_tree=1, predictor='auto', random_state=0, reg_alpha=0, reg_lambda=1, ...) """ classifier = XGBClassifier() classifier.fit(features, target) return classifier def main() -> None: """ >>> main() Url for the algorithm: https://xgboost.readthedocs.io/en/stable/ Iris type dataset is used to demonstrate algorithm. """ # Load Iris dataset iris = load_iris() features, targets = data_handling(iris) x_train, x_test, y_train, y_test = train_test_split( features, targets, test_size=0.25 ) names = iris["target_names"] # Create an XGBoost Classifier from the training data xgboost_classifier = xgboost(x_train, y_train) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( xgboost_classifier, x_test, y_test, display_labels=names, cmap="Blues", normalize="true", ) plt.title("Normalized Confusion Matrix - IRIS Dataset") plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
#
#
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
"""A merge sort which accepts an array as input and recursively splits an array in half and sorts and combines them. """ """https://en.wikipedia.org/wiki/Merge_sort """ def merge(arr: list[int]) -> list[int]: """Return a sorted array. >>> merge([10,9,8,7,6,5,4,3,2,1]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([1,2,3,4,5,6,7,8,9,10]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([10,22,1,2,3,9,15,23]) [1, 2, 3, 9, 10, 15, 22, 23] >>> merge([100]) [100] >>> merge([]) [] """ if len(arr) > 1: middle_length = len(arr) // 2 # Finds the middle of the array left_array = arr[ :middle_length ] # Creates an array of the elements in the first half. right_array = arr[ middle_length: ] # Creates an array of the elements in the second half. left_size = len(left_array) right_size = len(right_array) merge(left_array) # Starts sorting the left. merge(right_array) # Starts sorting the right left_index = 0 # Left Counter right_index = 0 # Right Counter index = 0 # Position Counter while ( left_index < left_size and right_index < right_size ): # Runs until the lowers size of the left and right are sorted. if left_array[left_index] < right_array[right_index]: arr[index] = left_array[left_index] left_index += 1 else: arr[index] = right_array[right_index] right_index += 1 index += 1 while ( left_index < left_size ): # Adds the left over elements in the left half of the array arr[index] = left_array[left_index] left_index += 1 index += 1 while ( right_index < right_size ): # Adds the left over elements in the right half of the array arr[index] = right_array[right_index] right_index += 1 index += 1 return arr if __name__ == "__main__": import doctest doctest.testmod()
"""A merge sort which accepts an array as input and recursively splits an array in half and sorts and combines them. """ """https://en.wikipedia.org/wiki/Merge_sort """ def merge(arr: list[int]) -> list[int]: """Return a sorted array. >>> merge([10,9,8,7,6,5,4,3,2,1]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([1,2,3,4,5,6,7,8,9,10]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([10,22,1,2,3,9,15,23]) [1, 2, 3, 9, 10, 15, 22, 23] >>> merge([100]) [100] >>> merge([]) [] """ if len(arr) > 1: middle_length = len(arr) // 2 # Finds the middle of the array left_array = arr[ :middle_length ] # Creates an array of the elements in the first half. right_array = arr[ middle_length: ] # Creates an array of the elements in the second half. left_size = len(left_array) right_size = len(right_array) merge(left_array) # Starts sorting the left. merge(right_array) # Starts sorting the right left_index = 0 # Left Counter right_index = 0 # Right Counter index = 0 # Position Counter while ( left_index < left_size and right_index < right_size ): # Runs until the lowers size of the left and right are sorted. if left_array[left_index] < right_array[right_index]: arr[index] = left_array[left_index] left_index += 1 else: arr[index] = right_array[right_index] right_index += 1 index += 1 while ( left_index < left_size ): # Adds the left over elements in the left half of the array arr[index] = left_array[left_index] left_index += 1 index += 1 while ( right_index < right_size ): # Adds the left over elements in the right half of the array arr[index] = right_array[right_index] right_index += 1 index += 1 return arr if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
name: Feature request description: Suggest features, propose improvements, discuss new ideas. labels: [enhancement] body: - type: markdown attributes: value: > Before requesting please search [existing issues](https://github.com/TheAlgorithms/Python/labels/enhancement). Usage questions such as "How do I...?" belong on the [Discord](https://discord.gg/c7MnfGFGa6) and will be closed. - type: textarea attributes: label: "Feature description" description: > This could be new algorithms, data structures or improving any existing implementations. validations: required: true
name: Feature request description: Suggest features, propose improvements, discuss new ideas. labels: [enhancement] body: - type: markdown attributes: value: > Before requesting please search [existing issues](https://github.com/TheAlgorithms/Python/labels/enhancement). Usage questions such as "How do I...?" belong on the [Discord](https://discord.gg/c7MnfGFGa6) and will be closed. - type: textarea attributes: label: "Feature description" description: > This could be new algorithms, data structures or improving any existing implementations. validations: required: true
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
# https://github.com/rupansh/QuantumComputing/blob/master/rippleadd.py # https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder # https://en.wikipedia.org/wiki/Controlled_NOT_gate import qiskit from qiskit.providers import Backend def store_two_classics(val1: int, val2: int) -> tuple[qiskit.QuantumCircuit, str, str]: """ Generates a Quantum Circuit which stores two classical integers Returns the circuit and binary representation of the integers """ x, y = bin(val1)[2:], bin(val2)[2:] # Remove leading '0b' # Ensure that both strings are of the same length if len(x) > len(y): y = y.zfill(len(x)) else: x = x.zfill(len(y)) # We need (3 * number of bits in the larger number)+1 qBits # The second parameter is the number of classical registers, to measure the result circuit = qiskit.QuantumCircuit((len(x) * 3) + 1, len(x) + 1) # We are essentially "not-ing" the bits that are 1 # Reversed because it's easier to perform ops on more significant bits for i in range(len(x)): if x[::-1][i] == "1": circuit.x(i) for j in range(len(y)): if y[::-1][j] == "1": circuit.x(len(x) + j) return circuit, x, y def full_adder( circuit: qiskit.QuantumCircuit, input1_loc: int, input2_loc: int, carry_in: int, carry_out: int, ): """ Quantum Equivalent of a Full Adder Circuit CX/CCX is like 2-way/3-way XOR """ circuit.ccx(input1_loc, input2_loc, carry_out) circuit.cx(input1_loc, input2_loc) circuit.ccx(input2_loc, carry_in, carry_out) circuit.cx(input2_loc, carry_in) circuit.cx(input1_loc, input2_loc) # The default value for **backend** is the result of a function call which is not # normally recommended and causes ruff to raise a B008 error. However, in this case, # this is acceptable because `Aer.get_backend()` is called when the function is defined # and that same backend is then reused for all function calls. def ripple_adder( val1: int, val2: int, backend: Backend = qiskit.Aer.get_backend("aer_simulator"), # noqa: B008 ) -> int: """ Quantum Equivalent of a Ripple Adder Circuit Uses qasm_simulator backend by default Currently only adds 'emulated' Classical Bits but nothing prevents us from doing this with hadamard'd bits :) Only supports adding positive integers >>> ripple_adder(3, 4) 7 >>> ripple_adder(10, 4) 14 >>> ripple_adder(-1, 10) Traceback (most recent call last): ... ValueError: Both Integers must be positive! """ if val1 < 0 or val2 < 0: raise ValueError("Both Integers must be positive!") # Store the Integers circuit, x, y = store_two_classics(val1, val2) """ We are essentially using each bit of x & y respectively as full_adder's input the carry_input is used from the previous circuit (for circuit num > 1) the carry_out is just below carry_input because it will be essentially the carry_input for the next full_adder """ for i in range(len(x)): full_adder(circuit, i, len(x) + i, len(x) + len(y) + i, len(x) + len(y) + i + 1) circuit.barrier() # Optional, just for aesthetics # Measure the resultant qBits for i in range(len(x) + 1): circuit.measure([(len(x) * 2) + i], [i]) res = qiskit.execute(circuit, backend, shots=1).result() # The result is in binary. Convert it back to int return int(next(iter(res.get_counts())), 2) if __name__ == "__main__": import doctest doctest.testmod()
# https://github.com/rupansh/QuantumComputing/blob/master/rippleadd.py # https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder # https://en.wikipedia.org/wiki/Controlled_NOT_gate import qiskit from qiskit.providers import Backend def store_two_classics(val1: int, val2: int) -> tuple[qiskit.QuantumCircuit, str, str]: """ Generates a Quantum Circuit which stores two classical integers Returns the circuit and binary representation of the integers """ x, y = bin(val1)[2:], bin(val2)[2:] # Remove leading '0b' # Ensure that both strings are of the same length if len(x) > len(y): y = y.zfill(len(x)) else: x = x.zfill(len(y)) # We need (3 * number of bits in the larger number)+1 qBits # The second parameter is the number of classical registers, to measure the result circuit = qiskit.QuantumCircuit((len(x) * 3) + 1, len(x) + 1) # We are essentially "not-ing" the bits that are 1 # Reversed because it's easier to perform ops on more significant bits for i in range(len(x)): if x[::-1][i] == "1": circuit.x(i) for j in range(len(y)): if y[::-1][j] == "1": circuit.x(len(x) + j) return circuit, x, y def full_adder( circuit: qiskit.QuantumCircuit, input1_loc: int, input2_loc: int, carry_in: int, carry_out: int, ): """ Quantum Equivalent of a Full Adder Circuit CX/CCX is like 2-way/3-way XOR """ circuit.ccx(input1_loc, input2_loc, carry_out) circuit.cx(input1_loc, input2_loc) circuit.ccx(input2_loc, carry_in, carry_out) circuit.cx(input2_loc, carry_in) circuit.cx(input1_loc, input2_loc) # The default value for **backend** is the result of a function call which is not # normally recommended and causes ruff to raise a B008 error. However, in this case, # this is acceptable because `Aer.get_backend()` is called when the function is defined # and that same backend is then reused for all function calls. def ripple_adder( val1: int, val2: int, backend: Backend = qiskit.Aer.get_backend("aer_simulator"), # noqa: B008 ) -> int: """ Quantum Equivalent of a Ripple Adder Circuit Uses qasm_simulator backend by default Currently only adds 'emulated' Classical Bits but nothing prevents us from doing this with hadamard'd bits :) Only supports adding positive integers >>> ripple_adder(3, 4) 7 >>> ripple_adder(10, 4) 14 >>> ripple_adder(-1, 10) Traceback (most recent call last): ... ValueError: Both Integers must be positive! """ if val1 < 0 or val2 < 0: raise ValueError("Both Integers must be positive!") # Store the Integers circuit, x, y = store_two_classics(val1, val2) """ We are essentially using each bit of x & y respectively as full_adder's input the carry_input is used from the previous circuit (for circuit num > 1) the carry_out is just below carry_input because it will be essentially the carry_input for the next full_adder """ for i in range(len(x)): full_adder(circuit, i, len(x) + i, len(x) + len(y) + i, len(x) + len(y) + i + 1) circuit.barrier() # Optional, just for aesthetics # Measure the resultant qBits for i in range(len(x) + 1): circuit.measure([(len(x) * 2) + i], [i]) res = qiskit.execute(circuit, backend, shots=1).result() # The result is in binary. Convert it back to int return int(next(iter(res.get_counts())), 2) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
"""Factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial """ def factorial(number: int) -> int: """ Calculate the factorial of specified number (n!). >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only accepts integral values >>> factorial(-1) Traceback (most recent call last): ... ValueError: factorial() not defined for negative values >>> factorial(1) 1 >>> factorial(6) 720 >>> factorial(0) 1 """ if number != int(number): raise ValueError("factorial() only accepts integral values") if number < 0: raise ValueError("factorial() not defined for negative values") value = 1 for i in range(1, number + 1): value *= i return value def factorial_recursive(n: int) -> int: """ Calculate the factorial of a positive integer https://en.wikipedia.org/wiki/Factorial >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only accepts integral values >>> factorial(-1) Traceback (most recent call last): ... ValueError: factorial() not defined for negative values """ if not isinstance(n, int): raise ValueError("factorial() only accepts integral values") if n < 0: raise ValueError("factorial() not defined for negative values") return 1 if n in {0, 1} else n * factorial(n - 1) if __name__ == "__main__": import doctest doctest.testmod() n = int(input("Enter a positive integer: ").strip() or 0) print(f"factorial{n} is {factorial(n)}")
"""Factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial """ def factorial(number: int) -> int: """ Calculate the factorial of specified number (n!). >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only accepts integral values >>> factorial(-1) Traceback (most recent call last): ... ValueError: factorial() not defined for negative values >>> factorial(1) 1 >>> factorial(6) 720 >>> factorial(0) 1 """ if number != int(number): raise ValueError("factorial() only accepts integral values") if number < 0: raise ValueError("factorial() not defined for negative values") value = 1 for i in range(1, number + 1): value *= i return value def factorial_recursive(n: int) -> int: """ Calculate the factorial of a positive integer https://en.wikipedia.org/wiki/Factorial >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only accepts integral values >>> factorial(-1) Traceback (most recent call last): ... ValueError: factorial() not defined for negative values """ if not isinstance(n, int): raise ValueError("factorial() only accepts integral values") if n < 0: raise ValueError("factorial() not defined for negative values") return 1 if n in {0, 1} else n * factorial(n - 1) if __name__ == "__main__": import doctest doctest.testmod() n = int(input("Enter a positive integer: ").strip() or 0) print(f"factorial{n} is {factorial(n)}")
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Project Euler Problem 116: https://projecteuler.net/problem=116 A row of five grey square tiles is to have a number of its tiles replaced with coloured oblong tiles chosen from red (length two), green (length three), or blue (length four). If red tiles are chosen there are exactly seven ways this can be done. |red,red|grey|grey|grey| |grey|red,red|grey|grey| |grey|grey|red,red|grey| |grey|grey|grey|red,red| |red,red|red,red|grey| |red,red|grey|red,red| |grey|red,red|red,red| If green tiles are chosen there are three ways. |green,green,green|grey|grey| |grey|green,green,green|grey| |grey|grey|green,green,green| And if blue tiles are chosen there are two ways. |blue,blue,blue,blue|grey| |grey|blue,blue,blue,blue| Assuming that colours cannot be mixed there are 7 + 3 + 2 = 12 ways of replacing the grey tiles in a row measuring five units in length. How many different ways can the grey tiles in a row measuring fifty units in length be replaced if colours cannot be mixed and at least one coloured tile must be used? NOTE: This is related to Problem 117 (https://projecteuler.net/problem=117). """ def solution(length: int = 50) -> int: """ Returns the number of different ways can the grey tiles in a row of the given length be replaced if colours cannot be mixed and at least one coloured tile must be used >>> solution(5) 12 """ different_colour_ways_number = [[0] * 3 for _ in range(length + 1)] for row_length in range(length + 1): for tile_length in range(2, 5): for tile_start in range(row_length - tile_length + 1): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length]) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 116: https://projecteuler.net/problem=116 A row of five grey square tiles is to have a number of its tiles replaced with coloured oblong tiles chosen from red (length two), green (length three), or blue (length four). If red tiles are chosen there are exactly seven ways this can be done. |red,red|grey|grey|grey| |grey|red,red|grey|grey| |grey|grey|red,red|grey| |grey|grey|grey|red,red| |red,red|red,red|grey| |red,red|grey|red,red| |grey|red,red|red,red| If green tiles are chosen there are three ways. |green,green,green|grey|grey| |grey|green,green,green|grey| |grey|grey|green,green,green| And if blue tiles are chosen there are two ways. |blue,blue,blue,blue|grey| |grey|blue,blue,blue,blue| Assuming that colours cannot be mixed there are 7 + 3 + 2 = 12 ways of replacing the grey tiles in a row measuring five units in length. How many different ways can the grey tiles in a row measuring fifty units in length be replaced if colours cannot be mixed and at least one coloured tile must be used? NOTE: This is related to Problem 117 (https://projecteuler.net/problem=117). """ def solution(length: int = 50) -> int: """ Returns the number of different ways can the grey tiles in a row of the given length be replaced if colours cannot be mixed and at least one coloured tile must be used >>> solution(5) 12 """ different_colour_ways_number = [[0] * 3 for _ in range(length + 1)] for row_length in range(length + 1): for tile_length in range(2, 5): for tile_start in range(row_length - tile_length + 1): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length]) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
from __future__ import annotations from collections.abc import Iterator from typing import Any class Node: def __init__(self, data: Any): """ Initialize a new Node with the given data. Args: data: The data to be stored in the node. """ self.data: Any = data self.next: Node | None = None # Reference to the next node class CircularLinkedList: def __init__(self) -> None: """ Initialize an empty Circular Linked List. """ self.head: Node | None = None # Reference to the head (first node) self.tail: Node | None = None # Reference to the tail (last node) def __iter__(self) -> Iterator[Any]: """ Iterate through all nodes in the Circular Linked List yielding their data. Yields: The data of each node in the linked list. """ node = self.head while node: yield node.data node = node.next if node == self.head: break def __len__(self) -> int: """ Get the length (number of nodes) in the Circular Linked List. """ return sum(1 for _ in self) def __repr__(self) -> str: """ Generate a string representation of the Circular Linked List. Returns: A string of the format "1->2->....->N". """ return "->".join(str(item) for item in iter(self)) def insert_tail(self, data: Any) -> None: """ Insert a node with the given data at the end of the Circular Linked List. """ self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: """ Insert a node with the given data at the beginning of the Circular Linked List. """ self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: """ Insert the data of the node at the nth pos in the Circular Linked List. Args: index: The index at which the data should be inserted. data: The data to be inserted. Raises: IndexError: If the index is out of range. """ if index < 0 or index > len(self): raise IndexError("list index out of range.") new_node: Node = Node(data) if self.head is None: new_node.next = new_node # First node points to itself self.tail = self.head = new_node elif index == 0: # Insert at the head new_node.next = self.head assert self.tail is not None # List is not empty, tail exists self.head = self.tail.next = new_node else: temp: Node | None = self.head for _ in range(index - 1): assert temp is not None temp = temp.next assert temp is not None new_node.next = temp.next temp.next = new_node if index == len(self) - 1: # Insert at the tail self.tail = new_node def delete_front(self) -> Any: """ Delete and return the data of the node at the front of the Circular Linked List. Raises: IndexError: If the list is empty. """ return self.delete_nth(0) def delete_tail(self) -> Any: """ Delete and return the data of the node at the end of the Circular Linked List. Returns: Any: The data of the deleted node. Raises: IndexError: If the index is out of range. """ return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: """ Delete and return the data of the node at the nth pos in Circular Linked List. Args: index (int): The index of the node to be deleted. Defaults to 0. Returns: Any: The data of the deleted node. Raises: IndexError: If the index is out of range. """ if not 0 <= index < len(self): raise IndexError("list index out of range.") assert self.head is not None and self.tail is not None delete_node: Node = self.head if self.head == self.tail: # Just one node self.head = self.tail = None elif index == 0: # Delete head node assert self.tail.next is not None self.tail.next = self.tail.next.next self.head = self.head.next else: temp: Node | None = self.head for _ in range(index - 1): assert temp is not None temp = temp.next assert temp is not None and temp.next is not None 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: """ Check if the Circular Linked List is empty. Returns: bool: True if the list is empty, False otherwise. """ return len(self) == 0 def test_circular_linked_list() -> None: """ Test cases for the CircularLinkedList class. >>> 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(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): """ Initialize a new Node with the given data. Args: data: The data to be stored in the node. """ self.data: Any = data self.next: Node | None = None # Reference to the next node class CircularLinkedList: def __init__(self) -> None: """ Initialize an empty Circular Linked List. """ self.head: Node | None = None # Reference to the head (first node) self.tail: Node | None = None # Reference to the tail (last node) def __iter__(self) -> Iterator[Any]: """ Iterate through all nodes in the Circular Linked List yielding their data. Yields: The data of each node in the linked list. """ node = self.head while node: yield node.data node = node.next if node == self.head: break def __len__(self) -> int: """ Get the length (number of nodes) in the Circular Linked List. """ return sum(1 for _ in self) def __repr__(self) -> str: """ Generate a string representation of the Circular Linked List. Returns: A string of the format "1->2->....->N". """ return "->".join(str(item) for item in iter(self)) def insert_tail(self, data: Any) -> None: """ Insert a node with the given data at the end of the Circular Linked List. """ self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: """ Insert a node with the given data at the beginning of the Circular Linked List. """ self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: """ Insert the data of the node at the nth pos in the Circular Linked List. Args: index: The index at which the data should be inserted. data: The data to be inserted. Raises: IndexError: If the index is out of range. """ if index < 0 or index > len(self): raise IndexError("list index out of range.") new_node: Node = Node(data) if self.head is None: new_node.next = new_node # First node points to itself self.tail = self.head = new_node elif index == 0: # Insert at the head new_node.next = self.head assert self.tail is not None # List is not empty, tail exists self.head = self.tail.next = new_node else: temp: Node | None = self.head for _ in range(index - 1): assert temp is not None temp = temp.next assert temp is not None new_node.next = temp.next temp.next = new_node if index == len(self) - 1: # Insert at the tail self.tail = new_node def delete_front(self) -> Any: """ Delete and return the data of the node at the front of the Circular Linked List. Raises: IndexError: If the list is empty. """ return self.delete_nth(0) def delete_tail(self) -> Any: """ Delete and return the data of the node at the end of the Circular Linked List. Returns: Any: The data of the deleted node. Raises: IndexError: If the index is out of range. """ return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: """ Delete and return the data of the node at the nth pos in Circular Linked List. Args: index (int): The index of the node to be deleted. Defaults to 0. Returns: Any: The data of the deleted node. Raises: IndexError: If the index is out of range. """ if not 0 <= index < len(self): raise IndexError("list index out of range.") assert self.head is not None and self.tail is not None delete_node: Node = self.head if self.head == self.tail: # Just one node self.head = self.tail = None elif index == 0: # Delete head node assert self.tail.next is not None self.tail.next = self.tail.next.next self.head = self.head.next else: temp: Node | None = self.head for _ in range(index - 1): assert temp is not None temp = temp.next assert temp is not None and temp.next is not None 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: """ Check if the Circular Linked List is empty. Returns: bool: True if the list is empty, False otherwise. """ return len(self) == 0 def test_circular_linked_list() -> None: """ Test cases for the CircularLinkedList class. >>> 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(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
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" A Stack using a linked list like structure """ from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar T = TypeVar("T") class Node(Generic[T]): def __init__(self, data: T): self.data = data self.next: Node[T] | None = None def __str__(self) -> str: return f"{self.data}" class LinkedStack(Generic[T]): """ Linked List Stack implementing push (to top), pop (from top) and is_empty >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(5) >>> stack.push(9) >>> stack.push('python') >>> stack.is_empty() False >>> stack.pop() 'python' >>> stack.push('algorithms') >>> stack.pop() 'algorithms' >>> stack.pop() 9 >>> stack.pop() 5 >>> stack.is_empty() True >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack """ def __init__(self) -> None: self.top: Node[T] | None = None def __iter__(self) -> Iterator[T]: node = self.top while node: yield node.data node = node.next def __str__(self) -> str: """ >>> stack = LinkedStack() >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> str(stack) 'a->b->c' """ return "->".join([str(item) for item in self]) def __len__(self) -> int: """ >>> stack = LinkedStack() >>> len(stack) == 0 True >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> len(stack) == 3 True """ return len(tuple(iter(self))) def is_empty(self) -> bool: """ >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(1) >>> stack.is_empty() False """ return self.top is None def push(self, item: T) -> None: """ >>> stack = LinkedStack() >>> stack.push("Python") >>> stack.push("Java") >>> stack.push("C") >>> str(stack) 'C->Java->Python' """ node = Node(item) if not self.is_empty(): node.next = self.top self.top = node def pop(self) -> T: """ >>> stack = LinkedStack() >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> stack.pop() == 'a' True >>> stack.pop() == 'b' True >>> stack.pop() == 'c' True """ if self.is_empty(): raise IndexError("pop from empty stack") assert isinstance(self.top, Node) pop_node = self.top self.top = self.top.next return pop_node.data def peek(self) -> T: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> stack.peek() 'Python' """ if self.is_empty(): raise IndexError("peek from empty stack") assert self.top is not None return self.top.data def clear(self) -> None: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> str(stack) 'Python->C->Java' >>> stack.clear() >>> len(stack) == 0 True """ self.top = None if __name__ == "__main__": from doctest import testmod testmod()
""" A Stack using a linked list like structure """ from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar T = TypeVar("T") class Node(Generic[T]): def __init__(self, data: T): self.data = data self.next: Node[T] | None = None def __str__(self) -> str: return f"{self.data}" class LinkedStack(Generic[T]): """ Linked List Stack implementing push (to top), pop (from top) and is_empty >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(5) >>> stack.push(9) >>> stack.push('python') >>> stack.is_empty() False >>> stack.pop() 'python' >>> stack.push('algorithms') >>> stack.pop() 'algorithms' >>> stack.pop() 9 >>> stack.pop() 5 >>> stack.is_empty() True >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack """ def __init__(self) -> None: self.top: Node[T] | None = None def __iter__(self) -> Iterator[T]: node = self.top while node: yield node.data node = node.next def __str__(self) -> str: """ >>> stack = LinkedStack() >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> str(stack) 'a->b->c' """ return "->".join([str(item) for item in self]) def __len__(self) -> int: """ >>> stack = LinkedStack() >>> len(stack) == 0 True >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> len(stack) == 3 True """ return len(tuple(iter(self))) def is_empty(self) -> bool: """ >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(1) >>> stack.is_empty() False """ return self.top is None def push(self, item: T) -> None: """ >>> stack = LinkedStack() >>> stack.push("Python") >>> stack.push("Java") >>> stack.push("C") >>> str(stack) 'C->Java->Python' """ node = Node(item) if not self.is_empty(): node.next = self.top self.top = node def pop(self) -> T: """ >>> stack = LinkedStack() >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> stack.pop() == 'a' True >>> stack.pop() == 'b' True >>> stack.pop() == 'c' True """ if self.is_empty(): raise IndexError("pop from empty stack") assert isinstance(self.top, Node) pop_node = self.top self.top = self.top.next return pop_node.data def peek(self) -> T: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> stack.peek() 'Python' """ if self.is_empty(): raise IndexError("peek from empty stack") assert self.top is not None return self.top.data def clear(self) -> None: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> str(stack) 'Python->C->Java' >>> stack.clear() >>> len(stack) == 0 True """ self.top = None if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
# fibonacci.py """ Calculates the Fibonacci sequence using iteration, recursion, memoization, and a simplified form of Binet's formula NOTE 1: the iterative, recursive, memoization functions are more accurate than the Binet's formula function because the Binet formula function uses floats NOTE 2: the Binet's formula function is much more limited in the size of inputs that it can handle due to the size limitations of Python floats RESULTS: (n = 20) fib_iterative runtime: 0.0055 ms fib_recursive runtime: 6.5627 ms fib_memoization runtime: 0.0107 ms fib_binet runtime: 0.0174 ms """ import functools from math import sqrt from time import time def time_func(func, *args, **kwargs): """ Times the execution of a function with parameters """ start = time() output = func(*args, **kwargs) end = time() if int(end - start) > 0: print(f"{func.__name__} runtime: {(end - start):0.4f} s") else: print(f"{func.__name__} runtime: {(end - start) * 1000:0.4f} ms") return output def fib_iterative(n: int) -> list[int]: """ Calculates the first n (0-indexed) Fibonacci numbers using iteration >>> fib_iterative(0) [0] >>> fib_iterative(1) [0, 1] >>> fib_iterative(5) [0, 1, 1, 2, 3, 5] >>> fib_iterative(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_iterative(-1) Traceback (most recent call last): ... Exception: n is negative """ if n < 0: raise Exception("n is negative") if n == 0: return [0] fib = [0, 1] for _ in range(n - 1): fib.append(fib[-1] + fib[-2]) return fib def fib_recursive(n: int) -> list[int]: """ Calculates the first n (0-indexed) Fibonacci numbers using recursion >>> fib_iterative(0) [0] >>> fib_iterative(1) [0, 1] >>> fib_iterative(5) [0, 1, 1, 2, 3, 5] >>> fib_iterative(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_iterative(-1) Traceback (most recent call last): ... Exception: n is negative """ def fib_recursive_term(i: int) -> int: """ Calculates the i-th (0-indexed) Fibonacci number using recursion """ if i < 0: raise Exception("n is negative") if i < 2: return i return fib_recursive_term(i - 1) + fib_recursive_term(i - 2) if n < 0: raise Exception("n is negative") return [fib_recursive_term(i) for i in range(n + 1)] def fib_recursive_cached(n: int) -> list[int]: """ Calculates the first n (0-indexed) Fibonacci numbers using recursion >>> fib_iterative(0) [0] >>> fib_iterative(1) [0, 1] >>> fib_iterative(5) [0, 1, 1, 2, 3, 5] >>> fib_iterative(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_iterative(-1) Traceback (most recent call last): ... Exception: n is negative """ @functools.cache def fib_recursive_term(i: int) -> int: """ Calculates the i-th (0-indexed) Fibonacci number using recursion """ if i < 0: raise Exception("n is negative") if i < 2: return i return fib_recursive_term(i - 1) + fib_recursive_term(i - 2) if n < 0: raise Exception("n is negative") return [fib_recursive_term(i) for i in range(n + 1)] def fib_memoization(n: int) -> list[int]: """ Calculates the first n (0-indexed) Fibonacci numbers using memoization >>> fib_memoization(0) [0] >>> fib_memoization(1) [0, 1] >>> fib_memoization(5) [0, 1, 1, 2, 3, 5] >>> fib_memoization(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_iterative(-1) Traceback (most recent call last): ... Exception: n is negative """ if n < 0: raise Exception("n is negative") # Cache must be outside recursuive function # other it will reset every time it calls itself. cache: dict[int, int] = {0: 0, 1: 1, 2: 1} # Prefilled cache def rec_fn_memoized(num: int) -> int: if num in cache: return cache[num] value = rec_fn_memoized(num - 1) + rec_fn_memoized(num - 2) cache[num] = value return value return [rec_fn_memoized(i) for i in range(n + 1)] def fib_binet(n: int) -> list[int]: """ Calculates the first n (0-indexed) Fibonacci numbers using a simplified form of Binet's formula: https://en.m.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding NOTE 1: this function diverges from fib_iterative at around n = 71, likely due to compounding floating-point arithmetic errors NOTE 2: this function doesn't accept n >= 1475 because it overflows thereafter due to the size limitations of Python floats >>> fib_binet(0) [0] >>> fib_binet(1) [0, 1] >>> fib_binet(5) [0, 1, 1, 2, 3, 5] >>> fib_binet(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_binet(-1) Traceback (most recent call last): ... Exception: n is negative >>> fib_binet(1475) Traceback (most recent call last): ... Exception: n is too large """ if n < 0: raise Exception("n is negative") if n >= 1475: raise Exception("n is too large") sqrt_5 = sqrt(5) phi = (1 + sqrt_5) / 2 return [round(phi**i / sqrt_5) for i in range(n + 1)] if __name__ == "__main__": num = 30 time_func(fib_iterative, num) time_func(fib_recursive, num) # Around 3s runtime time_func(fib_recursive_cached, num) # Around 0ms runtime time_func(fib_memoization, num) time_func(fib_binet, num)
# fibonacci.py """ Calculates the Fibonacci sequence using iteration, recursion, memoization, and a simplified form of Binet's formula NOTE 1: the iterative, recursive, memoization functions are more accurate than the Binet's formula function because the Binet formula function uses floats NOTE 2: the Binet's formula function is much more limited in the size of inputs that it can handle due to the size limitations of Python floats RESULTS: (n = 20) fib_iterative runtime: 0.0055 ms fib_recursive runtime: 6.5627 ms fib_memoization runtime: 0.0107 ms fib_binet runtime: 0.0174 ms """ import functools from math import sqrt from time import time def time_func(func, *args, **kwargs): """ Times the execution of a function with parameters """ start = time() output = func(*args, **kwargs) end = time() if int(end - start) > 0: print(f"{func.__name__} runtime: {(end - start):0.4f} s") else: print(f"{func.__name__} runtime: {(end - start) * 1000:0.4f} ms") return output def fib_iterative(n: int) -> list[int]: """ Calculates the first n (0-indexed) Fibonacci numbers using iteration >>> fib_iterative(0) [0] >>> fib_iterative(1) [0, 1] >>> fib_iterative(5) [0, 1, 1, 2, 3, 5] >>> fib_iterative(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_iterative(-1) Traceback (most recent call last): ... Exception: n is negative """ if n < 0: raise Exception("n is negative") if n == 0: return [0] fib = [0, 1] for _ in range(n - 1): fib.append(fib[-1] + fib[-2]) return fib def fib_recursive(n: int) -> list[int]: """ Calculates the first n (0-indexed) Fibonacci numbers using recursion >>> fib_iterative(0) [0] >>> fib_iterative(1) [0, 1] >>> fib_iterative(5) [0, 1, 1, 2, 3, 5] >>> fib_iterative(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_iterative(-1) Traceback (most recent call last): ... Exception: n is negative """ def fib_recursive_term(i: int) -> int: """ Calculates the i-th (0-indexed) Fibonacci number using recursion """ if i < 0: raise Exception("n is negative") if i < 2: return i return fib_recursive_term(i - 1) + fib_recursive_term(i - 2) if n < 0: raise Exception("n is negative") return [fib_recursive_term(i) for i in range(n + 1)] def fib_recursive_cached(n: int) -> list[int]: """ Calculates the first n (0-indexed) Fibonacci numbers using recursion >>> fib_iterative(0) [0] >>> fib_iterative(1) [0, 1] >>> fib_iterative(5) [0, 1, 1, 2, 3, 5] >>> fib_iterative(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_iterative(-1) Traceback (most recent call last): ... Exception: n is negative """ @functools.cache def fib_recursive_term(i: int) -> int: """ Calculates the i-th (0-indexed) Fibonacci number using recursion """ if i < 0: raise Exception("n is negative") if i < 2: return i return fib_recursive_term(i - 1) + fib_recursive_term(i - 2) if n < 0: raise Exception("n is negative") return [fib_recursive_term(i) for i in range(n + 1)] def fib_memoization(n: int) -> list[int]: """ Calculates the first n (0-indexed) Fibonacci numbers using memoization >>> fib_memoization(0) [0] >>> fib_memoization(1) [0, 1] >>> fib_memoization(5) [0, 1, 1, 2, 3, 5] >>> fib_memoization(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_iterative(-1) Traceback (most recent call last): ... Exception: n is negative """ if n < 0: raise Exception("n is negative") # Cache must be outside recursuive function # other it will reset every time it calls itself. cache: dict[int, int] = {0: 0, 1: 1, 2: 1} # Prefilled cache def rec_fn_memoized(num: int) -> int: if num in cache: return cache[num] value = rec_fn_memoized(num - 1) + rec_fn_memoized(num - 2) cache[num] = value return value return [rec_fn_memoized(i) for i in range(n + 1)] def fib_binet(n: int) -> list[int]: """ Calculates the first n (0-indexed) Fibonacci numbers using a simplified form of Binet's formula: https://en.m.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding NOTE 1: this function diverges from fib_iterative at around n = 71, likely due to compounding floating-point arithmetic errors NOTE 2: this function doesn't accept n >= 1475 because it overflows thereafter due to the size limitations of Python floats >>> fib_binet(0) [0] >>> fib_binet(1) [0, 1] >>> fib_binet(5) [0, 1, 1, 2, 3, 5] >>> fib_binet(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_binet(-1) Traceback (most recent call last): ... Exception: n is negative >>> fib_binet(1475) Traceback (most recent call last): ... Exception: n is too large """ if n < 0: raise Exception("n is negative") if n >= 1475: raise Exception("n is too large") sqrt_5 = sqrt(5) phi = (1 + sqrt_5) / 2 return [round(phi**i / sqrt_5) for i in range(n + 1)] if __name__ == "__main__": num = 30 time_func(fib_iterative, num) time_func(fib_recursive, num) # Around 3s runtime time_func(fib_recursive_cached, num) # Around 0ms runtime time_func(fib_memoization, num) time_func(fib_binet, num)
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Problem 125: https://projecteuler.net/problem=125 The palindromic number 595 is interesting because it can be written as the sum of consecutive squares: 6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2. There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums, and the sum of these palindromes is 4164. Note that 1 = 0^2 + 1^2 has not been included as this problem is concerned with the squares of positive integers. Find the sum of all the numbers less than 10^8 that are both palindromic and can be written as the sum of consecutive squares. """ LIMIT = 10**8 def is_palindrome(n: int) -> bool: """ Check if an integer is palindromic. >>> is_palindrome(12521) True >>> is_palindrome(12522) False >>> is_palindrome(12210) False """ if n % 10 == 0: return False s = str(n) return s == s[::-1] def solution() -> int: """ Returns the sum of all numbers less than 1e8 that are both palindromic and can be written as the sum of consecutive squares. """ answer = set() first_square = 1 sum_squares = 5 while sum_squares < LIMIT: last_square = first_square + 1 while sum_squares < LIMIT: if is_palindrome(sum_squares): answer.add(sum_squares) last_square += 1 sum_squares += last_square**2 first_square += 1 sum_squares = first_square**2 + (first_square + 1) ** 2 return sum(answer) if __name__ == "__main__": print(solution())
""" Problem 125: https://projecteuler.net/problem=125 The palindromic number 595 is interesting because it can be written as the sum of consecutive squares: 6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2. There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums, and the sum of these palindromes is 4164. Note that 1 = 0^2 + 1^2 has not been included as this problem is concerned with the squares of positive integers. Find the sum of all the numbers less than 10^8 that are both palindromic and can be written as the sum of consecutive squares. """ LIMIT = 10**8 def is_palindrome(n: int) -> bool: """ Check if an integer is palindromic. >>> is_palindrome(12521) True >>> is_palindrome(12522) False >>> is_palindrome(12210) False """ if n % 10 == 0: return False s = str(n) return s == s[::-1] def solution() -> int: """ Returns the sum of all numbers less than 1e8 that are both palindromic and can be written as the sum of consecutive squares. """ answer = set() first_square = 1 sum_squares = 5 while sum_squares < LIMIT: last_square = first_square + 1 while sum_squares < LIMIT: if is_palindrome(sum_squares): answer.add(sum_squares) last_square += 1 sum_squares += last_square**2 first_square += 1 sum_squares = first_square**2 + (first_square + 1) ** 2 return sum(answer) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
def match_word_pattern(pattern: str, input_string: str) -> bool: """ Determine if a given pattern matches a string using backtracking. pattern: The pattern to match. input_string: The string to match against the pattern. return: True if the pattern matches the string, False otherwise. >>> match_word_pattern("aba", "GraphTreesGraph") True >>> match_word_pattern("xyx", "PythonRubyPython") True >>> match_word_pattern("GG", "PythonJavaPython") False """ def backtrack(pattern_index: int, str_index: int) -> bool: """ >>> backtrack(0, 0) True >>> backtrack(0, 1) True >>> backtrack(0, 4) False """ if pattern_index == len(pattern) and str_index == len(input_string): return True if pattern_index == len(pattern) or str_index == len(input_string): return False char = pattern[pattern_index] if char in pattern_map: mapped_str = pattern_map[char] if input_string.startswith(mapped_str, str_index): return backtrack(pattern_index + 1, str_index + len(mapped_str)) else: return False for end in range(str_index + 1, len(input_string) + 1): substr = input_string[str_index:end] if substr in str_map: continue pattern_map[char] = substr str_map[substr] = char if backtrack(pattern_index + 1, end): return True del pattern_map[char] del str_map[substr] return False pattern_map: dict[str, str] = {} str_map: dict[str, str] = {} return backtrack(0, 0) if __name__ == "__main__": import doctest doctest.testmod()
def match_word_pattern(pattern: str, input_string: str) -> bool: """ Determine if a given pattern matches a string using backtracking. pattern: The pattern to match. input_string: The string to match against the pattern. return: True if the pattern matches the string, False otherwise. >>> match_word_pattern("aba", "GraphTreesGraph") True >>> match_word_pattern("xyx", "PythonRubyPython") True >>> match_word_pattern("GG", "PythonJavaPython") False """ def backtrack(pattern_index: int, str_index: int) -> bool: """ >>> backtrack(0, 0) True >>> backtrack(0, 1) True >>> backtrack(0, 4) False """ if pattern_index == len(pattern) and str_index == len(input_string): return True if pattern_index == len(pattern) or str_index == len(input_string): return False char = pattern[pattern_index] if char in pattern_map: mapped_str = pattern_map[char] if input_string.startswith(mapped_str, str_index): return backtrack(pattern_index + 1, str_index + len(mapped_str)) else: return False for end in range(str_index + 1, len(input_string) + 1): substr = input_string[str_index:end] if substr in str_map: continue pattern_map[char] = substr str_map[substr] = char if backtrack(pattern_index + 1, end): return True del pattern_map[char] del str_map[substr] return False pattern_map: dict[str, str] = {} str_map: dict[str, str] = {} return backtrack(0, 0) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
# source - The ARRL Handbook for Radio Communications # https://en.wikipedia.org/wiki/RC_time_constant """ Description ----------- When a capacitor is connected with a potential source (AC or DC). It starts to charge at a general speed but when a resistor is connected in the circuit with in series to a capacitor then the capacitor charges slowly means it will take more time than usual. while the capacitor is being charged, the voltage is in exponential function with time. 'resistance(ohms) * capacitance(farads)' is called RC-timeconstant which may also be represented as Ο„ (tau). By using this RC-timeconstant we can find the voltage at any time 't' from the initiation of charging a capacitor with the help of the exponential function containing RC. Both at charging and discharging of a capacitor. """ from math import exp # value of exp = 2.718281828459… def charging_capacitor( source_voltage: float, # voltage in volts. resistance: float, # resistance in ohms. capacitance: float, # capacitance in farads. time_sec: float, # time in seconds after charging initiation of capacitor. ) -> float: """ Find capacitor voltage at any nth second after initiating its charging. Examples -------- >>> charging_capacitor(source_voltage=.2,resistance=.9,capacitance=8.4,time_sec=.5) 0.013 >>> charging_capacitor(source_voltage=2.2,resistance=3.5,capacitance=2.4,time_sec=9) 1.446 >>> charging_capacitor(source_voltage=15,resistance=200,capacitance=20,time_sec=2) 0.007 >>> charging_capacitor(20, 2000, 30*pow(10,-5), 4) 19.975 >>> charging_capacitor(source_voltage=0,resistance=10.0,capacitance=.30,time_sec=3) Traceback (most recent call last): ... ValueError: Source voltage must be positive. >>> charging_capacitor(source_voltage=20,resistance=-2000,capacitance=30,time_sec=4) Traceback (most recent call last): ... ValueError: Resistance must be positive. >>> charging_capacitor(source_voltage=30,resistance=1500,capacitance=0,time_sec=4) Traceback (most recent call last): ... ValueError: Capacitance must be positive. """ if source_voltage <= 0: raise ValueError("Source voltage must be positive.") if resistance <= 0: raise ValueError("Resistance must be positive.") if capacitance <= 0: raise ValueError("Capacitance must be positive.") return round(source_voltage * (1 - exp(-time_sec / (resistance * capacitance))), 3) if __name__ == "__main__": import doctest doctest.testmod()
# source - The ARRL Handbook for Radio Communications # https://en.wikipedia.org/wiki/RC_time_constant """ Description ----------- When a capacitor is connected with a potential source (AC or DC). It starts to charge at a general speed but when a resistor is connected in the circuit with in series to a capacitor then the capacitor charges slowly means it will take more time than usual. while the capacitor is being charged, the voltage is in exponential function with time. 'resistance(ohms) * capacitance(farads)' is called RC-timeconstant which may also be represented as Ο„ (tau). By using this RC-timeconstant we can find the voltage at any time 't' from the initiation of charging a capacitor with the help of the exponential function containing RC. Both at charging and discharging of a capacitor. """ from math import exp # value of exp = 2.718281828459… def charging_capacitor( source_voltage: float, # voltage in volts. resistance: float, # resistance in ohms. capacitance: float, # capacitance in farads. time_sec: float, # time in seconds after charging initiation of capacitor. ) -> float: """ Find capacitor voltage at any nth second after initiating its charging. Examples -------- >>> charging_capacitor(source_voltage=.2,resistance=.9,capacitance=8.4,time_sec=.5) 0.013 >>> charging_capacitor(source_voltage=2.2,resistance=3.5,capacitance=2.4,time_sec=9) 1.446 >>> charging_capacitor(source_voltage=15,resistance=200,capacitance=20,time_sec=2) 0.007 >>> charging_capacitor(20, 2000, 30*pow(10,-5), 4) 19.975 >>> charging_capacitor(source_voltage=0,resistance=10.0,capacitance=.30,time_sec=3) Traceback (most recent call last): ... ValueError: Source voltage must be positive. >>> charging_capacitor(source_voltage=20,resistance=-2000,capacitance=30,time_sec=4) Traceback (most recent call last): ... ValueError: Resistance must be positive. >>> charging_capacitor(source_voltage=30,resistance=1500,capacitance=0,time_sec=4) Traceback (most recent call last): ... ValueError: Capacitance must be positive. """ if source_voltage <= 0: raise ValueError("Source voltage must be positive.") if resistance <= 0: raise ValueError("Resistance must be positive.") if capacitance <= 0: raise ValueError("Capacitance must be positive.") return round(source_voltage * (1 - exp(-time_sec / (resistance * capacitance))), 3) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" This is an implementation of Pigeon Hole Sort. For doctests run following command: python3 -m doctest -v pigeon_sort.py or python -m doctest -v pigeon_sort.py For manual testing run: python pigeon_sort.py """ from __future__ import annotations def pigeon_sort(array: list[int]) -> list[int]: """ Implementation of pigeon hole sort algorithm :param array: Collection of comparable items :return: Collection sorted in ascending order >>> pigeon_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> pigeon_sort([]) [] >>> pigeon_sort([-2, -5, -45]) [-45, -5, -2] """ if len(array) == 0: return array _min, _max = min(array), max(array) # Compute the variables holes_range = _max - _min + 1 holes, holes_repeat = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: index = i - _min holes[index] = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. index = 0 for i in range(holes_range): while holes_repeat[i] > 0: array[index] = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by comma:\n") unsorted = [int(x) for x in user_input.split(",")] print(pigeon_sort(unsorted))
""" This is an implementation of Pigeon Hole Sort. For doctests run following command: python3 -m doctest -v pigeon_sort.py or python -m doctest -v pigeon_sort.py For manual testing run: python pigeon_sort.py """ from __future__ import annotations def pigeon_sort(array: list[int]) -> list[int]: """ Implementation of pigeon hole sort algorithm :param array: Collection of comparable items :return: Collection sorted in ascending order >>> pigeon_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> pigeon_sort([]) [] >>> pigeon_sort([-2, -5, -45]) [-45, -5, -2] """ if len(array) == 0: return array _min, _max = min(array), max(array) # Compute the variables holes_range = _max - _min + 1 holes, holes_repeat = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: index = i - _min holes[index] = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. index = 0 for i in range(holes_range): while holes_repeat[i] > 0: array[index] = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by comma:\n") unsorted = [int(x) for x in user_input.split(",")] print(pigeon_sort(unsorted))
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" This is a pure Python implementation of the binary insertion sort algorithm For doctests run following command: python -m doctest -v binary_insertion_sort.py or python3 -m doctest -v binary_insertion_sort.py For manual testing run: python binary_insertion_sort.py """ def binary_insertion_sort(collection: list) -> list: """Pure implementation of the binary insertion sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> binary_insertion_sort([0, 4, 1234, 4, 1]) [0, 1, 4, 4, 1234] >>> binary_insertion_sort([]) == sorted([]) True >>> binary_insertion_sort([-1, -2, -3]) == sorted([-1, -2, -3]) True >>> lst = ['d', 'a', 'b', 'e', 'c'] >>> binary_insertion_sort(lst) == sorted(lst) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> binary_insertion_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> binary_insertion_sort(collection) == sorted(collection) True """ n = len(collection) for i in range(1, n): val = collection[i] low = 0 high = i - 1 while low <= high: mid = (low + high) // 2 if val < collection[mid]: high = mid - 1 else: low = mid + 1 for j in range(i, low, -1): collection[j] = collection[j - 1] collection[low] = val return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(binary_insertion_sort(unsorted))
""" This is a pure Python implementation of the binary insertion sort algorithm For doctests run following command: python -m doctest -v binary_insertion_sort.py or python3 -m doctest -v binary_insertion_sort.py For manual testing run: python binary_insertion_sort.py """ def binary_insertion_sort(collection: list) -> list: """Pure implementation of the binary insertion sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> binary_insertion_sort([0, 4, 1234, 4, 1]) [0, 1, 4, 4, 1234] >>> binary_insertion_sort([]) == sorted([]) True >>> binary_insertion_sort([-1, -2, -3]) == sorted([-1, -2, -3]) True >>> lst = ['d', 'a', 'b', 'e', 'c'] >>> binary_insertion_sort(lst) == sorted(lst) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> binary_insertion_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> binary_insertion_sort(collection) == sorted(collection) True """ n = len(collection) for i in range(1, n): val = collection[i] low = 0 high = i - 1 while low <= high: mid = (low + high) // 2 if val < collection[mid]: high = mid - 1 else: low = mid + 1 for j in range(i, low, -1): collection[j] = collection[j - 1] collection[low] = val return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(binary_insertion_sort(unsorted))
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Title : Finding the value of either Gravitational Force, one of the masses or distance provided that the other three parameters are given. Description : Newton's Law of Universal Gravitation explains the presence of force of attraction between bodies having a definite mass situated at a distance. It is usually stated as that, every particle attracts every other particle in the universe with a force that is directly proportional to the product of their masses and inversely proportional to the square of the distance between their centers. The publication of the theory has become known as the "first great unification", as it marked the unification of the previously described phenomena of gravity on Earth with known astronomical behaviors. The equation for the universal gravitation is as follows: F = (G * mass_1 * mass_2) / (distance)^2 Source : - https://en.wikipedia.org/wiki/Newton%27s_law_of_universal_gravitation - Newton (1687) "Philosophiæ Naturalis Principia Mathematica" """ from __future__ import annotations # Define the Gravitational Constant G and the function GRAVITATIONAL_CONSTANT = 6.6743e-11 # unit of G : m^3 * kg^-1 * s^-2 def gravitational_law( force: float, mass_1: float, mass_2: float, distance: float ) -> dict[str, float]: """ Input Parameters ---------------- force : magnitude in Newtons mass_1 : mass in Kilograms mass_2 : mass in Kilograms distance : distance in Meters Returns ------- result : dict name, value pair of the parameter having Zero as it's value Returns the value of one of the parameters specified as 0, provided the values of other parameters are given. >>> gravitational_law(force=0, mass_1=5, mass_2=10, distance=20) {'force': 8.342875e-12} >>> gravitational_law(force=7367.382, mass_1=0, mass_2=74, distance=3048) {'mass_1': 1.385816317292268e+19} >>> gravitational_law(force=36337.283, mass_1=0, mass_2=0, distance=35584) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> gravitational_law(force=36337.283, mass_1=-674, mass_2=0, distance=35584) Traceback (most recent call last): ... ValueError: Mass can not be negative >>> gravitational_law(force=-847938e12, mass_1=674, mass_2=0, distance=9374) Traceback (most recent call last): ... ValueError: Gravitational force can not be negative """ product_of_mass = mass_1 * mass_2 if (force, mass_1, mass_2, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if force < 0: raise ValueError("Gravitational force can not be negative") if distance < 0: raise ValueError("Distance can not be negative") if mass_1 < 0 or mass_2 < 0: raise ValueError("Mass can not be negative") if force == 0: force = GRAVITATIONAL_CONSTANT * product_of_mass / (distance**2) return {"force": force} elif mass_1 == 0: mass_1 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_2) return {"mass_1": mass_1} elif mass_2 == 0: mass_2 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_1) return {"mass_2": mass_2} elif distance == 0: distance = (GRAVITATIONAL_CONSTANT * product_of_mass / (force)) ** 0.5 return {"distance": distance} raise ValueError("One and only one argument must be 0") # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
""" Title : Finding the value of either Gravitational Force, one of the masses or distance provided that the other three parameters are given. Description : Newton's Law of Universal Gravitation explains the presence of force of attraction between bodies having a definite mass situated at a distance. It is usually stated as that, every particle attracts every other particle in the universe with a force that is directly proportional to the product of their masses and inversely proportional to the square of the distance between their centers. The publication of the theory has become known as the "first great unification", as it marked the unification of the previously described phenomena of gravity on Earth with known astronomical behaviors. The equation for the universal gravitation is as follows: F = (G * mass_1 * mass_2) / (distance)^2 Source : - https://en.wikipedia.org/wiki/Newton%27s_law_of_universal_gravitation - Newton (1687) "Philosophiæ Naturalis Principia Mathematica" """ from __future__ import annotations # Define the Gravitational Constant G and the function GRAVITATIONAL_CONSTANT = 6.6743e-11 # unit of G : m^3 * kg^-1 * s^-2 def gravitational_law( force: float, mass_1: float, mass_2: float, distance: float ) -> dict[str, float]: """ Input Parameters ---------------- force : magnitude in Newtons mass_1 : mass in Kilograms mass_2 : mass in Kilograms distance : distance in Meters Returns ------- result : dict name, value pair of the parameter having Zero as it's value Returns the value of one of the parameters specified as 0, provided the values of other parameters are given. >>> gravitational_law(force=0, mass_1=5, mass_2=10, distance=20) {'force': 8.342875e-12} >>> gravitational_law(force=7367.382, mass_1=0, mass_2=74, distance=3048) {'mass_1': 1.385816317292268e+19} >>> gravitational_law(force=36337.283, mass_1=0, mass_2=0, distance=35584) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> gravitational_law(force=36337.283, mass_1=-674, mass_2=0, distance=35584) Traceback (most recent call last): ... ValueError: Mass can not be negative >>> gravitational_law(force=-847938e12, mass_1=674, mass_2=0, distance=9374) Traceback (most recent call last): ... ValueError: Gravitational force can not be negative """ product_of_mass = mass_1 * mass_2 if (force, mass_1, mass_2, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if force < 0: raise ValueError("Gravitational force can not be negative") if distance < 0: raise ValueError("Distance can not be negative") if mass_1 < 0 or mass_2 < 0: raise ValueError("Mass can not be negative") if force == 0: force = GRAVITATIONAL_CONSTANT * product_of_mass / (distance**2) return {"force": force} elif mass_1 == 0: mass_1 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_2) return {"mass_1": mass_1} elif mass_2 == 0: mass_2 = (force) * (distance**2) / (GRAVITATIONAL_CONSTANT * mass_1) return {"mass_2": mass_2} elif distance == 0: distance = (GRAVITATIONAL_CONSTANT * product_of_mass / (force)) ** 0.5 return {"distance": distance} raise ValueError("One and only one argument must be 0") # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" The algorithm finds the pattern in given text using following rule. The bad-character rule considers the mismatched character in Text. The next occurrence of that character to the left in Pattern is found, If the mismatched character occurs to the left in Pattern, a shift is proposed that aligns text block and pattern. If the mismatched character does not occur to the left in Pattern, a shift is proposed that moves the entirety of Pattern past the point of mismatch in the text. If there no mismatch then the pattern matches with text block. Time Complexity : O(n/m) n=length of main string m=length of pattern string """ from __future__ import annotations class BoyerMooreSearch: def __init__(self, text: str, pattern: str): self.text, self.pattern = text, pattern self.textLen, self.patLen = len(text), len(pattern) def match_in_pattern(self, char: str) -> int: """finds the index of char in pattern in reverse order Parameters : char (chr): character to be searched Returns : i (int): index of char from last in pattern -1 (int): if char is not found in pattern """ for i in range(self.patLen - 1, -1, -1): if char == self.pattern[i]: return i return -1 def mismatch_in_text(self, current_pos: int) -> int: """ find the index of mis-matched character in text when compared with pattern from last Parameters : current_pos (int): current index position of text Returns : i (int): index of mismatched char from last in text -1 (int): if there is no mismatch between pattern and text block """ for i in range(self.patLen - 1, -1, -1): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def bad_character_heuristic(self) -> list[int]: # searches pattern in text and returns index positions positions = [] for i in range(self.textLen - self.patLen + 1): mismatch_index = self.mismatch_in_text(i) if mismatch_index == -1: positions.append(i) else: match_index = self.match_in_pattern(self.text[mismatch_index]) i = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions text = "ABAABA" pattern = "AB" bms = BoyerMooreSearch(text, pattern) positions = bms.bad_character_heuristic() if len(positions) == 0: print("No match found") else: print("Pattern found in following positions: ") print(positions)
""" The algorithm finds the pattern in given text using following rule. The bad-character rule considers the mismatched character in Text. The next occurrence of that character to the left in Pattern is found, If the mismatched character occurs to the left in Pattern, a shift is proposed that aligns text block and pattern. If the mismatched character does not occur to the left in Pattern, a shift is proposed that moves the entirety of Pattern past the point of mismatch in the text. If there no mismatch then the pattern matches with text block. Time Complexity : O(n/m) n=length of main string m=length of pattern string """ from __future__ import annotations class BoyerMooreSearch: def __init__(self, text: str, pattern: str): self.text, self.pattern = text, pattern self.textLen, self.patLen = len(text), len(pattern) def match_in_pattern(self, char: str) -> int: """finds the index of char in pattern in reverse order Parameters : char (chr): character to be searched Returns : i (int): index of char from last in pattern -1 (int): if char is not found in pattern """ for i in range(self.patLen - 1, -1, -1): if char == self.pattern[i]: return i return -1 def mismatch_in_text(self, current_pos: int) -> int: """ find the index of mis-matched character in text when compared with pattern from last Parameters : current_pos (int): current index position of text Returns : i (int): index of mismatched char from last in text -1 (int): if there is no mismatch between pattern and text block """ for i in range(self.patLen - 1, -1, -1): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def bad_character_heuristic(self) -> list[int]: # searches pattern in text and returns index positions positions = [] for i in range(self.textLen - self.patLen + 1): mismatch_index = self.mismatch_in_text(i) if mismatch_index == -1: positions.append(i) else: match_index = self.match_in_pattern(self.text[mismatch_index]) i = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions text = "ABAABA" pattern = "AB" bms = BoyerMooreSearch(text, pattern) positions = bms.bad_character_heuristic() if len(positions) == 0: print("No match found") else: print("Pattern found in following positions: ") print(positions)
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Description : Centripetal force is the force acting on an object in curvilinear motion directed towards the axis of rotation or centre of curvature. The unit of centripetal force is newton. The centripetal force is always directed perpendicular to the direction of the object’s displacement. Using Newton’s second law of motion, it is found that the centripetal force of an object moving in a circular path always acts towards the centre of the circle. The Centripetal Force Formula is given as the product of mass (in kg) and tangential velocity (in meters per second) squared, divided by the radius (in meters) that implies that on doubling the tangential velocity, the centripetal force will be quadrupled. Mathematically it is written as: F = mvΒ²/r Where, F is the Centripetal force, m is the mass of the object, v is the speed or velocity of the object and r is the radius. Reference: https://byjus.com/physics/centripetal-and-centrifugal-force/ """ def centripetal(mass: float, velocity: float, radius: float) -> float: """ The Centripetal Force formula is given as: (m*v*v)/r >>> round(centripetal(15.5,-30,10),2) 1395.0 >>> round(centripetal(10,15,5),2) 450.0 >>> round(centripetal(20,-50,15),2) 3333.33 >>> round(centripetal(12.25,40,25),2) 784.0 >>> round(centripetal(50,100,50),2) 10000.0 """ if mass < 0: raise ValueError("The mass of the body cannot be negative") if radius <= 0: raise ValueError("The radius is always a positive non zero integer") return (mass * (velocity) ** 2) / radius if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
""" Description : Centripetal force is the force acting on an object in curvilinear motion directed towards the axis of rotation or centre of curvature. The unit of centripetal force is newton. The centripetal force is always directed perpendicular to the direction of the object’s displacement. Using Newton’s second law of motion, it is found that the centripetal force of an object moving in a circular path always acts towards the centre of the circle. The Centripetal Force Formula is given as the product of mass (in kg) and tangential velocity (in meters per second) squared, divided by the radius (in meters) that implies that on doubling the tangential velocity, the centripetal force will be quadrupled. Mathematically it is written as: F = mvΒ²/r Where, F is the Centripetal force, m is the mass of the object, v is the speed or velocity of the object and r is the radius. Reference: https://byjus.com/physics/centripetal-and-centrifugal-force/ """ def centripetal(mass: float, velocity: float, radius: float) -> float: """ The Centripetal Force formula is given as: (m*v*v)/r >>> round(centripetal(15.5,-30,10),2) 1395.0 >>> round(centripetal(10,15,5),2) 450.0 >>> round(centripetal(20,-50,15),2) 3333.33 >>> round(centripetal(12.25,40,25),2) 784.0 >>> round(centripetal(50,100,50),2) 10000.0 """ if mass < 0: raise ValueError("The mass of the body cannot be negative") if radius <= 0: raise ValueError("The radius is always a positive non zero integer") return (mass * (velocity) ** 2) / radius if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
# XGBoost Regressor Example import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def data_handling(data: dict) -> tuple: # Split dataset into features and target. Data is features. """ >>> data_handling(( ... {'data':'[ 8.3252 41. 6.9841269 1.02380952 322. 2.55555556 37.88 -122.23 ]' ... ,'target':([4.526])})) ('[ 8.3252 41. 6.9841269 1.02380952 322. 2.55555556 37.88 -122.23 ]', [4.526]) """ return (data["data"], data["target"]) def xgboost( features: np.ndarray, target: np.ndarray, test_features: np.ndarray ) -> np.ndarray: """ >>> xgboost(np.array([[ 2.3571 , 52. , 6.00813008, 1.06775068, ... 907. , 2.45799458, 40.58 , -124.26]]),np.array([1.114]), ... np.array([[1.97840000e+00, 3.70000000e+01, 4.98858447e+00, 1.03881279e+00, ... 1.14300000e+03, 2.60958904e+00, 3.67800000e+01, -1.19780000e+02]])) array([[1.1139996]], dtype=float32) """ xgb = XGBRegressor( verbosity=0, random_state=42, tree_method="exact", base_score=0.5 ) xgb.fit(features, target) # Predict target for test data predictions = xgb.predict(test_features) predictions = predictions.reshape(len(predictions), 1) return predictions def main() -> None: """ >>> main() Mean Absolute Error : 0.30957163379906033 Mean Square Error : 0.22611560196662744 The URL for this algorithm https://xgboost.readthedocs.io/en/stable/ California house price dataset is used to demonstrate the algorithm. """ # Load California house price dataset california = fetch_california_housing() data, target = data_handling(california) x_train, x_test, y_train, y_test = train_test_split( data, target, test_size=0.25, random_state=1 ) predictions = xgboost(x_train, y_train, x_test) # Error printing print(f"Mean Absolute Error : {mean_absolute_error(y_test, predictions)}") print(f"Mean Square Error : {mean_squared_error(y_test, predictions)}") if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
# XGBoost Regressor Example import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def data_handling(data: dict) -> tuple: # Split dataset into features and target. Data is features. """ >>> data_handling(( ... {'data':'[ 8.3252 41. 6.9841269 1.02380952 322. 2.55555556 37.88 -122.23 ]' ... ,'target':([4.526])})) ('[ 8.3252 41. 6.9841269 1.02380952 322. 2.55555556 37.88 -122.23 ]', [4.526]) """ return (data["data"], data["target"]) def xgboost( features: np.ndarray, target: np.ndarray, test_features: np.ndarray ) -> np.ndarray: """ >>> xgboost(np.array([[ 2.3571 , 52. , 6.00813008, 1.06775068, ... 907. , 2.45799458, 40.58 , -124.26]]),np.array([1.114]), ... np.array([[1.97840000e+00, 3.70000000e+01, 4.98858447e+00, 1.03881279e+00, ... 1.14300000e+03, 2.60958904e+00, 3.67800000e+01, -1.19780000e+02]])) array([[1.1139996]], dtype=float32) """ xgb = XGBRegressor( verbosity=0, random_state=42, tree_method="exact", base_score=0.5 ) xgb.fit(features, target) # Predict target for test data predictions = xgb.predict(test_features) predictions = predictions.reshape(len(predictions), 1) return predictions def main() -> None: """ >>> main() Mean Absolute Error : 0.30957163379906033 Mean Square Error : 0.22611560196662744 The URL for this algorithm https://xgboost.readthedocs.io/en/stable/ California house price dataset is used to demonstrate the algorithm. """ # Load California house price dataset california = fetch_california_housing() data, target = data_handling(california) x_train, x_test, y_train, y_test = train_test_split( data, target, test_size=0.25, random_state=1 ) predictions = xgboost(x_train, y_train, x_test) # Error printing print(f"Mean Absolute Error : {mean_absolute_error(y_test, predictions)}") print(f"Mean Square Error : {mean_squared_error(y_test, predictions)}") if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
# Author: JoΓ£o Gustavo A. Amorim & Gabriel Kunz # Author email: joaogustavoamorim@gmail.com and gabriel-kunz@uergs.edu.br # Coding date: apr 2019 # Black: True """ * This code implement the Hamming code: https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, Hamming codes are a family of linear error-correcting codes. Hamming codes can detect up to two-bit errors or correct one-bit errors without detection of uncorrected errors. By contrast, the simple parity code cannot correct errors, and can detect only an odd number of bits in error. Hamming codes are perfect codes, that is, they achieve the highest possible rate for codes with their block length and minimum distance of three. * the implemented code consists of: * a function responsible for encoding the message (emitterConverter) * return the encoded message * a function responsible for decoding the message (receptorConverter) * return the decoded message and a ack of data integrity * how to use: to be used you must declare how many parity bits (sizePari) you want to include in the message. it is desired (for test purposes) to select a bit to be set as an error. This serves to check whether the code is working correctly. Lastly, the variable of the message/word that must be desired to be encoded (text). * how this work: declaration of variables (sizePari, be, text) converts the message/word (text) to binary using the text_to_bits function encodes the message using the rules of hamming encoding decodes the message using the rules of hamming encoding print the original message, the encoded message and the decoded message forces an error in the coded text variable decodes the message that was forced the error print the original message, the encoded message, the bit changed message and the decoded message """ # Imports import numpy as np # Functions of binary conversion-------------------------------------- def text_to_bits(text, encoding="utf-8", errors="surrogatepass"): """ >>> text_to_bits("msg") '011011010111001101100111' """ bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"): """ >>> text_from_bits('011011010111001101100111') 'msg' """ n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "\0" # Functions of hamming code------------------------------------------- def emitter_converter(size_par, data): """ :param size_par: how many parity bits the message must have :param data: information bits :return: message to be transmitted by unreliable medium - bits of information merged with parity bits >>> emitter_converter(4, "101010111111") ['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1'] """ if size_par + len(data) <= 2**size_par - (len(data) - 1): raise ValueError("size of parity don't match with size of data") data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data) + 1)] # sorted information data for the size of the output data data_ord = [] # data position template + parity data_out_gab = [] # parity bit counter qtd_bp = 0 # counter position of data bits cont_data = 0 for x in range(1, size_par + len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par: if (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a given parity cont_bo = 0 # counter to control the loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(cont_bo % 2) qtd_bp += 1 # Mount the message cont_bp = 0 # parity bit counter for x in range(size_par + len(data)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) return data_out def receptor_converter(size_par, data): """ >>> receptor_converter(4, "1111010010111111") (['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True) """ # data position template + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 # list of parity received parity_received = [] data_output = [] for x in range(1, len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_output.append(data[cont_data]) else: parity_received.append(data[cont_data]) cont_data += 1 # -----------calculates the parity with the data data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data_output) + 1)] # sorted information data for the size of the output data data_ord = [] # Data position feedback + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 for x in range(1, size_par + len(data_output) + 1): # Performs a template position of bits - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data_output[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a certain parity cont_bo = 0 # Counter to control loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(str(cont_bo % 2)) qtd_bp += 1 # Mount the message cont_bp = 0 # Parity bit counter for x in range(size_par + len(data_output)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) ack = parity_received == parity return data_output, ack # --------------------------------------------------------------------- """ # Example how to use # number of parity bits sizePari = 4 # location of the bit that will be forced an error be = 2 # Message/word to be encoded and decoded with hamming # text = input("Enter the word to be read: ") text = "Message01" # Convert the message to binary binaryText = text_to_bits(text) # Prints the binary of the string print("Text input in binary is '" + binaryText + "'") # total transmitted bits totalBits = len(binaryText) + sizePari print("Size of data is " + str(totalBits)) print("\n --Message exchange--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) print("\n --Force error--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) # forces error dataOut[-be] = "1" * (dataOut[-be] == "0") + "0" * (dataOut[-be] == "1") print("Data after transmission -> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) """
# Author: JoΓ£o Gustavo A. Amorim & Gabriel Kunz # Author email: joaogustavoamorim@gmail.com and gabriel-kunz@uergs.edu.br # Coding date: apr 2019 # Black: True """ * This code implement the Hamming code: https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, Hamming codes are a family of linear error-correcting codes. Hamming codes can detect up to two-bit errors or correct one-bit errors without detection of uncorrected errors. By contrast, the simple parity code cannot correct errors, and can detect only an odd number of bits in error. Hamming codes are perfect codes, that is, they achieve the highest possible rate for codes with their block length and minimum distance of three. * the implemented code consists of: * a function responsible for encoding the message (emitterConverter) * return the encoded message * a function responsible for decoding the message (receptorConverter) * return the decoded message and a ack of data integrity * how to use: to be used you must declare how many parity bits (sizePari) you want to include in the message. it is desired (for test purposes) to select a bit to be set as an error. This serves to check whether the code is working correctly. Lastly, the variable of the message/word that must be desired to be encoded (text). * how this work: declaration of variables (sizePari, be, text) converts the message/word (text) to binary using the text_to_bits function encodes the message using the rules of hamming encoding decodes the message using the rules of hamming encoding print the original message, the encoded message and the decoded message forces an error in the coded text variable decodes the message that was forced the error print the original message, the encoded message, the bit changed message and the decoded message """ # Imports import numpy as np # Functions of binary conversion-------------------------------------- def text_to_bits(text, encoding="utf-8", errors="surrogatepass"): """ >>> text_to_bits("msg") '011011010111001101100111' """ bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"): """ >>> text_from_bits('011011010111001101100111') 'msg' """ n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "\0" # Functions of hamming code------------------------------------------- def emitter_converter(size_par, data): """ :param size_par: how many parity bits the message must have :param data: information bits :return: message to be transmitted by unreliable medium - bits of information merged with parity bits >>> emitter_converter(4, "101010111111") ['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1'] """ if size_par + len(data) <= 2**size_par - (len(data) - 1): raise ValueError("size of parity don't match with size of data") data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data) + 1)] # sorted information data for the size of the output data data_ord = [] # data position template + parity data_out_gab = [] # parity bit counter qtd_bp = 0 # counter position of data bits cont_data = 0 for x in range(1, size_par + len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par: if (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a given parity cont_bo = 0 # counter to control the loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(cont_bo % 2) qtd_bp += 1 # Mount the message cont_bp = 0 # parity bit counter for x in range(size_par + len(data)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) return data_out def receptor_converter(size_par, data): """ >>> receptor_converter(4, "1111010010111111") (['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True) """ # data position template + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 # list of parity received parity_received = [] data_output = [] for x in range(1, len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_output.append(data[cont_data]) else: parity_received.append(data[cont_data]) cont_data += 1 # -----------calculates the parity with the data data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data_output) + 1)] # sorted information data for the size of the output data data_ord = [] # Data position feedback + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 for x in range(1, size_par + len(data_output) + 1): # Performs a template position of bits - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data_output[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a certain parity cont_bo = 0 # Counter to control loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(str(cont_bo % 2)) qtd_bp += 1 # Mount the message cont_bp = 0 # Parity bit counter for x in range(size_par + len(data_output)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) ack = parity_received == parity return data_output, ack # --------------------------------------------------------------------- """ # Example how to use # number of parity bits sizePari = 4 # location of the bit that will be forced an error be = 2 # Message/word to be encoded and decoded with hamming # text = input("Enter the word to be read: ") text = "Message01" # Convert the message to binary binaryText = text_to_bits(text) # Prints the binary of the string print("Text input in binary is '" + binaryText + "'") # total transmitted bits totalBits = len(binaryText) + sizePari print("Size of data is " + str(totalBits)) print("\n --Message exchange--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) print("\n --Force error--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) # forces error dataOut[-be] = "1" * (dataOut[-be] == "0") + "0" * (dataOut[-be] == "1") print("Data after transmission -> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) """
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Implementation of finding nth fibonacci number using matrix exponentiation. Time Complexity is about O(log(n)*8), where 8 is the complexity of matrix multiplication of size 2 by 2. And on the other hand complexity of bruteforce solution is O(n). As we know f[n] = f[n-1] + f[n-1] Converting to matrix, [f(n),f(n-1)] = [[1,1],[1,0]] * [f(n-1),f(n-2)] -> [f(n),f(n-1)] = [[1,1],[1,0]]^2 * [f(n-2),f(n-3)] ... ... -> [f(n),f(n-1)] = [[1,1],[1,0]]^(n-1) * [f(1),f(0)] So we just need the n times multiplication of the matrix [1,1],[1,0]]. We can decrease the n times multiplication by following the divide and conquer approach. """ def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: matrix_c = [] n = len(matrix_a) for i in range(n): list_1 = [] for j in range(n): val = 0 for k in range(n): val = val + matrix_a[i][k] * matrix_b[k][j] list_1.append(val) matrix_c.append(list_1) return matrix_c def identity(n: int) -> list[list[int]]: return [[int(row == column) for column in range(n)] for row in range(n)] def nth_fibonacci_matrix(n: int) -> int: """ >>> nth_fibonacci_matrix(100) 354224848179261915075 >>> nth_fibonacci_matrix(-100) -100 """ if n <= 1: return n res_matrix = identity(2) fibonacci_matrix = [[1, 1], [1, 0]] n = n - 1 while n > 0: if n % 2 == 1: res_matrix = multiply(res_matrix, fibonacci_matrix) fibonacci_matrix = multiply(fibonacci_matrix, fibonacci_matrix) n = int(n / 2) return res_matrix[0][0] def nth_fibonacci_bruteforce(n: int) -> int: """ >>> nth_fibonacci_bruteforce(100) 354224848179261915075 >>> nth_fibonacci_bruteforce(-100) -100 """ if n <= 1: return n fib0 = 0 fib1 = 1 for _ in range(2, n + 1): fib0, fib1 = fib1, fib0 + fib1 return fib1 def main() -> None: for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split(): n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000 print( f"{ordinal} fibonacci number using matrix exponentiation is " f"{nth_fibonacci_matrix(n)} and using bruteforce is " f"{nth_fibonacci_bruteforce(n)}\n" ) # from timeit import timeit # print(timeit("nth_fibonacci_matrix(1000000)", # "from main import nth_fibonacci_matrix", number=5)) # print(timeit("nth_fibonacci_bruteforce(1000000)", # "from main import nth_fibonacci_bruteforce", number=5)) # 2.3342058970001744 # 57.256506615000035 if __name__ == "__main__": import doctest doctest.testmod() main()
""" Implementation of finding nth fibonacci number using matrix exponentiation. Time Complexity is about O(log(n)*8), where 8 is the complexity of matrix multiplication of size 2 by 2. And on the other hand complexity of bruteforce solution is O(n). As we know f[n] = f[n-1] + f[n-1] Converting to matrix, [f(n),f(n-1)] = [[1,1],[1,0]] * [f(n-1),f(n-2)] -> [f(n),f(n-1)] = [[1,1],[1,0]]^2 * [f(n-2),f(n-3)] ... ... -> [f(n),f(n-1)] = [[1,1],[1,0]]^(n-1) * [f(1),f(0)] So we just need the n times multiplication of the matrix [1,1],[1,0]]. We can decrease the n times multiplication by following the divide and conquer approach. """ def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: matrix_c = [] n = len(matrix_a) for i in range(n): list_1 = [] for j in range(n): val = 0 for k in range(n): val = val + matrix_a[i][k] * matrix_b[k][j] list_1.append(val) matrix_c.append(list_1) return matrix_c def identity(n: int) -> list[list[int]]: return [[int(row == column) for column in range(n)] for row in range(n)] def nth_fibonacci_matrix(n: int) -> int: """ >>> nth_fibonacci_matrix(100) 354224848179261915075 >>> nth_fibonacci_matrix(-100) -100 """ if n <= 1: return n res_matrix = identity(2) fibonacci_matrix = [[1, 1], [1, 0]] n = n - 1 while n > 0: if n % 2 == 1: res_matrix = multiply(res_matrix, fibonacci_matrix) fibonacci_matrix = multiply(fibonacci_matrix, fibonacci_matrix) n = int(n / 2) return res_matrix[0][0] def nth_fibonacci_bruteforce(n: int) -> int: """ >>> nth_fibonacci_bruteforce(100) 354224848179261915075 >>> nth_fibonacci_bruteforce(-100) -100 """ if n <= 1: return n fib0 = 0 fib1 = 1 for _ in range(2, n + 1): fib0, fib1 = fib1, fib0 + fib1 return fib1 def main() -> None: for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split(): n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000 print( f"{ordinal} fibonacci number using matrix exponentiation is " f"{nth_fibonacci_matrix(n)} and using bruteforce is " f"{nth_fibonacci_bruteforce(n)}\n" ) # from timeit import timeit # print(timeit("nth_fibonacci_matrix(1000000)", # "from main import nth_fibonacci_matrix", number=5)) # print(timeit("nth_fibonacci_bruteforce(1000000)", # "from main import nth_fibonacci_bruteforce", number=5)) # 2.3342058970001744 # 57.256506615000035 if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Project Euler 62 https://projecteuler.net/problem=62 The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube. Find the smallest cube for which exactly five permutations of its digits are cube. """ from collections import defaultdict def solution(max_base: int = 5) -> int: """ Iterate through every possible cube and sort the cube's digits in ascending order. Sorting maintains an ordering of the digits that allows you to compare permutations. Store each sorted sequence of digits in a dictionary, whose key is the sequence of digits and value is a list of numbers that are the base of the cube. Once you find 5 numbers that produce the same sequence of digits, return the smallest one, which is at index 0 since we insert each base number in ascending order. >>> solution(2) 125 >>> solution(3) 41063625 """ freqs = defaultdict(list) num = 0 while True: digits = get_digits(num) freqs[digits].append(num) if len(freqs[digits]) == max_base: base = freqs[digits][0] ** 3 return base num += 1 def get_digits(num: int) -> str: """ Computes the sorted sequence of digits of the cube of num. >>> get_digits(3) '27' >>> get_digits(99) '027999' >>> get_digits(123) '0166788' """ return "".join(sorted(str(num**3))) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler 62 https://projecteuler.net/problem=62 The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube. Find the smallest cube for which exactly five permutations of its digits are cube. """ from collections import defaultdict def solution(max_base: int = 5) -> int: """ Iterate through every possible cube and sort the cube's digits in ascending order. Sorting maintains an ordering of the digits that allows you to compare permutations. Store each sorted sequence of digits in a dictionary, whose key is the sequence of digits and value is a list of numbers that are the base of the cube. Once you find 5 numbers that produce the same sequence of digits, return the smallest one, which is at index 0 since we insert each base number in ascending order. >>> solution(2) 125 >>> solution(3) 41063625 """ freqs = defaultdict(list) num = 0 while True: digits = get_digits(num) freqs[digits].append(num) if len(freqs[digits]) == max_base: base = freqs[digits][0] ** 3 return base num += 1 def get_digits(num: int) -> str: """ Computes the sorted sequence of digits of the cube of num. >>> get_digits(3) '27' >>> get_digits(99) '027999' >>> get_digits(123) '0166788' """ return "".join(sorted(str(num**3))) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Problem Statement: By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. """ import os def solution(): """ Finds the maximum total in a triangle as described by the problem statement above. >>> solution() 7273 """ script_dir = os.path.dirname(os.path.realpath(__file__)) triangle = os.path.join(script_dir, "triangle.txt") with open(triangle) as f: triangle = f.readlines() a = [] for line in triangle: numbers_from_line = [] for number in line.strip().split(" "): numbers_from_line.append(int(number)) a.append(numbers_from_line) for i in range(1, len(a)): for j in range(len(a[i])): number1 = a[i - 1][j] if j != len(a[i - 1]) else 0 number2 = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(number1, number2) return max(a[-1]) if __name__ == "__main__": print(solution())
""" Problem Statement: By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. """ import os def solution(): """ Finds the maximum total in a triangle as described by the problem statement above. >>> solution() 7273 """ script_dir = os.path.dirname(os.path.realpath(__file__)) triangle = os.path.join(script_dir, "triangle.txt") with open(triangle) as f: triangle = f.readlines() a = [] for line in triangle: numbers_from_line = [] for number in line.strip().split(" "): numbers_from_line.append(int(number)) a.append(numbers_from_line) for i in range(1, len(a)): for j in range(len(a[i])): number1 = a[i - 1][j] if j != len(a[i - 1]) else 0 number2 = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(number1, number2) return max(a[-1]) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
from collections import deque def _input(message): return input(message).strip().split(" ") def initialize_unweighted_directed_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) return graph def initialize_unweighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) graph[y].append(x) return graph def initialize_weighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[tuple[int, int]]]: graph: dict[int, list[tuple[int, int]]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y, w = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> <weight> ")) graph[x].append((y, w)) graph[y].append((x, w)) return graph if __name__ == "__main__": n, m = (int(i) for i in _input("Number of nodes and edges: ")) graph_choice = int( _input( "Press 1 or 2 or 3 \n" "1. Unweighted directed \n" "2. Unweighted undirected \n" "3. Weighted undirected \n" )[0] ) g = { 1: initialize_unweighted_directed_graph, 2: initialize_unweighted_undirected_graph, 3: initialize_weighted_undirected_graph, }[graph_choice](n, m) """ -------------------------------------------------------------------------------- Depth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes S - Traversal Stack -------------------------------------------------------------------------------- """ def dfs(g, s): vis, _s = {s}, [s] print(s) while _s: flag = 0 for i in g[_s[-1]]: if i not in vis: _s.append(i) vis.add(i) flag = 1 print(i) break if not flag: _s.pop() """ -------------------------------------------------------------------------------- Breadth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes Q - Traversal Stack -------------------------------------------------------------------------------- """ def bfs(g, s): vis, q = {s}, deque([s]) print(s) while q: u = q.popleft() for v in g[u]: if v not in vis: vis.add(v) q.append(v) print(v) """ -------------------------------------------------------------------------------- Dijkstra's shortest path Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def dijk(g, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(g) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in g[u]: if v[0] not in known and dist[u] + v[1] < dist.get(v[0], 100000): dist[v[0]] = dist[u] + v[1] path[v[0]] = u for i in dist: if i != s: print(dist[i]) """ -------------------------------------------------------------------------------- Topological Sort -------------------------------------------------------------------------------- """ def topo(g, ind=None, q=None): if q is None: q = [1] if ind is None: ind = [0] * (len(g) + 1) # SInce oth Index is ignored for u in g: for v in g[u]: ind[v] += 1 q = deque() for i in g: if ind[i] == 0: q.append(i) if len(q) == 0: return v = q.popleft() print(v) for w in g[v]: ind[w] -= 1 if ind[w] == 0: q.append(w) topo(g, ind, q) """ -------------------------------------------------------------------------------- Reading an Adjacency matrix -------------------------------------------------------------------------------- """ def adjm(): n = input().strip() a = [] for _ in range(n): a.append(map(int, input().strip().split())) return a, n """ -------------------------------------------------------------------------------- Floyd Warshall's algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def floy(a_and_n): (a, n) = a_and_n dist = list(a) path = [[0] * n for i in range(n)] for k in range(n): for i in range(n): for j in range(n): if dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] path[i][k] = k print(dist) """ -------------------------------------------------------------------------------- Prim's MST Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to nearest node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def prim(g, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(g) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in g[u]: if v[0] not in known and v[1] < dist.get(v[0], 100000): dist[v[0]] = v[1] path[v[0]] = u return dist """ -------------------------------------------------------------------------------- Accepting Edge list Vars : n - Number of nodes m - Number of edges Returns : l - Edge list n - Number of Nodes -------------------------------------------------------------------------------- """ def edglist(): n, m = map(int, input().split(" ")) edges = [] for _ in range(m): edges.append(map(int, input().split(" "))) return edges, n """ -------------------------------------------------------------------------------- Kruskal's MST Algorithm Args : E - Edge list n - Number of Nodes Vars : s - Set of all nodes as unique disjoint sets (initially) -------------------------------------------------------------------------------- """ def krusk(e_and_n): # Sort edges on the basis of distance (e, n) = e_and_n e.sort(reverse=True, key=lambda x: x[2]) s = [{i} for i in range(1, n + 1)] while True: if len(s) == 1: break print(s) x = e.pop() for i in range(len(s)): if x[0] in s[i]: break for j in range(len(s)): if x[1] in s[j]: if i == j: break s[j].update(s[i]) s.pop(i) break # find the isolated node in the graph def find_isolated_nodes(graph): isolated = [] for node in graph: if not graph[node]: isolated.append(node) return isolated
from collections import deque def _input(message): return input(message).strip().split(" ") def initialize_unweighted_directed_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) return graph def initialize_unweighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[int]]: graph: dict[int, list[int]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> ")) graph[x].append(y) graph[y].append(x) return graph def initialize_weighted_undirected_graph( node_count: int, edge_count: int ) -> dict[int, list[tuple[int, int]]]: graph: dict[int, list[tuple[int, int]]] = {} for i in range(node_count): graph[i + 1] = [] for e in range(edge_count): x, y, w = (int(i) for i in _input(f"Edge {e + 1}: <node1> <node2> <weight> ")) graph[x].append((y, w)) graph[y].append((x, w)) return graph if __name__ == "__main__": n, m = (int(i) for i in _input("Number of nodes and edges: ")) graph_choice = int( _input( "Press 1 or 2 or 3 \n" "1. Unweighted directed \n" "2. Unweighted undirected \n" "3. Weighted undirected \n" )[0] ) g = { 1: initialize_unweighted_directed_graph, 2: initialize_unweighted_undirected_graph, 3: initialize_weighted_undirected_graph, }[graph_choice](n, m) """ -------------------------------------------------------------------------------- Depth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes S - Traversal Stack -------------------------------------------------------------------------------- """ def dfs(g, s): vis, _s = {s}, [s] print(s) while _s: flag = 0 for i in g[_s[-1]]: if i not in vis: _s.append(i) vis.add(i) flag = 1 print(i) break if not flag: _s.pop() """ -------------------------------------------------------------------------------- Breadth First Search. Args : G - Dictionary of edges s - Starting Node Vars : vis - Set of visited nodes Q - Traversal Stack -------------------------------------------------------------------------------- """ def bfs(g, s): vis, q = {s}, deque([s]) print(s) while q: u = q.popleft() for v in g[u]: if v not in vis: vis.add(v) q.append(v) print(v) """ -------------------------------------------------------------------------------- Dijkstra's shortest path Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def dijk(g, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(g) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in g[u]: if v[0] not in known and dist[u] + v[1] < dist.get(v[0], 100000): dist[v[0]] = dist[u] + v[1] path[v[0]] = u for i in dist: if i != s: print(dist[i]) """ -------------------------------------------------------------------------------- Topological Sort -------------------------------------------------------------------------------- """ def topo(g, ind=None, q=None): if q is None: q = [1] if ind is None: ind = [0] * (len(g) + 1) # SInce oth Index is ignored for u in g: for v in g[u]: ind[v] += 1 q = deque() for i in g: if ind[i] == 0: q.append(i) if len(q) == 0: return v = q.popleft() print(v) for w in g[v]: ind[w] -= 1 if ind[w] == 0: q.append(w) topo(g, ind, q) """ -------------------------------------------------------------------------------- Reading an Adjacency matrix -------------------------------------------------------------------------------- """ def adjm(): n = input().strip() a = [] for _ in range(n): a.append(map(int, input().strip().split())) return a, n """ -------------------------------------------------------------------------------- Floyd Warshall's algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to every other node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def floy(a_and_n): (a, n) = a_and_n dist = list(a) path = [[0] * n for i in range(n)] for k in range(n): for i in range(n): for j in range(n): if dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] path[i][k] = k print(dist) """ -------------------------------------------------------------------------------- Prim's MST Algorithm Args : G - Dictionary of edges s - Starting Node Vars : dist - Dictionary storing shortest distance from s to nearest node known - Set of knows nodes path - Preceding node in path -------------------------------------------------------------------------------- """ def prim(g, s): dist, known, path = {s: 0}, set(), {s: 0} while True: if len(known) == len(g) - 1: break mini = 100000 for i in dist: if i not in known and dist[i] < mini: mini = dist[i] u = i known.add(u) for v in g[u]: if v[0] not in known and v[1] < dist.get(v[0], 100000): dist[v[0]] = v[1] path[v[0]] = u return dist """ -------------------------------------------------------------------------------- Accepting Edge list Vars : n - Number of nodes m - Number of edges Returns : l - Edge list n - Number of Nodes -------------------------------------------------------------------------------- """ def edglist(): n, m = map(int, input().split(" ")) edges = [] for _ in range(m): edges.append(map(int, input().split(" "))) return edges, n """ -------------------------------------------------------------------------------- Kruskal's MST Algorithm Args : E - Edge list n - Number of Nodes Vars : s - Set of all nodes as unique disjoint sets (initially) -------------------------------------------------------------------------------- """ def krusk(e_and_n): # Sort edges on the basis of distance (e, n) = e_and_n e.sort(reverse=True, key=lambda x: x[2]) s = [{i} for i in range(1, n + 1)] while True: if len(s) == 1: break print(s) x = e.pop() for i in range(len(s)): if x[0] in s[i]: break for j in range(len(s)): if x[1] in s[j]: if i == j: break s[j].update(s[i]) s.pop(i) break # find the isolated node in the graph def find_isolated_nodes(graph): isolated = [] for node in graph: if not graph[node]: isolated.append(node) return isolated
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Checks if a system of forces is in static equilibrium. """ from __future__ import annotations from numpy import array, cos, cross, float64, radians, sin from numpy.typing import NDArray def polar_force( magnitude: float, angle: float, radian_mode: bool = False ) -> list[float]: """ Resolves force along rectangular components. (force, angle) => (force_x, force_y) >>> import math >>> force = polar_force(10, 45) >>> math.isclose(force[0], 7.071067811865477) True >>> math.isclose(force[1], 7.0710678118654755) True >>> force = polar_force(10, 3.14, radian_mode=True) >>> math.isclose(force[0], -9.999987317275396) True >>> math.isclose(force[1], 0.01592652916486828) True """ if radian_mode: return [magnitude * cos(angle), magnitude * sin(angle)] return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))] def in_static_equilibrium( forces: NDArray[float64], location: NDArray[float64], eps: float = 10**-1 ) -> bool: """ Check if a system is in equilibrium. It takes two numpy.array objects. forces ==> [ [force1_x, force1_y], [force2_x, force2_y], ....] location ==> [ [x1, y1], [x2, y2], ....] >>> force = array([[1, 1], [-1, 2]]) >>> location = array([[1, 0], [10, 0]]) >>> in_static_equilibrium(force, location) False """ # summation of moments is zero moments: NDArray[float64] = cross(location, forces) sum_moments: float = sum(moments) return abs(sum_moments) < eps if __name__ == "__main__": # Test to check if it works forces = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) location: NDArray[float64] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg forces = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) location = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg forces = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]]) location = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
""" Checks if a system of forces is in static equilibrium. """ from __future__ import annotations from numpy import array, cos, cross, float64, radians, sin from numpy.typing import NDArray def polar_force( magnitude: float, angle: float, radian_mode: bool = False ) -> list[float]: """ Resolves force along rectangular components. (force, angle) => (force_x, force_y) >>> import math >>> force = polar_force(10, 45) >>> math.isclose(force[0], 7.071067811865477) True >>> math.isclose(force[1], 7.0710678118654755) True >>> force = polar_force(10, 3.14, radian_mode=True) >>> math.isclose(force[0], -9.999987317275396) True >>> math.isclose(force[1], 0.01592652916486828) True """ if radian_mode: return [magnitude * cos(angle), magnitude * sin(angle)] return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))] def in_static_equilibrium( forces: NDArray[float64], location: NDArray[float64], eps: float = 10**-1 ) -> bool: """ Check if a system is in equilibrium. It takes two numpy.array objects. forces ==> [ [force1_x, force1_y], [force2_x, force2_y], ....] location ==> [ [x1, y1], [x2, y2], ....] >>> force = array([[1, 1], [-1, 2]]) >>> location = array([[1, 0], [10, 0]]) >>> in_static_equilibrium(force, location) False """ # summation of moments is zero moments: NDArray[float64] = cross(location, forces) sum_moments: float = sum(moments) return abs(sum_moments) < eps if __name__ == "__main__": # Test to check if it works forces = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) location: NDArray[float64] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg forces = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) location = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg forces = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]]) location = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
from typing import Any def bubble_sort(collection: list[Any]) -> list[Any]: """Pure implementation of bubble sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> bubble_sort([0, 5, 2, 3, 2]) [0, 2, 2, 3, 5] >>> bubble_sort([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2]) True >>> bubble_sort([]) == sorted([]) True >>> bubble_sort([-2, -45, -5]) == sorted([-2, -45, -5]) True >>> bubble_sort([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34]) True >>> bubble_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> bubble_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> bubble_sort(collection) == sorted(collection) True """ length = len(collection) for i in reversed(range(length)): swapped = False for j in range(i): if collection[j] > collection[j + 1]: swapped = True collection[j], collection[j + 1] = collection[j + 1], collection[j] if not swapped: break # Stop iteration if the collection is sorted. return collection if __name__ == "__main__": import doctest import time doctest.testmod() user_input = input("Enter numbers separated by a comma:").strip() unsorted = [int(item) for item in user_input.split(",")] start = time.process_time() print(*bubble_sort(unsorted), sep=",") print(f"Processing time: {(time.process_time() - start)%1e9 + 7}")
from typing import Any def bubble_sort(collection: list[Any]) -> list[Any]: """Pure implementation of bubble sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> bubble_sort([0, 5, 2, 3, 2]) [0, 2, 2, 3, 5] >>> bubble_sort([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2]) True >>> bubble_sort([]) == sorted([]) True >>> bubble_sort([-2, -45, -5]) == sorted([-2, -45, -5]) True >>> bubble_sort([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34]) True >>> bubble_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c']) True >>> import random >>> collection = random.sample(range(-50, 50), 100) >>> bubble_sort(collection) == sorted(collection) True >>> import string >>> collection = random.choices(string.ascii_letters + string.digits, k=100) >>> bubble_sort(collection) == sorted(collection) True """ length = len(collection) for i in reversed(range(length)): swapped = False for j in range(i): if collection[j] > collection[j + 1]: swapped = True collection[j], collection[j + 1] = collection[j + 1], collection[j] if not swapped: break # Stop iteration if the collection is sorted. return collection if __name__ == "__main__": import doctest import time doctest.testmod() user_input = input("Enter numbers separated by a comma:").strip() unsorted = [int(item) for item in user_input.split(",")] start = time.process_time() print(*bubble_sort(unsorted), sep=",") print(f"Processing time: {(time.process_time() - start)%1e9 + 7}")
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Linked Lists consists of Nodes. Nodes contain data and also may link to other nodes: - Head Node: First node, the address of the head node gives us access of the complete list - Last node: points to null """ from __future__ import annotations from typing import Any class Node: def __init__(self, item: Any, next: Any) -> None: # noqa: A002 self.item = item self.next = next class LinkedList: def __init__(self) -> None: self.head: Node | None = None self.size = 0 def add(self, item: Any, position: int = 0) -> None: """ Add an item to the LinkedList at the specified position. Default position is 0 (the head). Args: item (Any): The item to add to the LinkedList. position (int, optional): The position at which to add the item. Defaults to 0. Raises: ValueError: If the position is negative or out of bounds. >>> linked_list = LinkedList() >>> linked_list.add(1) >>> linked_list.add(2) >>> linked_list.add(3) >>> linked_list.add(4, 2) >>> print(linked_list) 3 --> 2 --> 4 --> 1 # Test adding to a negative position >>> linked_list.add(5, -3) Traceback (most recent call last): ... ValueError: Position must be non-negative # Test adding to an out-of-bounds position >>> linked_list.add(5,7) Traceback (most recent call last): ... ValueError: Out of bounds >>> linked_list.add(5, 4) >>> print(linked_list) 3 --> 2 --> 4 --> 1 --> 5 """ if position < 0: raise ValueError("Position must be non-negative") if position == 0 or self.head is None: new_node = Node(item, self.head) self.head = new_node else: current = self.head for _ in range(position - 1): current = current.next if current is None: raise ValueError("Out of bounds") new_node = Node(item, current.next) current.next = new_node self.size += 1 def remove(self) -> Any: # Switched 'self.is_empty()' to 'self.head is None' # because mypy was considering the possibility that 'self.head' # can be None in below else part and giving error if self.head is None: return None else: item = self.head.item self.head = self.head.next self.size -= 1 return item def is_empty(self) -> bool: return self.head is None def __str__(self) -> str: """ >>> linked_list = LinkedList() >>> linked_list.add(23) >>> linked_list.add(14) >>> linked_list.add(9) >>> print(linked_list) 9 --> 14 --> 23 """ if self.is_empty(): return "" else: iterate = self.head item_str = "" item_list: list[str] = [] while iterate: item_list.append(str(iterate.item)) iterate = iterate.next item_str = " --> ".join(item_list) return item_str def __len__(self) -> int: """ >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.add("a") >>> len(linked_list) 1 >>> linked_list.add("b") >>> len(linked_list) 2 >>> _ = linked_list.remove() >>> len(linked_list) 1 >>> _ = linked_list.remove() >>> len(linked_list) 0 """ return self.size
""" Linked Lists consists of Nodes. Nodes contain data and also may link to other nodes: - Head Node: First node, the address of the head node gives us access of the complete list - Last node: points to null """ from __future__ import annotations from typing import Any class Node: def __init__(self, item: Any, next: Any) -> None: # noqa: A002 self.item = item self.next = next class LinkedList: def __init__(self) -> None: self.head: Node | None = None self.size = 0 def add(self, item: Any, position: int = 0) -> None: """ Add an item to the LinkedList at the specified position. Default position is 0 (the head). Args: item (Any): The item to add to the LinkedList. position (int, optional): The position at which to add the item. Defaults to 0. Raises: ValueError: If the position is negative or out of bounds. >>> linked_list = LinkedList() >>> linked_list.add(1) >>> linked_list.add(2) >>> linked_list.add(3) >>> linked_list.add(4, 2) >>> print(linked_list) 3 --> 2 --> 4 --> 1 # Test adding to a negative position >>> linked_list.add(5, -3) Traceback (most recent call last): ... ValueError: Position must be non-negative # Test adding to an out-of-bounds position >>> linked_list.add(5,7) Traceback (most recent call last): ... ValueError: Out of bounds >>> linked_list.add(5, 4) >>> print(linked_list) 3 --> 2 --> 4 --> 1 --> 5 """ if position < 0: raise ValueError("Position must be non-negative") if position == 0 or self.head is None: new_node = Node(item, self.head) self.head = new_node else: current = self.head for _ in range(position - 1): current = current.next if current is None: raise ValueError("Out of bounds") new_node = Node(item, current.next) current.next = new_node self.size += 1 def remove(self) -> Any: # Switched 'self.is_empty()' to 'self.head is None' # because mypy was considering the possibility that 'self.head' # can be None in below else part and giving error if self.head is None: return None else: item = self.head.item self.head = self.head.next self.size -= 1 return item def is_empty(self) -> bool: return self.head is None def __str__(self) -> str: """ >>> linked_list = LinkedList() >>> linked_list.add(23) >>> linked_list.add(14) >>> linked_list.add(9) >>> print(linked_list) 9 --> 14 --> 23 """ if self.is_empty(): return "" else: iterate = self.head item_str = "" item_list: list[str] = [] while iterate: item_list.append(str(iterate.item)) iterate = iterate.next item_str = " --> ".join(item_list) return item_str def __len__(self) -> int: """ >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.add("a") >>> len(linked_list) 1 >>> linked_list.add("b") >>> len(linked_list) 2 >>> _ = linked_list.remove() >>> len(linked_list) 1 >>> _ = linked_list.remove() >>> len(linked_list) 0 """ return self.size
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a*b*c. References: - https://en.wikipedia.org/wiki/Pythagorean_triple """ def solution() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution() 31875000 """ for a in range(300): for b in range(a + 1, 400): for c in range(b + 1, 500): if (a + b + c) == 1000 and (a**2) + (b**2) == (c**2): return a * b * c return -1 def solution_fast() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution_fast() 31875000 """ for a in range(300): for b in range(400): c = 1000 - a - b if a < b < c and (a**2) + (b**2) == (c**2): return a * b * c return -1 def benchmark() -> None: """ Benchmark code comparing two different version function. """ import timeit print( timeit.timeit("solution()", setup="from __main__ import solution", number=1000) ) print( timeit.timeit( "solution_fast()", setup="from __main__ import solution_fast", number=1000 ) ) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a*b*c. References: - https://en.wikipedia.org/wiki/Pythagorean_triple """ def solution() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution() 31875000 """ for a in range(300): for b in range(a + 1, 400): for c in range(b + 1, 500): if (a + b + c) == 1000 and (a**2) + (b**2) == (c**2): return a * b * c return -1 def solution_fast() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution_fast() 31875000 """ for a in range(300): for b in range(400): c = 1000 - a - b if a < b < c and (a**2) + (b**2) == (c**2): return a * b * c return -1 def benchmark() -> None: """ Benchmark code comparing two different version function. """ import timeit print( timeit.timeit("solution()", setup="from __main__ import solution", number=1000) ) print( timeit.timeit( "solution_fast()", setup="from __main__ import solution_fast", number=1000 ) ) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Project Euler Problem 50: https://projecteuler.net/problem=50 Consecutive prime sum The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? """ from __future__ import annotations def prime_sieve(limit: int) -> list[int]: """ Sieve of Erotosthenes Function to return all the prime numbers up to a number 'limit' https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes >>> prime_sieve(3) [2] >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] """ is_prime = [True] * limit is_prime[0] = False is_prime[1] = False is_prime[2] = True for i in range(3, int(limit**0.5 + 1), 2): index = i * 2 while index < limit: is_prime[index] = False index = index + i primes = [2] for i in range(3, limit, 2): if is_prime[i]: primes.append(i) return primes def solution(ceiling: int = 1_000_000) -> int: """ Returns the biggest prime, below the celing, that can be written as the sum of consecutive the most consecutive primes. >>> solution(500) 499 >>> solution(1_000) 953 >>> solution(10_000) 9521 """ primes = prime_sieve(ceiling) length = 0 largest = 0 for i in range(len(primes)): for j in range(i + length, len(primes)): sol = sum(primes[i:j]) if sol >= ceiling: break if sol in primes: length = j - i largest = sol return largest if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 50: https://projecteuler.net/problem=50 Consecutive prime sum The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? """ from __future__ import annotations def prime_sieve(limit: int) -> list[int]: """ Sieve of Erotosthenes Function to return all the prime numbers up to a number 'limit' https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes >>> prime_sieve(3) [2] >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] """ is_prime = [True] * limit is_prime[0] = False is_prime[1] = False is_prime[2] = True for i in range(3, int(limit**0.5 + 1), 2): index = i * 2 while index < limit: is_prime[index] = False index = index + i primes = [2] for i in range(3, limit, 2): if is_prime[i]: primes.append(i) return primes def solution(ceiling: int = 1_000_000) -> int: """ Returns the biggest prime, below the celing, that can be written as the sum of consecutive the most consecutive primes. >>> solution(500) 499 >>> solution(1_000) 953 >>> solution(10_000) 9521 """ primes = prime_sieve(ceiling) length = 0 largest = 0 for i in range(len(primes)): for j in range(i + length, len(primes)): sol = sum(primes[i:j]) if sol >= ceiling: break if sol in primes: length = j - i largest = sol return largest if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" This is a pure Python implementation of the pancake sort algorithm For doctests run following command: python3 -m doctest -v pancake_sort.py or python -m doctest -v pancake_sort.py For manual testing run: python pancake_sort.py """ def pancake_sort(arr): """Sort Array with Pancake Sort. :param arr: Collection containing comparable items :return: Collection ordered in ascending order of items Examples: >>> pancake_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> pancake_sort([]) [] >>> pancake_sort([-2, -5, -45]) [-45, -5, -2] """ cur = len(arr) while cur > 1: # Find the maximum number in arr mi = arr.index(max(arr[0:cur])) # Reverse from 0 to mi arr = arr[mi::-1] + arr[mi + 1 : len(arr)] # Reverse whole list arr = arr[cur - 1 :: -1] + arr[cur : len(arr)] cur -= 1 return arr if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(pancake_sort(unsorted))
""" This is a pure Python implementation of the pancake sort algorithm For doctests run following command: python3 -m doctest -v pancake_sort.py or python -m doctest -v pancake_sort.py For manual testing run: python pancake_sort.py """ def pancake_sort(arr): """Sort Array with Pancake Sort. :param arr: Collection containing comparable items :return: Collection ordered in ascending order of items Examples: >>> pancake_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> pancake_sort([]) [] >>> pancake_sort([-2, -5, -45]) [-45, -5, -2] """ cur = len(arr) while cur > 1: # Find the maximum number in arr mi = arr.index(max(arr[0:cur])) # Reverse from 0 to mi arr = arr[mi::-1] + arr[mi + 1 : len(arr)] # Reverse whole list arr = arr[cur - 1 :: -1] + arr[cur : len(arr)] cur -= 1 return arr if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(pancake_sort(unsorted))
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
#!/usr/bin/env python3 from __future__ import annotations from collections.abc import Iterable, Iterator from typing import Any, Generic, TypeVar T = TypeVar("T", bound=bool) class SkewNode(Generic[T]): """ One node of the skew heap. Contains the value and references to two children. """ def __init__(self, value: T) -> None: self._value: T = value self.left: SkewNode[T] | None = None self.right: SkewNode[T] | None = None @property def value(self) -> T: """Return the value of the node.""" return self._value @staticmethod def merge( root1: SkewNode[T] | None, root2: SkewNode[T] | None ) -> SkewNode[T] | None: """Merge 2 nodes together.""" if not root1: return root2 if not root2: return root1 if root1.value > root2.value: root1, root2 = root2, root1 result = root1 temp = root1.right result.right = root1.left result.left = SkewNode.merge(temp, root2) return result class SkewHeap(Generic[T]): """ A data structure that allows inserting a new value and to pop the smallest values. Both operations take O(logN) time where N is the size of the structure. Wiki: https://en.wikipedia.org/wiki/Skew_heap Visualization: https://www.cs.usfca.edu/~galles/visualization/SkewHeap.html >>> list(SkewHeap([2, 3, 1, 5, 1, 7])) [1, 1, 2, 3, 5, 7] >>> sh = SkewHeap() >>> sh.pop() Traceback (most recent call last): ... IndexError: Can't get top element for the empty heap. >>> sh.insert(1) >>> sh.insert(-1) >>> sh.insert(0) >>> list(sh) [-1, 0, 1] """ def __init__(self, data: Iterable[T] | None = ()) -> None: """ >>> sh = SkewHeap([3, 1, 3, 7]) >>> list(sh) [1, 3, 3, 7] """ self._root: SkewNode[T] | None = None if data: for item in data: self.insert(item) def __bool__(self) -> bool: """ Check if the heap is not empty. >>> sh = SkewHeap() >>> bool(sh) False >>> sh.insert(1) >>> bool(sh) True >>> sh.clear() >>> bool(sh) False """ return self._root is not None def __iter__(self) -> Iterator[T]: """ Returns sorted list containing all the values in the heap. >>> sh = SkewHeap([3, 1, 3, 7]) >>> list(sh) [1, 3, 3, 7] """ result: list[Any] = [] while self: result.append(self.pop()) # Pushing items back to the heap not to clear it. for item in result: self.insert(item) return iter(result) def insert(self, value: T) -> None: """ Insert the value into the heap. >>> sh = SkewHeap() >>> sh.insert(3) >>> sh.insert(1) >>> sh.insert(3) >>> sh.insert(7) >>> list(sh) [1, 3, 3, 7] """ self._root = SkewNode.merge(self._root, SkewNode(value)) def pop(self) -> T | None: """ Pop the smallest value from the heap and return it. >>> sh = SkewHeap([3, 1, 3, 7]) >>> sh.pop() 1 >>> sh.pop() 3 >>> sh.pop() 3 >>> sh.pop() 7 >>> sh.pop() Traceback (most recent call last): ... IndexError: Can't get top element for the empty heap. """ result = self.top() self._root = ( SkewNode.merge(self._root.left, self._root.right) if self._root else None ) return result def top(self) -> T: """ Return the smallest value from the heap. >>> sh = SkewHeap() >>> sh.insert(3) >>> sh.top() 3 >>> sh.insert(1) >>> sh.top() 1 >>> sh.insert(3) >>> sh.top() 1 >>> sh.insert(7) >>> sh.top() 1 """ if not self._root: raise IndexError("Can't get top element for the empty heap.") return self._root.value def clear(self) -> None: """ Clear the heap. >>> sh = SkewHeap([3, 1, 3, 7]) >>> sh.clear() >>> sh.pop() Traceback (most recent call last): ... IndexError: Can't get top element for the empty heap. """ self._root = None if __name__ == "__main__": import doctest doctest.testmod()
#!/usr/bin/env python3 from __future__ import annotations from collections.abc import Iterable, Iterator from typing import Any, Generic, TypeVar T = TypeVar("T", bound=bool) class SkewNode(Generic[T]): """ One node of the skew heap. Contains the value and references to two children. """ def __init__(self, value: T) -> None: self._value: T = value self.left: SkewNode[T] | None = None self.right: SkewNode[T] | None = None @property def value(self) -> T: """Return the value of the node.""" return self._value @staticmethod def merge( root1: SkewNode[T] | None, root2: SkewNode[T] | None ) -> SkewNode[T] | None: """Merge 2 nodes together.""" if not root1: return root2 if not root2: return root1 if root1.value > root2.value: root1, root2 = root2, root1 result = root1 temp = root1.right result.right = root1.left result.left = SkewNode.merge(temp, root2) return result class SkewHeap(Generic[T]): """ A data structure that allows inserting a new value and to pop the smallest values. Both operations take O(logN) time where N is the size of the structure. Wiki: https://en.wikipedia.org/wiki/Skew_heap Visualization: https://www.cs.usfca.edu/~galles/visualization/SkewHeap.html >>> list(SkewHeap([2, 3, 1, 5, 1, 7])) [1, 1, 2, 3, 5, 7] >>> sh = SkewHeap() >>> sh.pop() Traceback (most recent call last): ... IndexError: Can't get top element for the empty heap. >>> sh.insert(1) >>> sh.insert(-1) >>> sh.insert(0) >>> list(sh) [-1, 0, 1] """ def __init__(self, data: Iterable[T] | None = ()) -> None: """ >>> sh = SkewHeap([3, 1, 3, 7]) >>> list(sh) [1, 3, 3, 7] """ self._root: SkewNode[T] | None = None if data: for item in data: self.insert(item) def __bool__(self) -> bool: """ Check if the heap is not empty. >>> sh = SkewHeap() >>> bool(sh) False >>> sh.insert(1) >>> bool(sh) True >>> sh.clear() >>> bool(sh) False """ return self._root is not None def __iter__(self) -> Iterator[T]: """ Returns sorted list containing all the values in the heap. >>> sh = SkewHeap([3, 1, 3, 7]) >>> list(sh) [1, 3, 3, 7] """ result: list[Any] = [] while self: result.append(self.pop()) # Pushing items back to the heap not to clear it. for item in result: self.insert(item) return iter(result) def insert(self, value: T) -> None: """ Insert the value into the heap. >>> sh = SkewHeap() >>> sh.insert(3) >>> sh.insert(1) >>> sh.insert(3) >>> sh.insert(7) >>> list(sh) [1, 3, 3, 7] """ self._root = SkewNode.merge(self._root, SkewNode(value)) def pop(self) -> T | None: """ Pop the smallest value from the heap and return it. >>> sh = SkewHeap([3, 1, 3, 7]) >>> sh.pop() 1 >>> sh.pop() 3 >>> sh.pop() 3 >>> sh.pop() 7 >>> sh.pop() Traceback (most recent call last): ... IndexError: Can't get top element for the empty heap. """ result = self.top() self._root = ( SkewNode.merge(self._root.left, self._root.right) if self._root else None ) return result def top(self) -> T: """ Return the smallest value from the heap. >>> sh = SkewHeap() >>> sh.insert(3) >>> sh.top() 3 >>> sh.insert(1) >>> sh.top() 1 >>> sh.insert(3) >>> sh.top() 1 >>> sh.insert(7) >>> sh.top() 1 """ if not self._root: raise IndexError("Can't get top element for the empty heap.") return self._root.value def clear(self) -> None: """ Clear the heap. >>> sh = SkewHeap([3, 1, 3, 7]) >>> sh.clear() >>> sh.pop() Traceback (most recent call last): ... IndexError: Can't get top element for the empty heap. """ self._root = None if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
# Information on 2's complement: https://en.wikipedia.org/wiki/Two%27s_complement def twos_complement(number: int) -> str: """ Take in a negative integer 'number'. Return the two's complement representation of 'number'. >>> twos_complement(0) '0b0' >>> twos_complement(-1) '0b11' >>> twos_complement(-5) '0b1011' >>> twos_complement(-17) '0b101111' >>> twos_complement(-207) '0b100110001' >>> twos_complement(1) Traceback (most recent call last): ... ValueError: input must be a negative integer """ if number > 0: raise ValueError("input must be a negative integer") binary_number_length = len(bin(number)[3:]) twos_complement_number = bin(abs(number) - (1 << binary_number_length))[3:] twos_complement_number = ( ( "1" + "0" * (binary_number_length - len(twos_complement_number)) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
# Information on 2's complement: https://en.wikipedia.org/wiki/Two%27s_complement def twos_complement(number: int) -> str: """ Take in a negative integer 'number'. Return the two's complement representation of 'number'. >>> twos_complement(0) '0b0' >>> twos_complement(-1) '0b11' >>> twos_complement(-5) '0b1011' >>> twos_complement(-17) '0b101111' >>> twos_complement(-207) '0b100110001' >>> twos_complement(1) Traceback (most recent call last): ... ValueError: input must be a negative integer """ if number > 0: raise ValueError("input must be a negative integer") binary_number_length = len(bin(number)[3:]) twos_complement_number = bin(abs(number) - (1 << binary_number_length))[3:] twos_complement_number = ( ( "1" + "0" * (binary_number_length - len(twos_complement_number)) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Given a function on floating number f(x) and two floating numbers β€˜a’ and β€˜b’ such that f(a) * f(b) < 0 and f(x) is continuous in [a, b]. Here f(x) represents algebraic or transcendental equation. Find root of function in interval [a, b] (Or find a value of x such that f(x) is 0) https://en.wikipedia.org/wiki/Bisection_method """ def equation(x: float) -> float: """ >>> equation(5) -15 >>> equation(0) 10 >>> equation(-5) -15 >>> equation(0.1) 9.99 >>> equation(-0.1) 9.99 """ return 10 - x * x def bisection(a: float, b: float) -> float: """ >>> bisection(-2, 5) 3.1611328125 >>> bisection(0, 6) 3.158203125 >>> bisection(2, 3) Traceback (most recent call last): ... ValueError: Wrong space! """ # Bolzano theory in order to find if there is a root between a and b if equation(a) * equation(b) >= 0: raise ValueError("Wrong space!") c = a while (b - a) >= 0.01: # Find middle point c = (a + b) / 2 # Check if middle point is root if equation(c) == 0.0: break # Decide the side to repeat the steps if equation(c) * equation(a) < 0: b = c else: a = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
""" Given a function on floating number f(x) and two floating numbers β€˜a’ and β€˜b’ such that f(a) * f(b) < 0 and f(x) is continuous in [a, b]. Here f(x) represents algebraic or transcendental equation. Find root of function in interval [a, b] (Or find a value of x such that f(x) is 0) https://en.wikipedia.org/wiki/Bisection_method """ def equation(x: float) -> float: """ >>> equation(5) -15 >>> equation(0) 10 >>> equation(-5) -15 >>> equation(0.1) 9.99 >>> equation(-0.1) 9.99 """ return 10 - x * x def bisection(a: float, b: float) -> float: """ >>> bisection(-2, 5) 3.1611328125 >>> bisection(0, 6) 3.158203125 >>> bisection(2, 3) Traceback (most recent call last): ... ValueError: Wrong space! """ # Bolzano theory in order to find if there is a root between a and b if equation(a) * equation(b) >= 0: raise ValueError("Wrong space!") c = a while (b - a) >= 0.01: # Find middle point c = (a + b) / 2 # Check if middle point is root if equation(c) == 0.0: break # Decide the side to repeat the steps if equation(c) * equation(a) < 0: b = c else: a = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
"""Absolute Value.""" def abs_val(num: float) -> float: """ Find the absolute value of a number. >>> abs_val(-5.1) 5.1 >>> abs_val(-5) == abs_val(5) True >>> abs_val(0) 0 """ return -num if num < 0 else num def abs_min(x: list[int]) -> int: """ >>> abs_min([0,5,1,11]) 0 >>> abs_min([3,-10,-2]) -2 >>> abs_min([]) Traceback (most recent call last): ... ValueError: abs_min() arg is an empty sequence """ if len(x) == 0: raise ValueError("abs_min() arg is an empty sequence") j = x[0] for i in x: if abs_val(i) < abs_val(j): j = i return j def abs_max(x: list[int]) -> int: """ >>> abs_max([0,5,1,11]) 11 >>> abs_max([3,-10,-2]) -10 >>> abs_max([]) Traceback (most recent call last): ... ValueError: abs_max() arg is an empty sequence """ if len(x) == 0: raise ValueError("abs_max() arg is an empty sequence") j = x[0] for i in x: if abs(i) > abs(j): j = i return j def abs_max_sort(x: list[int]) -> int: """ >>> abs_max_sort([0,5,1,11]) 11 >>> abs_max_sort([3,-10,-2]) -10 >>> abs_max_sort([]) Traceback (most recent call last): ... ValueError: abs_max_sort() arg is an empty sequence """ if len(x) == 0: raise ValueError("abs_max_sort() arg is an empty sequence") return sorted(x, key=abs)[-1] def test_abs_val(): """ >>> test_abs_val() """ assert abs_val(0) == 0 assert abs_val(34) == 34 assert abs_val(-100000000000) == 100000000000 a = [-3, -1, 2, -11] assert abs_max(a) == -11 assert abs_max_sort(a) == -11 assert abs_min(a) == -1 if __name__ == "__main__": import doctest doctest.testmod() test_abs_val() print(abs_val(-34)) # --> 34
"""Absolute Value.""" def abs_val(num: float) -> float: """ Find the absolute value of a number. >>> abs_val(-5.1) 5.1 >>> abs_val(-5) == abs_val(5) True >>> abs_val(0) 0 """ return -num if num < 0 else num def abs_min(x: list[int]) -> int: """ >>> abs_min([0,5,1,11]) 0 >>> abs_min([3,-10,-2]) -2 >>> abs_min([]) Traceback (most recent call last): ... ValueError: abs_min() arg is an empty sequence """ if len(x) == 0: raise ValueError("abs_min() arg is an empty sequence") j = x[0] for i in x: if abs_val(i) < abs_val(j): j = i return j def abs_max(x: list[int]) -> int: """ >>> abs_max([0,5,1,11]) 11 >>> abs_max([3,-10,-2]) -10 >>> abs_max([]) Traceback (most recent call last): ... ValueError: abs_max() arg is an empty sequence """ if len(x) == 0: raise ValueError("abs_max() arg is an empty sequence") j = x[0] for i in x: if abs(i) > abs(j): j = i return j def abs_max_sort(x: list[int]) -> int: """ >>> abs_max_sort([0,5,1,11]) 11 >>> abs_max_sort([3,-10,-2]) -10 >>> abs_max_sort([]) Traceback (most recent call last): ... ValueError: abs_max_sort() arg is an empty sequence """ if len(x) == 0: raise ValueError("abs_max_sort() arg is an empty sequence") return sorted(x, key=abs)[-1] def test_abs_val(): """ >>> test_abs_val() """ assert abs_val(0) == 0 assert abs_val(34) == 34 assert abs_val(-100000000000) == 100000000000 a = [-3, -1, 2, -11] assert abs_max(a) == -11 assert abs_max_sort(a) == -11 assert abs_min(a) == -1 if __name__ == "__main__": import doctest doctest.testmod() test_abs_val() print(abs_val(-34)) # --> 34
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). Leetcode reference: https://leetcode.com/problems/symmetric-tree/ """ from __future__ import annotations from dataclasses import dataclass @dataclass class Node: """ A Node has data variable and pointers to Nodes to its left and right. """ data: int left: Node | None = None right: Node | None = None def make_symmetric_tree() -> Node: r""" Create a symmetric tree for testing. The tree looks like this: 1 / \ 2 2 / \ / \ 3 4 4 3 """ root = Node(1) root.left = Node(2) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right.left = Node(4) root.right.right = Node(3) return root def make_asymmetric_tree() -> Node: r""" Create a asymmetric tree for testing. The tree looks like this: 1 / \ 2 2 / \ / \ 3 4 3 4 """ root = Node(1) root.left = Node(2) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right.left = Node(3) root.right.right = Node(4) return root def is_symmetric_tree(tree: Node) -> bool: """ Test cases for is_symmetric_tree function >>> is_symmetric_tree(make_symmetric_tree()) True >>> is_symmetric_tree(make_asymmetric_tree()) False """ if tree: return is_mirror(tree.left, tree.right) return True # An empty tree is considered symmetric. def is_mirror(left: Node | None, right: Node | None) -> bool: """ >>> tree1 = make_symmetric_tree() >>> tree1.right.right = Node(3) >>> is_mirror(tree1.left, tree1.right) True >>> tree2 = make_asymmetric_tree() >>> is_mirror(tree2.left, tree2.right) False """ if left is None and right is None: # Both sides are empty, which is symmetric. return True if left is None or right is None: # One side is empty while the other is not, which is not symmetric. return False if left.data == right.data: # The values match, so check the subtree return is_mirror(left.left, right.right) and is_mirror(left.right, right.left) return False if __name__ == "__main__": from doctest import testmod testmod()
""" Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). Leetcode reference: https://leetcode.com/problems/symmetric-tree/ """ from __future__ import annotations from dataclasses import dataclass @dataclass class Node: """ A Node has data variable and pointers to Nodes to its left and right. """ data: int left: Node | None = None right: Node | None = None def make_symmetric_tree() -> Node: r""" Create a symmetric tree for testing. The tree looks like this: 1 / \ 2 2 / \ / \ 3 4 4 3 """ root = Node(1) root.left = Node(2) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right.left = Node(4) root.right.right = Node(3) return root def make_asymmetric_tree() -> Node: r""" Create a asymmetric tree for testing. The tree looks like this: 1 / \ 2 2 / \ / \ 3 4 3 4 """ root = Node(1) root.left = Node(2) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right.left = Node(3) root.right.right = Node(4) return root def is_symmetric_tree(tree: Node) -> bool: """ Test cases for is_symmetric_tree function >>> is_symmetric_tree(make_symmetric_tree()) True >>> is_symmetric_tree(make_asymmetric_tree()) False """ if tree: return is_mirror(tree.left, tree.right) return True # An empty tree is considered symmetric. def is_mirror(left: Node | None, right: Node | None) -> bool: """ >>> tree1 = make_symmetric_tree() >>> tree1.right.right = Node(3) >>> is_mirror(tree1.left, tree1.right) True >>> tree2 = make_asymmetric_tree() >>> is_mirror(tree2.left, tree2.right) False """ if left is None and right is None: # Both sides are empty, which is symmetric. return True if left is None or right is None: # One side is empty while the other is not, which is not symmetric. return False if left.data == right.data: # The values match, so check the subtree return is_mirror(left.left, right.right) and is_mirror(left.right, right.left) return False if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" In laser physics, a "white cell" is a mirror system that acts as a delay line for the laser beam. The beam enters the cell, bounces around on the mirrors, and eventually works its way back out. The specific white cell we will be considering is an ellipse with the equation 4x^2 + y^2 = 100 The section corresponding to βˆ’0.01 ≀ x ≀ +0.01 at the top is missing, allowing the light to enter and exit through the hole. οΏΌοΏΌ The light beam in this problem starts at the point (0.0,10.1) just outside the white cell, and the beam first impacts the mirror at (1.4,-9.6). Each time the laser beam hits the surface of the ellipse, it follows the usual law of reflection "angle of incidence equals angle of reflection." That is, both the incident and reflected beams make the same angle with the normal line at the point of incidence. In the figure on the left, the red line shows the first two points of contact between the laser beam and the wall of the white cell; the blue line shows the line tangent to the ellipse at the point of incidence of the first bounce. The slope m of the tangent line at any point (x,y) of the given ellipse is: m = βˆ’4x/y The normal line is perpendicular to this tangent line at the point of incidence. The animation on the right shows the first 10 reflections of the beam. How many times does the beam hit the internal surface of the white cell before exiting? """ from math import isclose, sqrt def next_point( point_x: float, point_y: float, incoming_gradient: float ) -> tuple[float, float, float]: """ Given that a laser beam hits the interior of the white cell at point (point_x, point_y) with gradient incoming_gradient, return a tuple (x,y,m1) where the next point of contact with the interior is (x,y) with gradient m1. >>> next_point(5.0, 0.0, 0.0) (-5.0, 0.0, 0.0) >>> next_point(5.0, 0.0, -2.0) (0.0, -10.0, 2.0) """ # normal_gradient = gradient of line through which the beam is reflected # outgoing_gradient = gradient of reflected line normal_gradient = point_y / 4 / point_x s2 = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) c2 = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) outgoing_gradient = (s2 - c2 * incoming_gradient) / (c2 + s2 * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 quadratic_term = outgoing_gradient**2 + 4 linear_term = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) constant_term = (point_y - outgoing_gradient * point_x) ** 2 - 100 x_minus = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) x_plus = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) # two solutions, one of which is our input point next_x = x_minus if isclose(x_plus, point_x) else x_plus next_y = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def solution(first_x_coord: float = 1.4, first_y_coord: float = -9.6) -> int: """ Return the number of times that the beam hits the interior wall of the cell before exiting. >>> solution(0.00001,-10) 1 >>> solution(5, 0) 287 """ num_reflections: int = 0 point_x: float = first_x_coord point_y: float = first_y_coord gradient: float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): point_x, point_y, gradient = next_point(point_x, point_y, gradient) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f"{solution() = }")
""" In laser physics, a "white cell" is a mirror system that acts as a delay line for the laser beam. The beam enters the cell, bounces around on the mirrors, and eventually works its way back out. The specific white cell we will be considering is an ellipse with the equation 4x^2 + y^2 = 100 The section corresponding to βˆ’0.01 ≀ x ≀ +0.01 at the top is missing, allowing the light to enter and exit through the hole. οΏΌοΏΌ The light beam in this problem starts at the point (0.0,10.1) just outside the white cell, and the beam first impacts the mirror at (1.4,-9.6). Each time the laser beam hits the surface of the ellipse, it follows the usual law of reflection "angle of incidence equals angle of reflection." That is, both the incident and reflected beams make the same angle with the normal line at the point of incidence. In the figure on the left, the red line shows the first two points of contact between the laser beam and the wall of the white cell; the blue line shows the line tangent to the ellipse at the point of incidence of the first bounce. The slope m of the tangent line at any point (x,y) of the given ellipse is: m = βˆ’4x/y The normal line is perpendicular to this tangent line at the point of incidence. The animation on the right shows the first 10 reflections of the beam. How many times does the beam hit the internal surface of the white cell before exiting? """ from math import isclose, sqrt def next_point( point_x: float, point_y: float, incoming_gradient: float ) -> tuple[float, float, float]: """ Given that a laser beam hits the interior of the white cell at point (point_x, point_y) with gradient incoming_gradient, return a tuple (x,y,m1) where the next point of contact with the interior is (x,y) with gradient m1. >>> next_point(5.0, 0.0, 0.0) (-5.0, 0.0, 0.0) >>> next_point(5.0, 0.0, -2.0) (0.0, -10.0, 2.0) """ # normal_gradient = gradient of line through which the beam is reflected # outgoing_gradient = gradient of reflected line normal_gradient = point_y / 4 / point_x s2 = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) c2 = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) outgoing_gradient = (s2 - c2 * incoming_gradient) / (c2 + s2 * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 quadratic_term = outgoing_gradient**2 + 4 linear_term = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) constant_term = (point_y - outgoing_gradient * point_x) ** 2 - 100 x_minus = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) x_plus = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) # two solutions, one of which is our input point next_x = x_minus if isclose(x_plus, point_x) else x_plus next_y = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def solution(first_x_coord: float = 1.4, first_y_coord: float = -9.6) -> int: """ Return the number of times that the beam hits the interior wall of the cell before exiting. >>> solution(0.00001,-10) 1 >>> solution(5, 0) 287 """ num_reflections: int = 0 point_x: float = first_x_coord point_y: float = first_y_coord gradient: float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): point_x, point_y, gradient = next_point(point_x, point_y, gradient) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. # # To enable this hook, rename this file to "pre-commit". if git rev-parse --verify HEAD >/dev/null 2>&1 then against=HEAD else # Initial commit: diff against an empty tree object against=$(git hash-object -t tree /dev/null) fi # If you want to allow non-ASCII filenames set this variable to true. allownonascii=$(git config --bool hooks.allownonascii) # Redirect output to stderr. exec 1>&2 # Cross platform projects tend to avoid non-ASCII filenames; prevent # them from being added to the repository. We exploit the fact that the # printable range starts at the space character and ends with tilde. if [ "$allownonascii" != "true" ] && # Note that the use of brackets around a tr range is ok here, (it's # even required, for portability to Solaris 10's /usr/bin/tr), since # the square bracket bytes happen to fall in the designated range. test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 then cat <<\EOF Error: Attempt to add a non-ASCII file name. This can cause problems if you want to work with people on other platforms. To be portable it is advisable to rename the file. If you know what you are doing you can disable this check using: git config hooks.allownonascii true EOF exit 1 fi # If there are whitespace errors, print the offending file names and fail. exec git diff-index --check --cached $against --
#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. # # To enable this hook, rename this file to "pre-commit". if git rev-parse --verify HEAD >/dev/null 2>&1 then against=HEAD else # Initial commit: diff against an empty tree object against=$(git hash-object -t tree /dev/null) fi # If you want to allow non-ASCII filenames set this variable to true. allownonascii=$(git config --bool hooks.allownonascii) # Redirect output to stderr. exec 1>&2 # Cross platform projects tend to avoid non-ASCII filenames; prevent # them from being added to the repository. We exploit the fact that the # printable range starts at the space character and ends with tilde. if [ "$allownonascii" != "true" ] && # Note that the use of brackets around a tr range is ok here, (it's # even required, for portability to Solaris 10's /usr/bin/tr), since # the square bracket bytes happen to fall in the designated range. test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 then cat <<\EOF Error: Attempt to add a non-ASCII file name. This can cause problems if you want to work with people on other platforms. To be portable it is advisable to rename the file. If you know what you are doing you can disable this check using: git config hooks.allownonascii true EOF exit 1 fi # If there are whitespace errors, print the offending file names and fail. exec git diff-index --check --cached $against --
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
from __future__ import annotations def solve_maze( maze: list[list[int]], source_row: int, source_column: int, destination_row: int, destination_column: int, ) -> list[list[int]]: """ This method solves the "rat in maze" problem. Parameters : - maze: A two dimensional matrix of zeros and ones. - source_row: The row index of the starting point. - source_column: The column index of the starting point. - destination_row: The row index of the destination point. - destination_column: The column index of the destination point. Returns: - solution: A 2D matrix representing the solution path if it exists. Raises: - ValueError: If no solution exists or if the source or destination coordinates are invalid. Description: This method navigates through a maze represented as an n by n matrix, starting from a specified source cell and aiming to reach a destination cell. The maze consists of walls (1s) and open paths (0s). By providing custom row and column values, the source and destination cells can be adjusted. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 0, 1, 0, 0], ... [1, 0, 0, 1, 0]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[0, 1, 1, 1, 1], [0, 0, 0, 0, 1], [1, 1, 1, 0, 1], [1, 1, 1, 0, 0], [1, 1, 1, 1, 0]] Note: In the output maze, the zeros (0s) represent one of the possible paths from the source to the destination. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0]] >>> maze = [[0, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[0, 0, 0], [1, 1, 0], [1, 1, 0]] >>> maze = [[1, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze,0,1,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[1, 0, 0], [1, 1, 0], [1, 1, 0]] >>> maze = [[1, 1, 0, 0, 1, 0, 0, 1], ... [1, 0, 1, 0, 0, 1, 1, 1], ... [0, 1, 0, 1, 0, 0, 1, 0], ... [1, 1, 1, 0, 0, 1, 0, 1], ... [0, 1, 0, 0, 1, 0, 1, 1], ... [0, 0, 0, 1, 1, 1, 0, 1], ... [0, 1, 0, 1, 0, 1, 1, 1], ... [1, 1, 0, 0, 0, 0, 0, 1]] >>> solve_maze(maze,0,2,len(maze)-1,2) # doctest: +NORMALIZE_WHITESPACE [[1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1]] >>> maze = [[1, 0, 0], ... [0, 1, 1], ... [1, 0, 1]] >>> solve_maze(maze,0,1,len(maze)-1,len(maze)-1) Traceback (most recent call last): ... ValueError: No solution exists! >>> maze = [[0, 0], ... [1, 1]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) Traceback (most recent call last): ... ValueError: No solution exists! >>> maze = [[0, 1], ... [1, 0]] >>> solve_maze(maze,2,0,len(maze)-1,len(maze)-1) Traceback (most recent call last): ... ValueError: Invalid source or destination coordinates >>> maze = [[1, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze,0,1,len(maze),len(maze)-1) Traceback (most recent call last): ... ValueError: Invalid source or destination coordinates """ size = len(maze) # Check if source and destination coordinates are Invalid. if not (0 <= source_row <= size - 1 and 0 <= source_column <= size - 1) or ( not (0 <= destination_row <= size - 1 and 0 <= destination_column <= size - 1) ): raise ValueError("Invalid source or destination coordinates") # We need to create solution object to save path. solutions = [[1 for _ in range(size)] for _ in range(size)] solved = run_maze( maze, source_row, source_column, destination_row, destination_column, solutions ) if solved: return solutions else: raise ValueError("No solution exists!") def run_maze( maze: list[list[int]], i: int, j: int, destination_row: int, destination_column: int, solutions: list[list[int]], ) -> bool: """ This method is recursive starting from (i, j) and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters maze: A two dimensional matrix of zeros and ones. i, j : coordinates of matrix solutions: A two dimensional matrix of solutions. Returns: Boolean if path is found True, Otherwise False. """ size = len(maze) # Final check point. if i == destination_row and j == destination_column and maze[i][j] == 0: solutions[i][j] = 0 return True lower_flag = (not i < 0) and (not j < 0) # Check lower bounds upper_flag = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. block_flag = (solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited solutions[i][j] = 0 # check for directions if ( run_maze(maze, i + 1, j, destination_row, destination_column, solutions) or run_maze( maze, i, j + 1, destination_row, destination_column, solutions ) or run_maze( maze, i - 1, j, destination_row, destination_column, solutions ) or run_maze( maze, i, j - 1, destination_row, destination_column, solutions ) ): return True solutions[i][j] = 1 return False return False if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
from __future__ import annotations def solve_maze( maze: list[list[int]], source_row: int, source_column: int, destination_row: int, destination_column: int, ) -> list[list[int]]: """ This method solves the "rat in maze" problem. Parameters : - maze: A two dimensional matrix of zeros and ones. - source_row: The row index of the starting point. - source_column: The column index of the starting point. - destination_row: The row index of the destination point. - destination_column: The column index of the destination point. Returns: - solution: A 2D matrix representing the solution path if it exists. Raises: - ValueError: If no solution exists or if the source or destination coordinates are invalid. Description: This method navigates through a maze represented as an n by n matrix, starting from a specified source cell and aiming to reach a destination cell. The maze consists of walls (1s) and open paths (0s). By providing custom row and column values, the source and destination cells can be adjusted. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 0, 1, 0, 0], ... [1, 0, 0, 1, 0]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[0, 1, 1, 1, 1], [0, 0, 0, 0, 1], [1, 1, 1, 0, 1], [1, 1, 1, 0, 0], [1, 1, 1, 1, 0]] Note: In the output maze, the zeros (0s) represent one of the possible paths from the source to the destination. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0]] >>> maze = [[0, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[0, 0, 0], [1, 1, 0], [1, 1, 0]] >>> maze = [[1, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze,0,1,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE [[1, 0, 0], [1, 1, 0], [1, 1, 0]] >>> maze = [[1, 1, 0, 0, 1, 0, 0, 1], ... [1, 0, 1, 0, 0, 1, 1, 1], ... [0, 1, 0, 1, 0, 0, 1, 0], ... [1, 1, 1, 0, 0, 1, 0, 1], ... [0, 1, 0, 0, 1, 0, 1, 1], ... [0, 0, 0, 1, 1, 1, 0, 1], ... [0, 1, 0, 1, 0, 1, 1, 1], ... [1, 1, 0, 0, 0, 0, 0, 1]] >>> solve_maze(maze,0,2,len(maze)-1,2) # doctest: +NORMALIZE_WHITESPACE [[1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 0, 0, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 1]] >>> maze = [[1, 0, 0], ... [0, 1, 1], ... [1, 0, 1]] >>> solve_maze(maze,0,1,len(maze)-1,len(maze)-1) Traceback (most recent call last): ... ValueError: No solution exists! >>> maze = [[0, 0], ... [1, 1]] >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) Traceback (most recent call last): ... ValueError: No solution exists! >>> maze = [[0, 1], ... [1, 0]] >>> solve_maze(maze,2,0,len(maze)-1,len(maze)-1) Traceback (most recent call last): ... ValueError: Invalid source or destination coordinates >>> maze = [[1, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze,0,1,len(maze),len(maze)-1) Traceback (most recent call last): ... ValueError: Invalid source or destination coordinates """ size = len(maze) # Check if source and destination coordinates are Invalid. if not (0 <= source_row <= size - 1 and 0 <= source_column <= size - 1) or ( not (0 <= destination_row <= size - 1 and 0 <= destination_column <= size - 1) ): raise ValueError("Invalid source or destination coordinates") # We need to create solution object to save path. solutions = [[1 for _ in range(size)] for _ in range(size)] solved = run_maze( maze, source_row, source_column, destination_row, destination_column, solutions ) if solved: return solutions else: raise ValueError("No solution exists!") def run_maze( maze: list[list[int]], i: int, j: int, destination_row: int, destination_column: int, solutions: list[list[int]], ) -> bool: """ This method is recursive starting from (i, j) and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters maze: A two dimensional matrix of zeros and ones. i, j : coordinates of matrix solutions: A two dimensional matrix of solutions. Returns: Boolean if path is found True, Otherwise False. """ size = len(maze) # Final check point. if i == destination_row and j == destination_column and maze[i][j] == 0: solutions[i][j] = 0 return True lower_flag = (not i < 0) and (not j < 0) # Check lower bounds upper_flag = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. block_flag = (solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited solutions[i][j] = 0 # check for directions if ( run_maze(maze, i + 1, j, destination_row, destination_column, solutions) or run_maze( maze, i, j + 1, destination_row, destination_column, solutions ) or run_maze( maze, i - 1, j, destination_row, destination_column, solutions ) or run_maze( maze, i, j - 1, destination_row, destination_column, solutions ) ): return True solutions[i][j] = 1 return False return False if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
#!/bin/sh # # An example hook script to verify what is about to be committed # by applypatch from an e-mail message. # # The hook should exit with non-zero status after issuing an # appropriate message if it wants to stop the commit. # # To enable this hook, rename this file to "pre-applypatch". . git-sh-setup precommit="$(git rev-parse --git-path hooks/pre-commit)" test -x "$precommit" && exec "$precommit" ${1+"$@"} :
#!/bin/sh # # An example hook script to verify what is about to be committed # by applypatch from an e-mail message. # # The hook should exit with non-zero status after issuing an # appropriate message if it wants to stop the commit. # # To enable this hook, rename this file to "pre-applypatch". . git-sh-setup precommit="$(git rev-parse --git-path hooks/pre-commit)" test -x "$precommit" && exec "$precommit" ${1+"$@"} :
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" This script implements the Dijkstra algorithm on a binary grid. The grid consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. Diagonal movement can be allowed or disallowed. """ from heapq import heappop, heappush import numpy as np def dijkstra( grid: np.ndarray, source: tuple[int, int], destination: tuple[int, int], allow_diagonal: bool, ) -> tuple[float | int, list[tuple[int, int]]]: """ Implements Dijkstra's algorithm on a binary grid. Args: grid (np.ndarray): A 2D numpy array representing the grid. 1 represents a walkable node and 0 represents an obstacle. source (Tuple[int, int]): A tuple representing the start node. destination (Tuple[int, int]): A tuple representing the destination node. allow_diagonal (bool): A boolean determining whether diagonal movements are allowed. Returns: Tuple[Union[float, int], List[Tuple[int, int]]]: The shortest distance from the start node to the destination node and the shortest path as a list of nodes. >>> dijkstra(np.array([[1, 1, 1], [0, 1, 0], [0, 1, 1]]), (0, 0), (2, 2), False) (4.0, [(0, 0), (0, 1), (1, 1), (2, 1), (2, 2)]) >>> dijkstra(np.array([[1, 1, 1], [0, 1, 0], [0, 1, 1]]), (0, 0), (2, 2), True) (2.0, [(0, 0), (1, 1), (2, 2)]) >>> dijkstra(np.array([[1, 1, 1], [0, 0, 1], [0, 1, 1]]), (0, 0), (2, 2), False) (4.0, [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]) """ rows, cols = grid.shape dx = [-1, 1, 0, 0] dy = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] queue, visited = [(0, source)], set() matrix = np.full((rows, cols), np.inf) matrix[source] = 0 predecessors = np.empty((rows, cols), dtype=object) predecessors[source] = None while queue: (dist, (x, y)) = heappop(queue) if (x, y) in visited: continue visited.add((x, y)) if (x, y) == destination: path = [] while (x, y) != source: path.append((x, y)) x, y = predecessors[x, y] path.append(source) # add the source manually path.reverse() return matrix[destination], path for i in range(len(dx)): nx, ny = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: next_node = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(queue, (dist + 1, (nx, ny))) matrix[nx, ny] = dist + 1 predecessors[nx, ny] = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
""" This script implements the Dijkstra algorithm on a binary grid. The grid consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. Diagonal movement can be allowed or disallowed. """ from heapq import heappop, heappush import numpy as np def dijkstra( grid: np.ndarray, source: tuple[int, int], destination: tuple[int, int], allow_diagonal: bool, ) -> tuple[float | int, list[tuple[int, int]]]: """ Implements Dijkstra's algorithm on a binary grid. Args: grid (np.ndarray): A 2D numpy array representing the grid. 1 represents a walkable node and 0 represents an obstacle. source (Tuple[int, int]): A tuple representing the start node. destination (Tuple[int, int]): A tuple representing the destination node. allow_diagonal (bool): A boolean determining whether diagonal movements are allowed. Returns: Tuple[Union[float, int], List[Tuple[int, int]]]: The shortest distance from the start node to the destination node and the shortest path as a list of nodes. >>> dijkstra(np.array([[1, 1, 1], [0, 1, 0], [0, 1, 1]]), (0, 0), (2, 2), False) (4.0, [(0, 0), (0, 1), (1, 1), (2, 1), (2, 2)]) >>> dijkstra(np.array([[1, 1, 1], [0, 1, 0], [0, 1, 1]]), (0, 0), (2, 2), True) (2.0, [(0, 0), (1, 1), (2, 2)]) >>> dijkstra(np.array([[1, 1, 1], [0, 0, 1], [0, 1, 1]]), (0, 0), (2, 2), False) (4.0, [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]) """ rows, cols = grid.shape dx = [-1, 1, 0, 0] dy = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] queue, visited = [(0, source)], set() matrix = np.full((rows, cols), np.inf) matrix[source] = 0 predecessors = np.empty((rows, cols), dtype=object) predecessors[source] = None while queue: (dist, (x, y)) = heappop(queue) if (x, y) in visited: continue visited.add((x, y)) if (x, y) == destination: path = [] while (x, y) != source: path.append((x, y)) x, y = predecessors[x, y] path.append(source) # add the source manually path.reverse() return matrix[destination], path for i in range(len(dx)): nx, ny = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: next_node = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(queue, (dist + 1, (nx, ny))) matrix[nx, ny] = dist + 1 predecessors[nx, ny] = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
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()
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
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Conversion of pressure units. Available Units:- Pascal,Bar,Kilopascal,Megapascal,psi(pound per square inch), inHg(in mercury column),torr,atm USAGE : -> Import this file into their respective project. -> Use the function pressure_conversion() for conversion of pressure units. -> Parameters : -> value : The number of from units you want to convert -> from_type : From which type you want to convert -> to_type : To which type you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Pascal_(unit) -> Wikipedia reference: https://en.wikipedia.org/wiki/Pound_per_square_inch -> Wikipedia reference: https://en.wikipedia.org/wiki/Inch_of_mercury -> Wikipedia reference: https://en.wikipedia.org/wiki/Torr -> https://en.wikipedia.org/wiki/Standard_atmosphere_(unit) -> https://msestudent.com/what-are-the-units-of-pressure/ -> https://www.unitconverters.net/pressure-converter.html """ from typing import NamedTuple class FromTo(NamedTuple): from_factor: float to_factor: float PRESSURE_CONVERSION = { "atm": FromTo(1, 1), "pascal": FromTo(0.0000098, 101325), "bar": FromTo(0.986923, 1.01325), "kilopascal": FromTo(0.00986923, 101.325), "megapascal": FromTo(9.86923, 0.101325), "psi": FromTo(0.068046, 14.6959), "inHg": FromTo(0.0334211, 29.9213), "torr": FromTo(0.00131579, 760), } def pressure_conversion(value: float, from_type: str, to_type: str) -> float: """ Conversion between pressure units. >>> pressure_conversion(4, "atm", "pascal") 405300 >>> pressure_conversion(1, "pascal", "psi") 0.00014401981999999998 >>> pressure_conversion(1, "bar", "atm") 0.986923 >>> pressure_conversion(3, "kilopascal", "bar") 0.029999991892499998 >>> pressure_conversion(2, "megapascal", "psi") 290.074434314 >>> pressure_conversion(4, "psi", "torr") 206.85984 >>> pressure_conversion(1, "inHg", "atm") 0.0334211 >>> pressure_conversion(1, "torr", "psi") 0.019336718261000002 >>> pressure_conversion(4, "wrongUnit", "atm") Traceback (most recent call last): ... ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are: atm, pascal, bar, kilopascal, megapascal, psi, inHg, torr """ if from_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) if to_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) return ( value * PRESSURE_CONVERSION[from_type].from_factor * PRESSURE_CONVERSION[to_type].to_factor ) if __name__ == "__main__": import doctest doctest.testmod()
""" Conversion of pressure units. Available Units:- Pascal,Bar,Kilopascal,Megapascal,psi(pound per square inch), inHg(in mercury column),torr,atm USAGE : -> Import this file into their respective project. -> Use the function pressure_conversion() for conversion of pressure units. -> Parameters : -> value : The number of from units you want to convert -> from_type : From which type you want to convert -> to_type : To which type you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Pascal_(unit) -> Wikipedia reference: https://en.wikipedia.org/wiki/Pound_per_square_inch -> Wikipedia reference: https://en.wikipedia.org/wiki/Inch_of_mercury -> Wikipedia reference: https://en.wikipedia.org/wiki/Torr -> https://en.wikipedia.org/wiki/Standard_atmosphere_(unit) -> https://msestudent.com/what-are-the-units-of-pressure/ -> https://www.unitconverters.net/pressure-converter.html """ from typing import NamedTuple class FromTo(NamedTuple): from_factor: float to_factor: float PRESSURE_CONVERSION = { "atm": FromTo(1, 1), "pascal": FromTo(0.0000098, 101325), "bar": FromTo(0.986923, 1.01325), "kilopascal": FromTo(0.00986923, 101.325), "megapascal": FromTo(9.86923, 0.101325), "psi": FromTo(0.068046, 14.6959), "inHg": FromTo(0.0334211, 29.9213), "torr": FromTo(0.00131579, 760), } def pressure_conversion(value: float, from_type: str, to_type: str) -> float: """ Conversion between pressure units. >>> pressure_conversion(4, "atm", "pascal") 405300 >>> pressure_conversion(1, "pascal", "psi") 0.00014401981999999998 >>> pressure_conversion(1, "bar", "atm") 0.986923 >>> pressure_conversion(3, "kilopascal", "bar") 0.029999991892499998 >>> pressure_conversion(2, "megapascal", "psi") 290.074434314 >>> pressure_conversion(4, "psi", "torr") 206.85984 >>> pressure_conversion(1, "inHg", "atm") 0.0334211 >>> pressure_conversion(1, "torr", "psi") 0.019336718261000002 >>> pressure_conversion(4, "wrongUnit", "atm") Traceback (most recent call last): ... ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are: atm, pascal, bar, kilopascal, megapascal, psi, inHg, torr """ if from_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) if to_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) return ( value * PRESSURE_CONVERSION[from_type].from_factor * PRESSURE_CONVERSION[to_type].to_factor ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Python program to show how to interpolate and evaluate a polynomial using Neville's method. Neville’s method evaluates a polynomial that passes through a given set of x and y points for a particular x value (x0) using the Newton polynomial form. Reference: https://rpubs.com/aaronsc32/nevilles-method-polynomial-interpolation """ def neville_interpolate(x_points: list, y_points: list, x0: int) -> list: """ Interpolate and evaluate a polynomial using Neville's method. Arguments: x_points, y_points: Iterables of x and corresponding y points through which the polynomial passes. x0: The value of x to evaluate the polynomial for. Return Value: A list of the approximated value and the Neville iterations table respectively. >>> import pprint >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 5)[0] 10.0 >>> pprint.pprint(neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[1]) [[0, 6, 0, 0, 0], [0, 7, 0, 0, 0], [0, 8, 104.0, 0, 0], [0, 9, 104.0, 104.0, 0], [0, 11, 104.0, 104.0, 104.0]] >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[0] 104.0 >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), '') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'str' and 'int' """ n = len(x_points) q = [[0] * n for i in range(n)] for i in range(n): q[i][1] = y_points[i] for i in range(2, n): for j in range(i, n): q[j][i] = ( (x0 - x_points[j - i + 1]) * q[j][i - 1] - (x0 - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
""" Python program to show how to interpolate and evaluate a polynomial using Neville's method. Neville’s method evaluates a polynomial that passes through a given set of x and y points for a particular x value (x0) using the Newton polynomial form. Reference: https://rpubs.com/aaronsc32/nevilles-method-polynomial-interpolation """ def neville_interpolate(x_points: list, y_points: list, x0: int) -> list: """ Interpolate and evaluate a polynomial using Neville's method. Arguments: x_points, y_points: Iterables of x and corresponding y points through which the polynomial passes. x0: The value of x to evaluate the polynomial for. Return Value: A list of the approximated value and the Neville iterations table respectively. >>> import pprint >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 5)[0] 10.0 >>> pprint.pprint(neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[1]) [[0, 6, 0, 0, 0], [0, 7, 0, 0, 0], [0, 8, 104.0, 0, 0], [0, 9, 104.0, 104.0, 0], [0, 11, 104.0, 104.0, 104.0]] >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[0] 104.0 >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), '') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'str' and 'int' """ n = len(x_points) q = [[0] * n for i in range(n)] for i in range(n): q[i][1] = y_points[i] for i in range(2, n): for j in range(i, n): q[j][i] = ( (x0 - x_points[j - i + 1]) * q[j][i - 1] - (x0 - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" 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
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
def bin_exp_mod(a: int, n: int, b: int) -> int: """ >>> bin_exp_mod(3, 4, 5) 1 >>> bin_exp_mod(7, 13, 10) 7 """ # mod b assert b != 0, "This cannot accept modulo that is == 0" if n == 0: return 1 if n % 2 == 1: return (bin_exp_mod(a, n - 1, b) * a) % b r = bin_exp_mod(a, n // 2, b) return (r * r) % b if __name__ == "__main__": try: BASE = int(input("Enter Base : ").strip()) POWER = int(input("Enter Power : ").strip()) MODULO = int(input("Enter Modulo : ").strip()) except ValueError: print("Invalid literal for integer") print(bin_exp_mod(BASE, POWER, MODULO))
def bin_exp_mod(a: int, n: int, b: int) -> int: """ >>> bin_exp_mod(3, 4, 5) 1 >>> bin_exp_mod(7, 13, 10) 7 """ # mod b assert b != 0, "This cannot accept modulo that is == 0" if n == 0: return 1 if n % 2 == 1: return (bin_exp_mod(a, n - 1, b) * a) % b r = bin_exp_mod(a, n // 2, b) return (r * r) % b if __name__ == "__main__": try: BASE = int(input("Enter Base : ").strip()) POWER = int(input("Enter Power : ").strip()) MODULO = int(input("Enter Modulo : ").strip()) except ValueError: print("Invalid literal for integer") print(bin_exp_mod(BASE, POWER, MODULO))
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
"""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: msg = ( f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(msg) 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: msg = ( f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(msg) 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
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Hey, we are going to find an exciting number called Catalan number which is use to find the number of possible binary search trees from tree of a given number of nodes. We will use the formula: t(n) = SUMMATION(i = 1 to n)t(i-1)t(n-i) Further details at Wikipedia: https://en.wikipedia.org/wiki/Catalan_number """ """ Our Contribution: Basically we Create the 2 function: 1. catalan_number(node_count: int) -> int Returns the number of possible binary search trees for n nodes. 2. binary_tree_count(node_count: int) -> int Returns the number of possible binary trees for n nodes. """ def binomial_coefficient(n: int, k: int) -> int: """ Since Here we Find the Binomial Coefficient: https://en.wikipedia.org/wiki/Binomial_coefficient C(n,k) = n! / k!(n-k)! :param n: 2 times of Number of nodes :param k: Number of nodes :return: Integer Value >>> binomial_coefficient(4, 2) 6 """ result = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): k = n - k # Calculate C(n,k) for i in range(k): result *= n - i result //= i + 1 return result def catalan_number(node_count: int) -> int: """ We can find Catalan number many ways but here we use Binomial Coefficient because it does the job in O(n) return the Catalan number of n using 2nCn/(n+1). :param n: number of nodes :return: Catalan number of n nodes >>> catalan_number(5) 42 >>> catalan_number(6) 132 """ return binomial_coefficient(2 * node_count, node_count) // (node_count + 1) def factorial(n: int) -> int: """ Return the factorial of a number. :param n: Number to find the Factorial of. :return: Factorial of n. >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(10)) True >>> factorial(-5) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: factorial() not defined for negative values """ if n < 0: raise ValueError("factorial() not defined for negative values") result = 1 for i in range(1, n + 1): result *= i return result def binary_tree_count(node_count: int) -> int: """ Return the number of possible of binary trees. :param n: number of nodes :return: Number of possible binary trees >>> binary_tree_count(5) 5040 >>> binary_tree_count(6) 95040 """ return catalan_number(node_count) * factorial(node_count) if __name__ == "__main__": node_count = int(input("Enter the number of nodes: ").strip() or 0) if node_count <= 0: raise ValueError("We need some nodes to work with.") print( f"Given {node_count} nodes, there are {binary_tree_count(node_count)} " f"binary trees and {catalan_number(node_count)} binary search trees." )
""" Hey, we are going to find an exciting number called Catalan number which is use to find the number of possible binary search trees from tree of a given number of nodes. We will use the formula: t(n) = SUMMATION(i = 1 to n)t(i-1)t(n-i) Further details at Wikipedia: https://en.wikipedia.org/wiki/Catalan_number """ """ Our Contribution: Basically we Create the 2 function: 1. catalan_number(node_count: int) -> int Returns the number of possible binary search trees for n nodes. 2. binary_tree_count(node_count: int) -> int Returns the number of possible binary trees for n nodes. """ def binomial_coefficient(n: int, k: int) -> int: """ Since Here we Find the Binomial Coefficient: https://en.wikipedia.org/wiki/Binomial_coefficient C(n,k) = n! / k!(n-k)! :param n: 2 times of Number of nodes :param k: Number of nodes :return: Integer Value >>> binomial_coefficient(4, 2) 6 """ result = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): k = n - k # Calculate C(n,k) for i in range(k): result *= n - i result //= i + 1 return result def catalan_number(node_count: int) -> int: """ We can find Catalan number many ways but here we use Binomial Coefficient because it does the job in O(n) return the Catalan number of n using 2nCn/(n+1). :param n: number of nodes :return: Catalan number of n nodes >>> catalan_number(5) 42 >>> catalan_number(6) 132 """ return binomial_coefficient(2 * node_count, node_count) // (node_count + 1) def factorial(n: int) -> int: """ Return the factorial of a number. :param n: Number to find the Factorial of. :return: Factorial of n. >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(10)) True >>> factorial(-5) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: factorial() not defined for negative values """ if n < 0: raise ValueError("factorial() not defined for negative values") result = 1 for i in range(1, n + 1): result *= i return result def binary_tree_count(node_count: int) -> int: """ Return the number of possible of binary trees. :param n: number of nodes :return: Number of possible binary trees >>> binary_tree_count(5) 5040 >>> binary_tree_count(6) 95040 """ return catalan_number(node_count) * factorial(node_count) if __name__ == "__main__": node_count = int(input("Enter the number of nodes: ").strip() or 0) if node_count <= 0: raise ValueError("We need some nodes to work with.") print( f"Given {node_count} nodes, there are {binary_tree_count(node_count)} " f"binary trees and {catalan_number(node_count)} binary search trees." )
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" An AND Gate is a logic gate in boolean algebra which results to 1 (True) if both the inputs are 1, and 0 (False) otherwise. Following is the truth table of an AND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 0 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 1 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def and_gate(input_1: int, input_2: int) -> int: """ Calculate AND of the input values >>> and_gate(0, 0) 0 >>> and_gate(0, 1) 0 >>> and_gate(1, 0) 0 >>> and_gate(1, 1) 1 """ return int((input_1, input_2).count(0) == 0) def test_and_gate() -> None: """ Tests the and_gate function """ assert and_gate(0, 0) == 0 assert and_gate(0, 1) == 0 assert and_gate(1, 0) == 0 assert and_gate(1, 1) == 1 if __name__ == "__main__": test_and_gate() print(and_gate(1, 0)) print(and_gate(0, 0)) print(and_gate(0, 1)) print(and_gate(1, 1))
""" An AND Gate is a logic gate in boolean algebra which results to 1 (True) if both the inputs are 1, and 0 (False) otherwise. Following is the truth table of an AND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 0 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 1 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def and_gate(input_1: int, input_2: int) -> int: """ Calculate AND of the input values >>> and_gate(0, 0) 0 >>> and_gate(0, 1) 0 >>> and_gate(1, 0) 0 >>> and_gate(1, 1) 1 """ return int((input_1, input_2).count(0) == 0) def test_and_gate() -> None: """ Tests the and_gate function """ assert and_gate(0, 0) == 0 assert and_gate(0, 1) == 0 assert and_gate(1, 0) == 0 assert and_gate(1, 1) == 1 if __name__ == "__main__": test_and_gate() print(and_gate(1, 0)) print(and_gate(0, 0)) print(and_gate(0, 1)) print(and_gate(1, 1))
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
def dencrypt(s: str, n: int = 13) -> str: """ https://en.wikipedia.org/wiki/ROT13 >>> msg = "My secret bank account number is 173-52946 so don't tell anyone!!" >>> s = dencrypt(msg) >>> s "Zl frperg onax nppbhag ahzore vf 173-52946 fb qba'g gryy nalbar!!" >>> dencrypt(s) == msg True """ out = "" for c in s: if "A" <= c <= "Z": out += chr(ord("A") + (ord(c) - ord("A") + n) % 26) elif "a" <= c <= "z": out += chr(ord("a") + (ord(c) - ord("a") + n) % 26) else: out += c return out def main() -> None: s0 = input("Enter message: ") s1 = dencrypt(s0, 13) print("Encryption:", s1) s2 = dencrypt(s1, 13) print("Decryption: ", s2) if __name__ == "__main__": import doctest doctest.testmod() main()
def dencrypt(s: str, n: int = 13) -> str: """ https://en.wikipedia.org/wiki/ROT13 >>> msg = "My secret bank account number is 173-52946 so don't tell anyone!!" >>> s = dencrypt(msg) >>> s "Zl frperg onax nppbhag ahzore vf 173-52946 fb qba'g gryy nalbar!!" >>> dencrypt(s) == msg True """ out = "" for c in s: if "A" <= c <= "Z": out += chr(ord("A") + (ord(c) - ord("A") + n) % 26) elif "a" <= c <= "z": out += chr(ord("a") + (ord(c) - ord("a") + n) % 26) else: out += c return out def main() -> None: s0 = input("Enter message: ") s1 = dencrypt(s0, 13) print("Encryption:", s1) s2 = dencrypt(s1, 13) print("Decryption: ", s2) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
def kruskal( num_nodes: int, edges: list[tuple[int, int, int]] ) -> list[tuple[int, int, int]]: """ >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1)]) [(2, 3, 1), (0, 1, 3), (1, 2, 5)] >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2)]) [(2, 3, 1), (0, 2, 1), (0, 1, 3)] >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2), ... (2, 1, 1)]) [(2, 3, 1), (0, 2, 1), (2, 1, 1)] """ edges = sorted(edges, key=lambda edge: edge[2]) parent = list(range(num_nodes)) def find_parent(i): if i != parent[i]: parent[i] = find_parent(parent[i]) return parent[i] minimum_spanning_tree_cost = 0 minimum_spanning_tree = [] for edge in edges: parent_a = find_parent(edge[0]) parent_b = find_parent(edge[1]) if parent_a != parent_b: minimum_spanning_tree_cost += edge[2] minimum_spanning_tree.append(edge) parent[parent_a] = parent_b return minimum_spanning_tree if __name__ == "__main__": # pragma: no cover num_nodes, num_edges = list(map(int, input().strip().split())) edges = [] for _ in range(num_edges): node1, node2, cost = (int(x) for x in input().strip().split()) edges.append((node1, node2, cost)) kruskal(num_nodes, edges)
def kruskal( num_nodes: int, edges: list[tuple[int, int, int]] ) -> list[tuple[int, int, int]]: """ >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1)]) [(2, 3, 1), (0, 1, 3), (1, 2, 5)] >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2)]) [(2, 3, 1), (0, 2, 1), (0, 1, 3)] >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2), ... (2, 1, 1)]) [(2, 3, 1), (0, 2, 1), (2, 1, 1)] """ edges = sorted(edges, key=lambda edge: edge[2]) parent = list(range(num_nodes)) def find_parent(i): if i != parent[i]: parent[i] = find_parent(parent[i]) return parent[i] minimum_spanning_tree_cost = 0 minimum_spanning_tree = [] for edge in edges: parent_a = find_parent(edge[0]) parent_b = find_parent(edge[1]) if parent_a != parent_b: minimum_spanning_tree_cost += edge[2] minimum_spanning_tree.append(edge) parent[parent_a] = parent_b return minimum_spanning_tree if __name__ == "__main__": # pragma: no cover num_nodes, num_edges = list(map(int, input().strip().split())) edges = [] for _ in range(num_edges): node1, node2, cost = (int(x) for x in input().strip().split()) edges.append((node1, node2, cost)) kruskal(num_nodes, edges)
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" This is a Python implementation of the circle sort algorithm For doctests run following command: python3 -m doctest -v circle_sort.py For manual testing run: python3 circle_sort.py """ def circle_sort(collection: list) -> list: """A pure Python implementation of circle sort algorithm :param collection: a mutable collection of comparable items in any order :return: the same collection in ascending order Examples: >>> circle_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> circle_sort([]) [] >>> circle_sort([-2, 5, 0, -45]) [-45, -2, 0, 5] >>> collections = ([], [0, 5, 3, 2, 2], [-2, 5, 0, -45]) >>> all(sorted(collection) == circle_sort(collection) for collection in collections) True """ if len(collection) < 2: return collection def circle_sort_util(collection: list, low: int, high: int) -> bool: """ >>> arr = [5,4,3,2,1] >>> circle_sort_util(lst, 0, 2) True >>> arr [3, 4, 5, 2, 1] """ swapped = False if low == high: return swapped left = low right = high while left < right: if collection[left] > collection[right]: collection[left], collection[right] = ( collection[right], collection[left], ) swapped = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: collection[left], collection[right + 1] = ( collection[right + 1], collection[left], ) swapped = True mid = low + int((high - low) / 2) left_swap = circle_sort_util(collection, low, mid) right_swap = circle_sort_util(collection, mid + 1, high) return swapped or left_swap or right_swap is_not_sorted = True while is_not_sorted is True: is_not_sorted = circle_sort_util(collection, 0, len(collection) - 1) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(circle_sort(unsorted))
""" This is a Python implementation of the circle sort algorithm For doctests run following command: python3 -m doctest -v circle_sort.py For manual testing run: python3 circle_sort.py """ def circle_sort(collection: list) -> list: """A pure Python implementation of circle sort algorithm :param collection: a mutable collection of comparable items in any order :return: the same collection in ascending order Examples: >>> circle_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> circle_sort([]) [] >>> circle_sort([-2, 5, 0, -45]) [-45, -2, 0, 5] >>> collections = ([], [0, 5, 3, 2, 2], [-2, 5, 0, -45]) >>> all(sorted(collection) == circle_sort(collection) for collection in collections) True """ if len(collection) < 2: return collection def circle_sort_util(collection: list, low: int, high: int) -> bool: """ >>> arr = [5,4,3,2,1] >>> circle_sort_util(lst, 0, 2) True >>> arr [3, 4, 5, 2, 1] """ swapped = False if low == high: return swapped left = low right = high while left < right: if collection[left] > collection[right]: collection[left], collection[right] = ( collection[right], collection[left], ) swapped = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: collection[left], collection[right + 1] = ( collection[right + 1], collection[left], ) swapped = True mid = low + int((high - low) / 2) left_swap = circle_sort_util(collection, low, mid) right_swap = circle_sort_util(collection, mid + 1, high) return swapped or left_swap or right_swap is_not_sorted = True while is_not_sorted is True: is_not_sorted = circle_sort_util(collection, 0, len(collection) - 1) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(circle_sort(unsorted))
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Code contributed by Honey Sharma Source: https://en.wikipedia.org/wiki/Cycle_sort """ def cycle_sort(array: list) -> list: """ >>> cycle_sort([4, 3, 2, 1]) [1, 2, 3, 4] >>> cycle_sort([-4, 20, 0, -50, 100, -1]) [-50, -4, -1, 0, 20, 100] >>> cycle_sort([-.1, -.2, 1.3, -.8]) [-0.8, -0.2, -0.1, 1.3] >>> cycle_sort([]) [] """ array_len = len(array) for cycle_start in range(array_len - 1): item = array[cycle_start] pos = cycle_start for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 if pos == cycle_start: continue while item == array[pos]: pos += 1 array[pos], item = item, array[pos] while pos != cycle_start: pos = cycle_start for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 while item == array[pos]: pos += 1 array[pos], item = item, array[pos] return array if __name__ == "__main__": assert cycle_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert cycle_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
""" Code contributed by Honey Sharma Source: https://en.wikipedia.org/wiki/Cycle_sort """ def cycle_sort(array: list) -> list: """ >>> cycle_sort([4, 3, 2, 1]) [1, 2, 3, 4] >>> cycle_sort([-4, 20, 0, -50, 100, -1]) [-50, -4, -1, 0, 20, 100] >>> cycle_sort([-.1, -.2, 1.3, -.8]) [-0.8, -0.2, -0.1, 1.3] >>> cycle_sort([]) [] """ array_len = len(array) for cycle_start in range(array_len - 1): item = array[cycle_start] pos = cycle_start for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 if pos == cycle_start: continue while item == array[pos]: pos += 1 array[pos], item = item, array[pos] while pos != cycle_start: pos = cycle_start for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 while item == array[pos]: pos += 1 array[pos], item = item, array[pos] return array if __name__ == "__main__": assert cycle_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert cycle_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Implementing Deque using DoublyLinkedList ... Operations: 1. insertion in the front -> O(1) 2. insertion in the end -> O(1) 3. remove from the front -> O(1) 4. remove from the end -> O(1) """ class _DoublyLinkedBase: """A Private class (to be inherited)""" class _Node: __slots__ = "_prev", "_data", "_next" def __init__(self, link_p, element, link_n): self._prev = link_p self._data = element self._next = link_n def has_next_and_prev(self): return ( f" Prev -> {self._prev is not None}, Next -> {self._next is not None}" ) def __init__(self): self._header = self._Node(None, None, None) self._trailer = self._Node(None, None, None) self._header._next = self._trailer self._trailer._prev = self._header self._size = 0 def __len__(self): return self._size def is_empty(self): return self.__len__() == 0 def _insert(self, predecessor, e, successor): # Create new_node by setting it's prev.link -> header # setting it's next.link -> trailer new_node = self._Node(predecessor, e, successor) predecessor._next = new_node successor._prev = new_node self._size += 1 return self def _delete(self, node): predecessor = node._prev successor = node._next predecessor._next = successor successor._prev = predecessor self._size -= 1 temp = node._data node._prev = node._next = node._data = None del node return temp class LinkedDeque(_DoublyLinkedBase): def first(self): """return first element >>> d = LinkedDeque() >>> d.add_first('A').first() 'A' >>> d.add_first('B').first() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._header._next._data def last(self): """return last element >>> d = LinkedDeque() >>> d.add_last('A').last() 'A' >>> d.add_last('B').last() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._trailer._prev._data # DEque Insert Operations (At the front, At the end) def add_first(self, element): """insertion in the front >>> LinkedDeque().add_first('AV').first() 'AV' """ return self._insert(self._header, element, self._header._next) def add_last(self, element): """insertion in the end >>> LinkedDeque().add_last('B').last() 'B' """ return self._insert(self._trailer._prev, element, self._trailer) # DEqueu Remove Operations (At the front, At the end) def remove_first(self): """removal from the front >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_first() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_first() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._header._next) def remove_last(self): """removal in the end >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_last() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_last() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._trailer._prev)
""" Implementing Deque using DoublyLinkedList ... Operations: 1. insertion in the front -> O(1) 2. insertion in the end -> O(1) 3. remove from the front -> O(1) 4. remove from the end -> O(1) """ class _DoublyLinkedBase: """A Private class (to be inherited)""" class _Node: __slots__ = "_prev", "_data", "_next" def __init__(self, link_p, element, link_n): self._prev = link_p self._data = element self._next = link_n def has_next_and_prev(self): return ( f" Prev -> {self._prev is not None}, Next -> {self._next is not None}" ) def __init__(self): self._header = self._Node(None, None, None) self._trailer = self._Node(None, None, None) self._header._next = self._trailer self._trailer._prev = self._header self._size = 0 def __len__(self): return self._size def is_empty(self): return self.__len__() == 0 def _insert(self, predecessor, e, successor): # Create new_node by setting it's prev.link -> header # setting it's next.link -> trailer new_node = self._Node(predecessor, e, successor) predecessor._next = new_node successor._prev = new_node self._size += 1 return self def _delete(self, node): predecessor = node._prev successor = node._next predecessor._next = successor successor._prev = predecessor self._size -= 1 temp = node._data node._prev = node._next = node._data = None del node return temp class LinkedDeque(_DoublyLinkedBase): def first(self): """return first element >>> d = LinkedDeque() >>> d.add_first('A').first() 'A' >>> d.add_first('B').first() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._header._next._data def last(self): """return last element >>> d = LinkedDeque() >>> d.add_last('A').last() 'A' >>> d.add_last('B').last() 'B' """ if self.is_empty(): raise Exception("List is empty") return self._trailer._prev._data # DEque Insert Operations (At the front, At the end) def add_first(self, element): """insertion in the front >>> LinkedDeque().add_first('AV').first() 'AV' """ return self._insert(self._header, element, self._header._next) def add_last(self, element): """insertion in the end >>> LinkedDeque().add_last('B').last() 'B' """ return self._insert(self._trailer._prev, element, self._trailer) # DEqueu Remove Operations (At the front, At the end) def remove_first(self): """removal from the front >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_first() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_first() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._header._next) def remove_last(self): """removal in the end >>> d = LinkedDeque() >>> d.is_empty() True >>> d.remove_last() Traceback (most recent call last): ... IndexError: remove_first from empty list >>> d.add_first('A') # doctest: +ELLIPSIS <data_structures.linked_list.deque_doubly.LinkedDeque object at ... >>> d.remove_last() 'A' >>> d.is_empty() True """ if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._trailer._prev)
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
"""Convert a positive Decimal Number to Any Other Representation""" from string import ascii_uppercase ALPHABET_VALUES = {str(ord(c) - 55): c for c in ascii_uppercase} def decimal_to_any(num: int, base: int) -> str: """ Convert a positive integer to another base as str. >>> decimal_to_any(0, 2) '0' >>> decimal_to_any(5, 4) '11' >>> decimal_to_any(20, 3) '202' >>> decimal_to_any(58, 16) '3A' >>> decimal_to_any(243, 17) 'E5' >>> decimal_to_any(34923, 36) 'QY3' >>> decimal_to_any(10, 11) 'A' >>> decimal_to_any(16, 16) '10' >>> decimal_to_any(36, 36) '10' >>> # negatives will error >>> decimal_to_any(-45, 8) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: parameter must be positive int >>> # floats will error >>> decimal_to_any(34.4, 6) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: int() can't convert non-string with explicit base >>> # a float base will error >>> decimal_to_any(5, 2.5) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # a str base will error >>> decimal_to_any(10, '16') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer >>> # a base less than 2 will error >>> decimal_to_any(7, 0) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be >= 2 >>> # a base greater than 36 will error >>> decimal_to_any(34, 37) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be <= 36 """ if isinstance(num, float): raise TypeError("int() can't convert non-string with explicit base") if num < 0: raise ValueError("parameter must be positive int") if isinstance(base, str): raise TypeError("'str' object cannot be interpreted as an integer") if isinstance(base, float): raise TypeError("'float' object cannot be interpreted as an integer") if base in (0, 1): raise ValueError("base must be >= 2") if base > 36: raise ValueError("base must be <= 36") new_value = "" mod = 0 div = 0 while div != 1: div, mod = divmod(num, base) if base >= 11 and 9 < mod < 36: actual_value = ALPHABET_VALUES[str(mod)] else: actual_value = str(mod) new_value += actual_value div = num // base num = div if div == 0: return str(new_value[::-1]) elif div == 1: new_value += str(div) return str(new_value[::-1]) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
"""Convert a positive Decimal Number to Any Other Representation""" from string import ascii_uppercase ALPHABET_VALUES = {str(ord(c) - 55): c for c in ascii_uppercase} def decimal_to_any(num: int, base: int) -> str: """ Convert a positive integer to another base as str. >>> decimal_to_any(0, 2) '0' >>> decimal_to_any(5, 4) '11' >>> decimal_to_any(20, 3) '202' >>> decimal_to_any(58, 16) '3A' >>> decimal_to_any(243, 17) 'E5' >>> decimal_to_any(34923, 36) 'QY3' >>> decimal_to_any(10, 11) 'A' >>> decimal_to_any(16, 16) '10' >>> decimal_to_any(36, 36) '10' >>> # negatives will error >>> decimal_to_any(-45, 8) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: parameter must be positive int >>> # floats will error >>> decimal_to_any(34.4, 6) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: int() can't convert non-string with explicit base >>> # a float base will error >>> decimal_to_any(5, 2.5) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # a str base will error >>> decimal_to_any(10, '16') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer >>> # a base less than 2 will error >>> decimal_to_any(7, 0) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be >= 2 >>> # a base greater than 36 will error >>> decimal_to_any(34, 37) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be <= 36 """ if isinstance(num, float): raise TypeError("int() can't convert non-string with explicit base") if num < 0: raise ValueError("parameter must be positive int") if isinstance(base, str): raise TypeError("'str' object cannot be interpreted as an integer") if isinstance(base, float): raise TypeError("'float' object cannot be interpreted as an integer") if base in (0, 1): raise ValueError("base must be >= 2") if base > 36: raise ValueError("base must be <= 36") new_value = "" mod = 0 div = 0 while div != 1: div, mod = divmod(num, base) if base >= 11 and 9 < mod < 36: actual_value = ALPHABET_VALUES[str(mod)] else: actual_value = str(mod) new_value += actual_value div = num // base num = div if div == 0: return str(new_value[::-1]) elif div == 1: new_value += str(div) return str(new_value[::-1]) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" The algorithm finds distance between closest pair of points in the given n points. Approach used -> Divide and conquer The points are sorted based on Xco-ords and then based on Yco-ords separately. And by applying divide and conquer approach, minimum distance is obtained recursively. >> Closest points can lie on different sides of partition. This case handled by forming a strip of points whose Xco-ords distance is less than closest_pair_dis from mid-point's Xco-ords. Points sorted based on Yco-ords are used in this step to reduce sorting time. Closest pair distance is found in the strip of points. (closest_in_strip) min(closest_pair_dis, closest_in_strip) would be the final answer. Time complexity: O(n * log n) """ def euclidean_distance_sqr(point1, point2): """ >>> euclidean_distance_sqr([1,2],[2,4]) 5 """ return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 def column_based_sort(array, column=0): """ >>> column_based_sort([(5, 1), (4, 2), (3, 0)], 1) [(3, 0), (5, 1), (4, 2)] """ return sorted(array, key=lambda x: x[column]) def dis_between_closest_pair(points, points_counts, min_dis=float("inf")): """ brute force approach to find distance between closest pair points Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance between closest pair of points >>> dis_between_closest_pair([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 5 """ for i in range(points_counts - 1): for j in range(i + 1, points_counts): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")): """ closest pair of points in strip Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance btw closest pair of points in the strip (< min_dis) >>> dis_between_closest_in_strip([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 85 """ for i in range(min(6, points_counts - 1), points_counts): for j in range(max(0, i - 6), i): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts): """divide and conquer approach Parameters : points, points_count (list(tuple(int, int)), int) Returns : (float): distance btw closest pair of points >>> closest_pair_of_points_sqr([(1, 2), (3, 4)], [(5, 6), (7, 8)], 2) 8 """ # base case if points_counts <= 3: return dis_between_closest_pair(points_sorted_on_x, points_counts) # recursion mid = points_counts // 2 closest_in_left = closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y[:mid], mid ) closest_in_right = closest_pair_of_points_sqr( points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid ) closest_pair_dis = min(closest_in_left, closest_in_right) """ cross_strip contains the points, whose Xcoords are at a distance(< closest_pair_dis) from mid's Xcoord """ cross_strip = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis: cross_strip.append(point) closest_in_strip = dis_between_closest_in_strip( cross_strip, len(cross_strip), closest_pair_dis ) return min(closest_pair_dis, closest_in_strip) def closest_pair_of_points(points, points_counts): """ >>> closest_pair_of_points([(2, 3), (12, 30)], len([(2, 3), (12, 30)])) 28.792360097775937 """ points_sorted_on_x = column_based_sort(points, column=0) points_sorted_on_y = column_based_sort(points, column=1) return ( closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y, points_counts ) ) ** 0.5 if __name__ == "__main__": points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
""" The algorithm finds distance between closest pair of points in the given n points. Approach used -> Divide and conquer The points are sorted based on Xco-ords and then based on Yco-ords separately. And by applying divide and conquer approach, minimum distance is obtained recursively. >> Closest points can lie on different sides of partition. This case handled by forming a strip of points whose Xco-ords distance is less than closest_pair_dis from mid-point's Xco-ords. Points sorted based on Yco-ords are used in this step to reduce sorting time. Closest pair distance is found in the strip of points. (closest_in_strip) min(closest_pair_dis, closest_in_strip) would be the final answer. Time complexity: O(n * log n) """ def euclidean_distance_sqr(point1, point2): """ >>> euclidean_distance_sqr([1,2],[2,4]) 5 """ return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 def column_based_sort(array, column=0): """ >>> column_based_sort([(5, 1), (4, 2), (3, 0)], 1) [(3, 0), (5, 1), (4, 2)] """ return sorted(array, key=lambda x: x[column]) def dis_between_closest_pair(points, points_counts, min_dis=float("inf")): """ brute force approach to find distance between closest pair points Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance between closest pair of points >>> dis_between_closest_pair([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 5 """ for i in range(points_counts - 1): for j in range(i + 1, points_counts): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")): """ closest pair of points in strip Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance btw closest pair of points in the strip (< min_dis) >>> dis_between_closest_in_strip([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 85 """ for i in range(min(6, points_counts - 1), points_counts): for j in range(max(0, i - 6), i): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts): """divide and conquer approach Parameters : points, points_count (list(tuple(int, int)), int) Returns : (float): distance btw closest pair of points >>> closest_pair_of_points_sqr([(1, 2), (3, 4)], [(5, 6), (7, 8)], 2) 8 """ # base case if points_counts <= 3: return dis_between_closest_pair(points_sorted_on_x, points_counts) # recursion mid = points_counts // 2 closest_in_left = closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y[:mid], mid ) closest_in_right = closest_pair_of_points_sqr( points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid ) closest_pair_dis = min(closest_in_left, closest_in_right) """ cross_strip contains the points, whose Xcoords are at a distance(< closest_pair_dis) from mid's Xcoord """ cross_strip = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis: cross_strip.append(point) closest_in_strip = dis_between_closest_in_strip( cross_strip, len(cross_strip), closest_pair_dis ) return min(closest_pair_dis, closest_in_strip) def closest_pair_of_points(points, points_counts): """ >>> closest_pair_of_points([(2, 3), (12, 30)], len([(2, 3), (12, 30)])) 28.792360097775937 """ points_sorted_on_x = column_based_sort(points, column=0) points_sorted_on_y = column_based_sort(points, column=1) return ( closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y, points_counts ) ) ** 0.5 if __name__ == "__main__": points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
import argparse import datetime def zeller(date_input: str) -> str: """ Zellers Congruence Algorithm Find the day of the week for nearly any Gregorian or Julian calendar date >>> zeller('01-31-2010') 'Your date 01-31-2010, is a Sunday!' Validate out of range month >>> zeller('13-31-2010') Traceback (most recent call last): ... ValueError: Month must be between 1 - 12 >>> zeller('.2-31-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.2' Validate out of range date: >>> zeller('01-33-2010') Traceback (most recent call last): ... ValueError: Date must be between 1 - 31 >>> zeller('01-.4-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.4' Validate second separator: >>> zeller('01-31*2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate first separator: >>> zeller('01^31-2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate out of range year: >>> zeller('01-31-8999') Traceback (most recent call last): ... ValueError: Year out of range. There has to be some sort of limit...right? Test null input: >>> zeller() Traceback (most recent call last): ... TypeError: zeller() missing 1 required positional argument: 'date_input' Test length of date_input: >>> zeller('') Traceback (most recent call last): ... ValueError: Must be 10 characters long >>> zeller('01-31-19082939') Traceback (most recent call last): ... ValueError: Must be 10 characters long""" # Days of the week for response days = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday", } convert_datetime_days = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(date_input) < 11: raise ValueError("Must be 10 characters long") # Get month m: int = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError("Month must be between 1 - 12") sep_1: str = date_input[2] # Validate if sep_1 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get day d: int = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError("Date must be between 1 - 31") # Get second separator sep_2: str = date_input[5] # Validate if sep_2 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get year y: int = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( "Year out of range. There has to be some sort of limit...right?" ) # Get datetime obj for validation dt_ck = datetime.date(int(y), int(m), int(d)) # Start math if m <= 2: y = y - 1 m = m + 12 # maths var c: int = int(str(y)[:2]) k: int = int(str(y)[2:]) t: int = int(2.6 * m - 5.39) u: int = int(c / 4) v: int = int(k / 4) x: int = int(d + k) z: int = int(t + u + v + x) w: int = int(z - (2 * c)) f: int = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer.") # Response response: str = f"Your date {date_input}, is a {days[str(f)]}!" return response if __name__ == "__main__": import doctest doctest.testmod() parser = argparse.ArgumentParser( description=( "Find out what day of the week nearly any date is or was. Enter " "date as a string in the mm-dd-yyyy or mm/dd/yyyy format" ) ) parser.add_argument( "date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)" ) args = parser.parse_args() zeller(args.date_input)
import argparse import datetime def zeller(date_input: str) -> str: """ Zellers Congruence Algorithm Find the day of the week for nearly any Gregorian or Julian calendar date >>> zeller('01-31-2010') 'Your date 01-31-2010, is a Sunday!' Validate out of range month >>> zeller('13-31-2010') Traceback (most recent call last): ... ValueError: Month must be between 1 - 12 >>> zeller('.2-31-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.2' Validate out of range date: >>> zeller('01-33-2010') Traceback (most recent call last): ... ValueError: Date must be between 1 - 31 >>> zeller('01-.4-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.4' Validate second separator: >>> zeller('01-31*2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate first separator: >>> zeller('01^31-2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate out of range year: >>> zeller('01-31-8999') Traceback (most recent call last): ... ValueError: Year out of range. There has to be some sort of limit...right? Test null input: >>> zeller() Traceback (most recent call last): ... TypeError: zeller() missing 1 required positional argument: 'date_input' Test length of date_input: >>> zeller('') Traceback (most recent call last): ... ValueError: Must be 10 characters long >>> zeller('01-31-19082939') Traceback (most recent call last): ... ValueError: Must be 10 characters long""" # Days of the week for response days = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday", } convert_datetime_days = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(date_input) < 11: raise ValueError("Must be 10 characters long") # Get month m: int = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError("Month must be between 1 - 12") sep_1: str = date_input[2] # Validate if sep_1 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get day d: int = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError("Date must be between 1 - 31") # Get second separator sep_2: str = date_input[5] # Validate if sep_2 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get year y: int = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( "Year out of range. There has to be some sort of limit...right?" ) # Get datetime obj for validation dt_ck = datetime.date(int(y), int(m), int(d)) # Start math if m <= 2: y = y - 1 m = m + 12 # maths var c: int = int(str(y)[:2]) k: int = int(str(y)[2:]) t: int = int(2.6 * m - 5.39) u: int = int(c / 4) v: int = int(k / 4) x: int = int(d + k) z: int = int(t + u + v + x) w: int = int(z - (2 * c)) f: int = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer.") # Response response: str = f"Your date {date_input}, is a {days[str(f)]}!" return response if __name__ == "__main__": import doctest doctest.testmod() parser = argparse.ArgumentParser( description=( "Find out what day of the week nearly any date is or was. Enter " "date as a string in the mm-dd-yyyy or mm/dd/yyyy format" ) ) parser.add_argument( "date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)" ) args = parser.parse_args() zeller(args.date_input)
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
# Information on binary shifts: # https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types # https://www.interviewcake.com/concept/java/bit-shift def logical_left_shift(number: int, shift_amount: int) -> str: """ Take in 2 positive integers. 'number' is the integer to be logically left shifted 'shift_amount' times. i.e. (number << shift_amount) Return the shifted binary representation. >>> logical_left_shift(0, 1) '0b00' >>> logical_left_shift(1, 1) '0b10' >>> logical_left_shift(1, 5) '0b100000' >>> logical_left_shift(17, 2) '0b1000100' >>> logical_left_shift(1983, 4) '0b111101111110000' >>> logical_left_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number)) binary_number += "0" * shift_amount return binary_number def logical_right_shift(number: int, shift_amount: int) -> str: """ Take in positive 2 integers. 'number' is the integer to be logically right shifted 'shift_amount' times. i.e. (number >>> shift_amount) Return the shifted binary representation. >>> logical_right_shift(0, 1) '0b0' >>> logical_right_shift(1, 1) '0b0' >>> logical_right_shift(1, 5) '0b0' >>> logical_right_shift(17, 2) '0b100' >>> logical_right_shift(1983, 4) '0b1111011' >>> logical_right_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number))[2:] if shift_amount >= len(binary_number): return "0b0" shifted_binary_number = binary_number[: len(binary_number) - shift_amount] return "0b" + shifted_binary_number def arithmetic_right_shift(number: int, shift_amount: int) -> str: """ Take in 2 integers. 'number' is the integer to be arithmetically right shifted 'shift_amount' times. i.e. (number >> shift_amount) Return the shifted binary representation. >>> arithmetic_right_shift(0, 1) '0b00' >>> arithmetic_right_shift(1, 1) '0b00' >>> arithmetic_right_shift(-1, 1) '0b11' >>> arithmetic_right_shift(17, 2) '0b000100' >>> arithmetic_right_shift(-17, 2) '0b111011' >>> arithmetic_right_shift(-1983, 4) '0b111110000100' """ if number >= 0: # Get binary representation of positive number binary_number = "0" + str(bin(number)).strip("-")[2:] else: # Get binary (2's complement) representation of negative number binary_number_length = len(bin(number)[3:]) # Find 2's complement of number binary_number = bin(abs(number) - (1 << binary_number_length))[3:] binary_number = ( "1" + "0" * (binary_number_length - len(binary_number)) + binary_number ) if shift_amount >= len(binary_number): return "0b" + binary_number[0] * len(binary_number) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(binary_number) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
# Information on binary shifts: # https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types # https://www.interviewcake.com/concept/java/bit-shift def logical_left_shift(number: int, shift_amount: int) -> str: """ Take in 2 positive integers. 'number' is the integer to be logically left shifted 'shift_amount' times. i.e. (number << shift_amount) Return the shifted binary representation. >>> logical_left_shift(0, 1) '0b00' >>> logical_left_shift(1, 1) '0b10' >>> logical_left_shift(1, 5) '0b100000' >>> logical_left_shift(17, 2) '0b1000100' >>> logical_left_shift(1983, 4) '0b111101111110000' >>> logical_left_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number)) binary_number += "0" * shift_amount return binary_number def logical_right_shift(number: int, shift_amount: int) -> str: """ Take in positive 2 integers. 'number' is the integer to be logically right shifted 'shift_amount' times. i.e. (number >>> shift_amount) Return the shifted binary representation. >>> logical_right_shift(0, 1) '0b0' >>> logical_right_shift(1, 1) '0b0' >>> logical_right_shift(1, 5) '0b0' >>> logical_right_shift(17, 2) '0b100' >>> logical_right_shift(1983, 4) '0b1111011' >>> logical_right_shift(1, -1) Traceback (most recent call last): ... ValueError: both inputs must be positive integers """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number))[2:] if shift_amount >= len(binary_number): return "0b0" shifted_binary_number = binary_number[: len(binary_number) - shift_amount] return "0b" + shifted_binary_number def arithmetic_right_shift(number: int, shift_amount: int) -> str: """ Take in 2 integers. 'number' is the integer to be arithmetically right shifted 'shift_amount' times. i.e. (number >> shift_amount) Return the shifted binary representation. >>> arithmetic_right_shift(0, 1) '0b00' >>> arithmetic_right_shift(1, 1) '0b00' >>> arithmetic_right_shift(-1, 1) '0b11' >>> arithmetic_right_shift(17, 2) '0b000100' >>> arithmetic_right_shift(-17, 2) '0b111011' >>> arithmetic_right_shift(-1983, 4) '0b111110000100' """ if number >= 0: # Get binary representation of positive number binary_number = "0" + str(bin(number)).strip("-")[2:] else: # Get binary (2's complement) representation of negative number binary_number_length = len(bin(number)[3:]) # Find 2's complement of number binary_number = bin(abs(number) - (1 << binary_number_length))[3:] binary_number = ( "1" + "0" * (binary_number_length - len(binary_number)) + binary_number ) if shift_amount >= len(binary_number): return "0b" + binary_number[0] * len(binary_number) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(binary_number) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Implementation of an auto-balanced binary tree! For doctests run following command: python3 -m doctest -v avl_tree.py For testing run: python avl_tree.py """ from __future__ import annotations import math import random from typing import Any class MyQueue: def __init__(self) -> None: self.data: list[Any] = [] self.head: int = 0 self.tail: int = 0 def is_empty(self) -> bool: return self.head == self.tail def push(self, data: Any) -> None: self.data.append(data) self.tail = self.tail + 1 def pop(self) -> Any: ret = self.data[self.head] self.head = self.head + 1 return ret def count(self) -> int: return self.tail - self.head def print_queue(self) -> None: print(self.data) print("**************") print(self.data[self.head : self.tail]) class MyNode: def __init__(self, data: Any) -> None: self.data = data self.left: MyNode | None = None self.right: MyNode | None = None self.height: int = 1 def get_data(self) -> Any: return self.data def get_left(self) -> MyNode | None: return self.left def get_right(self) -> MyNode | None: return self.right def get_height(self) -> int: return self.height def set_data(self, data: Any) -> None: self.data = data def set_left(self, node: MyNode | None) -> None: self.left = node def set_right(self, node: MyNode | None) -> None: self.right = node def set_height(self, height: int) -> None: self.height = height def get_height(node: MyNode | None) -> int: if node is None: return 0 return node.get_height() def my_max(a: int, b: int) -> int: if a > b: return a return b def right_rotation(node: MyNode) -> MyNode: r""" A B / \ / \ B C Bl A / \ --> / / \ Bl Br UB Br C / UB UB = unbalanced node """ print("left rotation node:", node.get_data()) ret = node.get_left() assert ret is not None node.set_left(ret.get_right()) ret.set_right(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret def left_rotation(node: MyNode) -> MyNode: """ a mirror symmetry rotation of the left_rotation """ print("right rotation node:", node.get_data()) ret = node.get_right() assert ret is not None node.set_right(ret.get_left()) ret.set_left(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret def lr_rotation(node: MyNode) -> MyNode: r""" A A Br / \ / \ / \ B C LR Br C RR B A / \ --> / \ --> / / \ Bl Br B UB Bl UB C \ / UB Bl RR = right_rotation LR = left_rotation """ left_child = node.get_left() assert left_child is not None node.set_left(left_rotation(left_child)) return right_rotation(node) def rl_rotation(node: MyNode) -> MyNode: right_child = node.get_right() assert right_child is not None node.set_right(right_rotation(right_child)) return left_rotation(node) def insert_node(node: MyNode | None, data: Any) -> MyNode | None: if node is None: return MyNode(data) if data < node.get_data(): node.set_left(insert_node(node.get_left(), data)) if ( get_height(node.get_left()) - get_height(node.get_right()) == 2 ): # an unbalance detected left_child = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child node = right_rotation(node) else: node = lr_rotation(node) else: node.set_right(insert_node(node.get_right(), data)) if get_height(node.get_right()) - get_height(node.get_left()) == 2: right_child = node.get_right() assert right_child is not None if data < right_child.get_data(): node = rl_rotation(node) else: node = left_rotation(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) return node def get_right_most(root: MyNode) -> Any: while True: right_child = root.get_right() if right_child is None: break root = right_child return root.get_data() def get_left_most(root: MyNode) -> Any: while True: left_child = root.get_left() if left_child is None: break root = left_child return root.get_data() def del_node(root: MyNode, data: Any) -> MyNode | None: left_child = root.get_left() right_child = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: temp_data = get_left_most(right_child) root.set_data(temp_data) root.set_right(del_node(right_child, temp_data)) elif left_child is not None: root = left_child elif right_child is not None: root = right_child else: return None elif root.get_data() > data: if left_child is None: print("No such data") return root else: root.set_left(del_node(left_child, data)) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(right_child, data)) if get_height(right_child) - get_height(left_child) == 2: assert right_child is not None if get_height(right_child.get_right()) > get_height(right_child.get_left()): root = left_rotation(root) else: root = rl_rotation(root) elif get_height(right_child) - get_height(left_child) == -2: assert left_child is not None if get_height(left_child.get_left()) > get_height(left_child.get_right()): root = right_rotation(root) else: root = lr_rotation(root) height = my_max(get_height(root.get_right()), get_height(root.get_left())) + 1 root.set_height(height) return root class AVLtree: """ An AVL tree doctest Examples: >>> t = AVLtree() >>> t.insert(4) insert:4 >>> print(str(t).replace(" \\n","\\n")) 4 ************************************* >>> t.insert(2) insert:2 >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) 4 2 * ************************************* >>> t.insert(3) insert:3 right rotation node: 2 left rotation node: 4 >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) 3 2 4 ************************************* >>> t.get_height() 2 >>> t.del_node(3) delete:3 >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) 4 2 * ************************************* """ def __init__(self) -> None: self.root: MyNode | None = None def get_height(self) -> int: return get_height(self.root) def insert(self, data: Any) -> None: print("insert:" + str(data)) self.root = insert_node(self.root, data) def del_node(self, data: Any) -> None: print("delete:" + str(data)) if self.root is None: print("Tree is empty!") return self.root = del_node(self.root, data) def __str__( self, ) -> str: # a level traversale, gives a more intuitive look on the tree output = "" q = MyQueue() q.push(self.root) layer = self.get_height() if layer == 0: return output cnt = 0 while not q.is_empty(): node = q.pop() space = " " * int(math.pow(2, layer - 1)) output += space if node is None: output += "*" q.push(None) q.push(None) else: output += str(node.get_data()) q.push(node.get_left()) q.push(node.get_right()) output += space cnt = cnt + 1 for i in range(100): if cnt == math.pow(2, i) - 1: layer = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def _test() -> None: import doctest doctest.testmod() if __name__ == "__main__": _test() t = AVLtree() lst = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
""" Implementation of an auto-balanced binary tree! For doctests run following command: python3 -m doctest -v avl_tree.py For testing run: python avl_tree.py """ from __future__ import annotations import math import random from typing import Any class MyQueue: def __init__(self) -> None: self.data: list[Any] = [] self.head: int = 0 self.tail: int = 0 def is_empty(self) -> bool: return self.head == self.tail def push(self, data: Any) -> None: self.data.append(data) self.tail = self.tail + 1 def pop(self) -> Any: ret = self.data[self.head] self.head = self.head + 1 return ret def count(self) -> int: return self.tail - self.head def print_queue(self) -> None: print(self.data) print("**************") print(self.data[self.head : self.tail]) class MyNode: def __init__(self, data: Any) -> None: self.data = data self.left: MyNode | None = None self.right: MyNode | None = None self.height: int = 1 def get_data(self) -> Any: return self.data def get_left(self) -> MyNode | None: return self.left def get_right(self) -> MyNode | None: return self.right def get_height(self) -> int: return self.height def set_data(self, data: Any) -> None: self.data = data def set_left(self, node: MyNode | None) -> None: self.left = node def set_right(self, node: MyNode | None) -> None: self.right = node def set_height(self, height: int) -> None: self.height = height def get_height(node: MyNode | None) -> int: if node is None: return 0 return node.get_height() def my_max(a: int, b: int) -> int: if a > b: return a return b def right_rotation(node: MyNode) -> MyNode: r""" A B / \ / \ B C Bl A / \ --> / / \ Bl Br UB Br C / UB UB = unbalanced node """ print("left rotation node:", node.get_data()) ret = node.get_left() assert ret is not None node.set_left(ret.get_right()) ret.set_right(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret def left_rotation(node: MyNode) -> MyNode: """ a mirror symmetry rotation of the left_rotation """ print("right rotation node:", node.get_data()) ret = node.get_right() assert ret is not None node.set_right(ret.get_left()) ret.set_left(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret def lr_rotation(node: MyNode) -> MyNode: r""" A A Br / \ / \ / \ B C LR Br C RR B A / \ --> / \ --> / / \ Bl Br B UB Bl UB C \ / UB Bl RR = right_rotation LR = left_rotation """ left_child = node.get_left() assert left_child is not None node.set_left(left_rotation(left_child)) return right_rotation(node) def rl_rotation(node: MyNode) -> MyNode: right_child = node.get_right() assert right_child is not None node.set_right(right_rotation(right_child)) return left_rotation(node) def insert_node(node: MyNode | None, data: Any) -> MyNode | None: if node is None: return MyNode(data) if data < node.get_data(): node.set_left(insert_node(node.get_left(), data)) if ( get_height(node.get_left()) - get_height(node.get_right()) == 2 ): # an unbalance detected left_child = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child node = right_rotation(node) else: node = lr_rotation(node) else: node.set_right(insert_node(node.get_right(), data)) if get_height(node.get_right()) - get_height(node.get_left()) == 2: right_child = node.get_right() assert right_child is not None if data < right_child.get_data(): node = rl_rotation(node) else: node = left_rotation(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) return node def get_right_most(root: MyNode) -> Any: while True: right_child = root.get_right() if right_child is None: break root = right_child return root.get_data() def get_left_most(root: MyNode) -> Any: while True: left_child = root.get_left() if left_child is None: break root = left_child return root.get_data() def del_node(root: MyNode, data: Any) -> MyNode | None: left_child = root.get_left() right_child = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: temp_data = get_left_most(right_child) root.set_data(temp_data) root.set_right(del_node(right_child, temp_data)) elif left_child is not None: root = left_child elif right_child is not None: root = right_child else: return None elif root.get_data() > data: if left_child is None: print("No such data") return root else: root.set_left(del_node(left_child, data)) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(right_child, data)) if get_height(right_child) - get_height(left_child) == 2: assert right_child is not None if get_height(right_child.get_right()) > get_height(right_child.get_left()): root = left_rotation(root) else: root = rl_rotation(root) elif get_height(right_child) - get_height(left_child) == -2: assert left_child is not None if get_height(left_child.get_left()) > get_height(left_child.get_right()): root = right_rotation(root) else: root = lr_rotation(root) height = my_max(get_height(root.get_right()), get_height(root.get_left())) + 1 root.set_height(height) return root class AVLtree: """ An AVL tree doctest Examples: >>> t = AVLtree() >>> t.insert(4) insert:4 >>> print(str(t).replace(" \\n","\\n")) 4 ************************************* >>> t.insert(2) insert:2 >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) 4 2 * ************************************* >>> t.insert(3) insert:3 right rotation node: 2 left rotation node: 4 >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) 3 2 4 ************************************* >>> t.get_height() 2 >>> t.del_node(3) delete:3 >>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n")) 4 2 * ************************************* """ def __init__(self) -> None: self.root: MyNode | None = None def get_height(self) -> int: return get_height(self.root) def insert(self, data: Any) -> None: print("insert:" + str(data)) self.root = insert_node(self.root, data) def del_node(self, data: Any) -> None: print("delete:" + str(data)) if self.root is None: print("Tree is empty!") return self.root = del_node(self.root, data) def __str__( self, ) -> str: # a level traversale, gives a more intuitive look on the tree output = "" q = MyQueue() q.push(self.root) layer = self.get_height() if layer == 0: return output cnt = 0 while not q.is_empty(): node = q.pop() space = " " * int(math.pow(2, layer - 1)) output += space if node is None: output += "*" q.push(None) q.push(None) else: output += str(node.get_data()) q.push(node.get_left()) q.push(node.get_right()) output += space cnt = cnt + 1 for i in range(100): if cnt == math.pow(2, i) - 1: layer = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def _test() -> None: import doctest doctest.testmod() if __name__ == "__main__": _test() t = AVLtree() lst = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
-1
TheAlgorithms/Python
9,543
[pre-commit.ci] pre-commit autoupdate
<!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
pre-commit-ci[bot]
"2023-10-02T23:32:55Z"
"2023-10-07T19:32:28Z"
60291738d2552999545c414bb8a8e90f86c69678
895dffb412d80f29c65a062bf6d91fd2a70d8818
[pre-commit.ci] pre-commit autoupdate. <!--pre-commit.ci start--> updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.291 β†’ v0.0.292](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.291...v0.0.292) - [github.com/codespell-project/codespell: v2.2.5 β†’ v2.2.6](https://github.com/codespell-project/codespell/compare/v2.2.5...v2.2.6) - [github.com/tox-dev/pyproject-fmt: 1.1.0 β†’ 1.2.0](https://github.com/tox-dev/pyproject-fmt/compare/1.1.0...1.2.0) <!--pre-commit.ci end-->
""" Numerical integration or quadrature for a smooth function f with known values at x_i This method is the classical approach of suming 'Equally Spaced Abscissas' method 2: "Simpson Rule" """ def method_2(boundary, steps): # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 3.0) * f(a) cnt = 2 for i in x_i: y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i) cnt += 1 y += (h / 3.0) * f(b) return y def make_points(a, b, h): x = a + h while x < (b - h): yield x x = x + h def f(x): # enter your function here y = (x - 0) * (x - 0) return y def main(): a = 0.0 # Lower bound of integration b = 1.0 # Upper bound of integration steps = 10.0 # define number of steps or resolution boundary = [a, b] # define boundary of integration y = method_2(boundary, steps) print(f"y = {y}") if __name__ == "__main__": main()
""" Numerical integration or quadrature for a smooth function f with known values at x_i This method is the classical approach of suming 'Equally Spaced Abscissas' method 2: "Simpson Rule" """ def method_2(boundary, steps): # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 3.0) * f(a) cnt = 2 for i in x_i: y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i) cnt += 1 y += (h / 3.0) * f(b) return y def make_points(a, b, h): x = a + h while x < (b - h): yield x x = x + h def f(x): # enter your function here y = (x - 0) * (x - 0) return y def main(): a = 0.0 # Lower bound of integration b = 1.0 # Upper bound of integration steps = 10.0 # define number of steps or resolution boundary = [a, b] # define boundary of integration y = method_2(boundary, steps) print(f"y = {y}") if __name__ == "__main__": main()
-1