Prompt
stringlengths
16
11.5k
Completions
stringlengths
84
25.3k
Integer Square Root Algorithm An efficient method to calculate the square root of a nonnegative integer 'num' rounded down to the nearest integer. It uses a binary search approach to find the integer square root without using any builtin exponent functions or operators. https:en.wikipedia.orgwikiIntegersquareroot https:docs.python.org3librarymath.htmlmath.isqrt Note: This algorithm is designed for nonnegative integers only. The result is rounded down to the nearest integer. The algorithm has a time complexity of Ologx. Original algorithm idea based on binary search. Returns the integer square root of a nonnegative integer num. Args: num: A nonnegative integer. Returns: The integer square root of num. Raises: ValueError: If num is not an integer or is negative. integersquarerooti for i in range18 0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4 integersquareroot625 25 integersquareroot2147483647 46340 from math import isqrt allintegersquarerooti isqrti for i in range20 True integersquareroot1 Traceback most recent call last: ... ValueError: num must be nonnegative integer integersquareroot1.5 Traceback most recent call last: ... ValueError: num must be nonnegative integer integersquareroot0 Traceback most recent call last: ... ValueError: num must be nonnegative integer
def integer_square_root(num: int) -> int: """ Returns the integer square root of a non-negative integer num. Args: num: A non-negative integer. Returns: The integer square root of num. Raises: ValueError: If num is not an integer or is negative. >>> [integer_square_root(i) for i in range(18)] [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4] >>> integer_square_root(625) 25 >>> integer_square_root(2_147_483_647) 46340 >>> from math import isqrt >>> all(integer_square_root(i) == isqrt(i) for i in range(20)) True >>> integer_square_root(-1) Traceback (most recent call last): ... ValueError: num must be non-negative integer >>> integer_square_root(1.5) Traceback (most recent call last): ... ValueError: num must be non-negative integer >>> integer_square_root("0") Traceback (most recent call last): ... ValueError: num must be non-negative integer """ if not isinstance(num, int) or num < 0: raise ValueError("num must be non-negative integer") if num < 2: return num left_bound = 0 right_bound = num // 2 while left_bound <= right_bound: mid = left_bound + (right_bound - left_bound) // 2 mid_squared = mid * mid if mid_squared == num: return mid if mid_squared < num: left_bound = mid + 1 else: right_bound = mid - 1 return right_bound if __name__ == "__main__": import doctest doctest.testmod()
An implementation of interquartile range IQR which is a measure of statistical dispersion, which is the spread of the data. The function takes the list of numeric values as input and returns the IQR. Script inspired by this Wikipedia article: https:en.wikipedia.orgwikiInterquartilerange This is the implementation of the median. :param nums: The list of numeric nums :return: Median of the list findmediannums1, 2, 2, 3, 4 2 findmediannums1, 2, 2, 3, 4, 4 2.5 findmediannums1, 2, 0, 3, 4, 4 1.5 findmediannums1.1, 2.2, 2, 3.3, 4.4, 4 2.65 Return the interquartile range for a list of numeric values. :param nums: The list of numeric values. :return: interquartile range interquartilerangenums4, 1, 2, 3, 2 2.0 interquartilerangenums 2, 7, 10, 9, 8, 4, 67, 45 17.0 interquartilerangenums 2.1, 7.1, 10.1, 9.1, 8.1, 4.1, 67.1, 45.1 17.2 interquartilerangenums 0, 0, 0, 0, 0 0.0 interquartilerangenums Traceback most recent call last: ... ValueError: The list is empty. Provide a nonempty list.
from __future__ import annotations def find_median(nums: list[int | float]) -> float: """ This is the implementation of the median. :param nums: The list of numeric nums :return: Median of the list >>> find_median(nums=([1, 2, 2, 3, 4])) 2 >>> find_median(nums=([1, 2, 2, 3, 4, 4])) 2.5 >>> find_median(nums=([-1, 2, 0, 3, 4, -4])) 1.5 >>> find_median(nums=([1.1, 2.2, 2, 3.3, 4.4, 4])) 2.65 """ div, mod = divmod(len(nums), 2) if mod: return nums[div] return (nums[div] + nums[(div) - 1]) / 2 def interquartile_range(nums: list[int | float]) -> float: """ Return the interquartile range for a list of numeric values. :param nums: The list of numeric values. :return: interquartile range >>> interquartile_range(nums=[4, 1, 2, 3, 2]) 2.0 >>> interquartile_range(nums = [-2, -7, -10, 9, 8, 4, -67, 45]) 17.0 >>> interquartile_range(nums = [-2.1, -7.1, -10.1, 9.1, 8.1, 4.1, -67.1, 45.1]) 17.2 >>> interquartile_range(nums = [0, 0, 0, 0, 0]) 0.0 >>> interquartile_range(nums=[]) Traceback (most recent call last): ... ValueError: The list is empty. Provide a non-empty list. """ if not nums: raise ValueError("The list is empty. Provide a non-empty list.") nums.sort() length = len(nums) div, mod = divmod(length, 2) q1 = find_median(nums[:div]) half_length = sum((div, mod)) q3 = find_median(nums[half_length:length]) return q3 - q1 if __name__ == "__main__": import doctest doctest.testmod()
Returns whether num is a palindrome or not see for reference https:en.wikipedia.orgwikiPalindromicnumber. isintpalindrome121 False isintpalindrome0 True isintpalindrome10 False isintpalindrome11 True isintpalindrome101 True isintpalindrome120 False
def is_int_palindrome(num: int) -> bool: """ Returns whether `num` is a palindrome or not (see for reference https://en.wikipedia.org/wiki/Palindromic_number). >>> is_int_palindrome(-121) False >>> is_int_palindrome(0) True >>> is_int_palindrome(10) False >>> is_int_palindrome(11) True >>> is_int_palindrome(101) True >>> is_int_palindrome(120) False """ if num < 0: return False num_copy: int = num rev_num: int = 0 while num > 0: rev_num = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
Is IP v4 address valid? A valid IP address must be four octets in the form of A.B.C.D, where A,B,C and D are numbers from 0254 for example: 192.168.23.1, 172.254.254.254 are valid IP address 192.168.255.0, 255.192.3.121 are invalid IP address print Valid IP address If IP is valid. or print Invalid IP address If IP is invalid. isipv4addressvalid192.168.0.23 True isipv4addressvalid192.255.15.8 False isipv4addressvalid172.100.0.8 True isipv4addressvalid254.255.0.255 False isipv4addressvalid1.2.33333333.4 False isipv4addressvalid1.2.3.4 False isipv4addressvalid1.2.3 False isipv4addressvalid1.2.3.4.5 False isipv4addressvalid1.2.A.4 False isipv4addressvalid0.0.0.0 True isipv4addressvalid1.2.3. False
def is_ip_v4_address_valid(ip_v4_address: str) -> bool: """ print "Valid IP address" If IP is valid. or print "Invalid IP address" If IP is invalid. >>> is_ip_v4_address_valid("192.168.0.23") True >>> is_ip_v4_address_valid("192.255.15.8") False >>> is_ip_v4_address_valid("172.100.0.8") True >>> is_ip_v4_address_valid("254.255.0.255") False >>> is_ip_v4_address_valid("1.2.33333333.4") False >>> is_ip_v4_address_valid("1.2.-3.4") False >>> is_ip_v4_address_valid("1.2.3") False >>> is_ip_v4_address_valid("1.2.3.4.5") False >>> is_ip_v4_address_valid("1.2.A.4") False >>> is_ip_v4_address_valid("0.0.0.0") True >>> is_ip_v4_address_valid("1.2.3.") False """ octets = [int(i) for i in ip_v4_address.split(".") if i.isdigit()] return len(octets) == 4 and all(0 <= int(octet) <= 254 for octet in octets) if __name__ == "__main__": ip = input().strip() valid_or_invalid = "valid" if is_ip_v4_address_valid(ip) else "invalid" print(f"{ip} is a {valid_or_invalid} IP v4 address.")
References: wikipedia:square free number psfblack : True ruff : True doctest: NORMALIZEWHITESPACE This functions takes a list of prime factors as input. returns True if the factors are square free. issquarefree1, 1, 2, 3, 4 False These are wrong but should return some value it simply checks for repetition in the numbers. issquarefree1, 3, 4, 'sd', 0.0 True issquarefree1, 0.5, 2, 0.0 True issquarefree1, 2, 2, 5 False issquarefree'asd' True issquarefree24 Traceback most recent call last: ... TypeError: 'int' object is not iterable
from __future__ import annotations def is_square_free(factors: list[int]) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes a list of prime factors as input. returns True if the factors are square free. >>> is_square_free([1, 1, 2, 3, 4]) False These are wrong but should return some value it simply checks for repetition in the numbers. >>> is_square_free([1, 3, 4, 'sd', 0.0]) True >>> is_square_free([1, 0.5, 2, 0.0]) True >>> is_square_free([1, 2, 2, 5]) False >>> is_square_free('asd') True >>> is_square_free(24) Traceback (most recent call last): ... TypeError: 'int' object is not iterable """ return len(set(factors)) == len(factors) if __name__ == "__main__": import doctest doctest.testmod()
The Jaccard similarity coefficient is a commonly used indicator of the similarity between two sets. Let U be a set and A and B be subsets of U, then the Jaccard indexsimilarity is defined to be the ratio of the number of elements of their intersection and the number of elements of their union. Inspired from Wikipedia and the book Mining of Massive Datasets MMDS 2nd Edition, Chapter 3 https:en.wikipedia.orgwikiJaccardindex https:mmds.org Jaccard similarity is widely used with MinHashing. Finds the jaccard similarity between two sets. Essentially, its intersection over union. The alternative way to calculate this is to take union as sum of the number of items in the two sets. This will lead to jaccard similarity of a set with itself be 12 instead of 1. MMDS 2nd Edition, Page 77 Parameters: :seta set,list,tuple: A nonempty setlist :setb set,list,tuple: A nonempty setlist :alternativeUnion boolean: If True, use sum of number of items as union Output: float The jaccard similarity between the two sets. Examples: seta 'a', 'b', 'c', 'd', 'e' setb 'c', 'd', 'e', 'f', 'h', 'i' jaccardsimilarityseta, setb 0.375 jaccardsimilarityseta, seta 1.0 jaccardsimilarityseta, seta, True 0.5 seta 'a', 'b', 'c', 'd', 'e' setb 'c', 'd', 'e', 'f', 'h', 'i' jaccardsimilarityseta, setb 0.375 seta 'c', 'd', 'e', 'f', 'h', 'i' setb 'a', 'b', 'c', 'd', 'e' jaccardsimilarityseta, setb 0.375 seta 'c', 'd', 'e', 'f', 'h', 'i' setb 'a', 'b', 'c', 'd' jaccardsimilarityseta, setb, True 0.2 seta 'a', 'b' setb 'c', 'd' jaccardsimilarityseta, setb Traceback most recent call last: ... ValueError: Set a and b must either both be sets or be either a list or a tuple. Cast seta to list because tuples cannot be mutated
def jaccard_similarity( set_a: set[str] | list[str] | tuple[str], set_b: set[str] | list[str] | tuple[str], alternative_union=False, ): """ Finds the jaccard similarity between two sets. Essentially, its intersection over union. The alternative way to calculate this is to take union as sum of the number of items in the two sets. This will lead to jaccard similarity of a set with itself be 1/2 instead of 1. [MMDS 2nd Edition, Page 77] Parameters: :set_a (set,list,tuple): A non-empty set/list :set_b (set,list,tuple): A non-empty set/list :alternativeUnion (boolean): If True, use sum of number of items as union Output: (float) The jaccard similarity between the two sets. Examples: >>> set_a = {'a', 'b', 'c', 'd', 'e'} >>> set_b = {'c', 'd', 'e', 'f', 'h', 'i'} >>> jaccard_similarity(set_a, set_b) 0.375 >>> jaccard_similarity(set_a, set_a) 1.0 >>> jaccard_similarity(set_a, set_a, True) 0.5 >>> set_a = ['a', 'b', 'c', 'd', 'e'] >>> set_b = ('c', 'd', 'e', 'f', 'h', 'i') >>> jaccard_similarity(set_a, set_b) 0.375 >>> set_a = ('c', 'd', 'e', 'f', 'h', 'i') >>> set_b = ['a', 'b', 'c', 'd', 'e'] >>> jaccard_similarity(set_a, set_b) 0.375 >>> set_a = ('c', 'd', 'e', 'f', 'h', 'i') >>> set_b = ['a', 'b', 'c', 'd'] >>> jaccard_similarity(set_a, set_b, True) 0.2 >>> set_a = {'a', 'b'} >>> set_b = ['c', 'd'] >>> jaccard_similarity(set_a, set_b) Traceback (most recent call last): ... ValueError: Set a and b must either both be sets or be either a list or a tuple. """ if isinstance(set_a, set) and isinstance(set_b, set): intersection_length = len(set_a.intersection(set_b)) if alternative_union: union_length = len(set_a) + len(set_b) else: union_length = len(set_a.union(set_b)) return intersection_length / union_length elif isinstance(set_a, (list, tuple)) and isinstance(set_b, (list, tuple)): intersection = [element for element in set_a if element in set_b] if alternative_union: return len(intersection) / (len(set_a) + len(set_b)) else: # Cast set_a to list because tuples cannot be mutated union = list(set_a) + [element for element in set_b if element not in set_a] return len(intersection) / len(union) raise ValueError( "Set a and b must either both be sets or be either a list or a tuple." ) if __name__ == "__main__": set_a = {"a", "b", "c", "d", "e"} set_b = {"c", "d", "e", "f", "h", "i"} print(jaccard_similarity(set_a, set_b))
Calculate joint probability distribution https:en.wikipedia.orgwikiJointprobabilitydistribution jointdistribution jointprobabilitydistribution ... 1, 2, 2, 5, 8, 0.7, 0.3, 0.3, 0.5, 0.2 ... from math import isclose isclosejointdistribution.pop1, 8, 0.14 True jointdistribution 1, 2: 0.21, 1, 5: 0.35, 2, 2: 0.09, 2, 5: 0.15, 2, 8: 0.06 Function to calculate the expectation mean from math import isclose iscloseexpectation1, 2, 0.7, 0.3, 1.3 True Function to calculate the variance from math import isclose isclosevariance1,2,0.7,0.3, 0.21 True Function to calculate the covariance covariance1, 2, 2, 5, 8, 0.7, 0.3, 0.3, 0.5, 0.2 2.7755575615628914e17 Function to calculate the standard deviation standarddeviation0.21 0.458257569495584 Input values for X and Y Convert input values to integers Input probabilities for X and Y Convert input probabilities to floats Calculate the joint probability distribution Print the joint probability distribution
def joint_probability_distribution( x_values: list[int], y_values: list[int], x_probabilities: list[float], y_probabilities: list[float], ) -> dict: """ >>> joint_distribution = joint_probability_distribution( ... [1, 2], [-2, 5, 8], [0.7, 0.3], [0.3, 0.5, 0.2] ... ) >>> from math import isclose >>> isclose(joint_distribution.pop((1, 8)), 0.14) True >>> joint_distribution {(1, -2): 0.21, (1, 5): 0.35, (2, -2): 0.09, (2, 5): 0.15, (2, 8): 0.06} """ return { (x, y): x_prob * y_prob for x, x_prob in zip(x_values, x_probabilities) for y, y_prob in zip(y_values, y_probabilities) } # Function to calculate the expectation (mean) def expectation(values: list, probabilities: list) -> float: """ >>> from math import isclose >>> isclose(expectation([1, 2], [0.7, 0.3]), 1.3) True """ return sum(x * p for x, p in zip(values, probabilities)) # Function to calculate the variance def variance(values: list[int], probabilities: list[float]) -> float: """ >>> from math import isclose >>> isclose(variance([1,2],[0.7,0.3]), 0.21) True """ mean = expectation(values, probabilities) return sum((x - mean) ** 2 * p for x, p in zip(values, probabilities)) # Function to calculate the covariance def covariance( x_values: list[int], y_values: list[int], x_probabilities: list[float], y_probabilities: list[float], ) -> float: """ >>> covariance([1, 2], [-2, 5, 8], [0.7, 0.3], [0.3, 0.5, 0.2]) -2.7755575615628914e-17 """ mean_x = expectation(x_values, x_probabilities) mean_y = expectation(y_values, y_probabilities) return sum( (x - mean_x) * (y - mean_y) * px * py for x, px in zip(x_values, x_probabilities) for y, py in zip(y_values, y_probabilities) ) # Function to calculate the standard deviation def standard_deviation(variance: float) -> float: """ >>> standard_deviation(0.21) 0.458257569495584 """ return variance**0.5 if __name__ == "__main__": from doctest import testmod testmod() # Input values for X and Y x_vals = input("Enter values of X separated by spaces: ").split() y_vals = input("Enter values of Y separated by spaces: ").split() # Convert input values to integers x_values = [int(x) for x in x_vals] y_values = [int(y) for y in y_vals] # Input probabilities for X and Y x_probs = input("Enter probabilities for X separated by spaces: ").split() y_probs = input("Enter probabilities for Y separated by spaces: ").split() assert len(x_values) == len(x_probs) assert len(y_values) == len(y_probs) # Convert input probabilities to floats x_probabilities = [float(p) for p in x_probs] y_probabilities = [float(p) for p in y_probs] # Calculate the joint probability distribution jpd = joint_probability_distribution( x_values, y_values, x_probabilities, y_probabilities ) # Print the joint probability distribution print( "\n".join( f"P(X={x}, Y={y}) = {probability}" for (x, y), probability in jpd.items() ) ) mean_xy = expectation( [x * y for x in x_values for y in y_values], [px * py for px in x_probabilities for py in y_probabilities], ) print(f"x mean: {expectation(x_values, x_probabilities) = }") print(f"y mean: {expectation(y_values, y_probabilities) = }") print(f"xy mean: {mean_xy}") print(f"x: {variance(x_values, x_probabilities) = }") print(f"y: {variance(y_values, y_probabilities) = }") print(f"{covariance(x_values, y_values, x_probabilities, y_probabilities) = }") print(f"x: {standard_deviation(variance(x_values, x_probabilities)) = }") print(f"y: {standard_deviation(variance(y_values, y_probabilities)) = }")
The Josephus problem is a famous theoretical problem related to a certain countingout game. This module provides functions to solve the Josephus problem for numpeople and a stepsize. The Josephus problem is defined as follows: numpeople are standing in a circle. Starting with a specified person, you count around the circle, skipping a fixed number of people stepsize. The person at which you stop counting is eliminated from the circle. The counting continues until only one person remains. For more information about the Josephus problem, refer to: https:en.wikipedia.orgwikiJosephusproblem Solve the Josephus problem for numpeople and a stepsize recursively. Args: numpeople: A positive integer representing the number of people. stepsize: A positive integer representing the step size for elimination. Returns: The position of the last person remaining. Raises: ValueError: If numpeople or stepsize is not a positive integer. Examples: josephusrecursive7, 3 3 josephusrecursive10, 2 4 josephusrecursive0, 2 Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. josephusrecursive1.9, 2 Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. josephusrecursive2, 2 Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. josephusrecursive7, 0 Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. josephusrecursive7, 2 Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. josephusrecursive1000, 0.01 Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. josephusrecursivecat, dog Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. Find the winner of the Josephus problem for numpeople and a stepsize. Args: numpeople int: Number of people. stepsize int: Step size for elimination. Returns: int: The position of the last person remaining 1based index. Examples: findwinner7, 3 4 findwinner10, 2 5 Solve the Josephus problem for numpeople and a stepsize iteratively. Args: numpeople int: The number of people in the circle. stepsize int: The number of steps to take before eliminating someone. Returns: int: The position of the last person standing. Examples: josephusiterative5, 2 3 josephusiterative7, 3 4
def josephus_recursive(num_people: int, step_size: int) -> int: """ Solve the Josephus problem for num_people and a step_size recursively. Args: num_people: A positive integer representing the number of people. step_size: A positive integer representing the step size for elimination. Returns: The position of the last person remaining. Raises: ValueError: If num_people or step_size is not a positive integer. Examples: >>> josephus_recursive(7, 3) 3 >>> josephus_recursive(10, 2) 4 >>> josephus_recursive(0, 2) Traceback (most recent call last): ... ValueError: num_people or step_size is not a positive integer. >>> josephus_recursive(1.9, 2) Traceback (most recent call last): ... ValueError: num_people or step_size is not a positive integer. >>> josephus_recursive(-2, 2) Traceback (most recent call last): ... ValueError: num_people or step_size is not a positive integer. >>> josephus_recursive(7, 0) Traceback (most recent call last): ... ValueError: num_people or step_size is not a positive integer. >>> josephus_recursive(7, -2) Traceback (most recent call last): ... ValueError: num_people or step_size is not a positive integer. >>> josephus_recursive(1_000, 0.01) Traceback (most recent call last): ... ValueError: num_people or step_size is not a positive integer. >>> josephus_recursive("cat", "dog") Traceback (most recent call last): ... ValueError: num_people or step_size is not a positive integer. """ if ( not isinstance(num_people, int) or not isinstance(step_size, int) or num_people <= 0 or step_size <= 0 ): raise ValueError("num_people or step_size is not a positive integer.") if num_people == 1: return 0 return (josephus_recursive(num_people - 1, step_size) + step_size) % num_people def find_winner(num_people: int, step_size: int) -> int: """ Find the winner of the Josephus problem for num_people and a step_size. Args: num_people (int): Number of people. step_size (int): Step size for elimination. Returns: int: The position of the last person remaining (1-based index). Examples: >>> find_winner(7, 3) 4 >>> find_winner(10, 2) 5 """ return josephus_recursive(num_people, step_size) + 1 def josephus_iterative(num_people: int, step_size: int) -> int: """ Solve the Josephus problem for num_people and a step_size iteratively. Args: num_people (int): The number of people in the circle. step_size (int): The number of steps to take before eliminating someone. Returns: int: The position of the last person standing. Examples: >>> josephus_iterative(5, 2) 3 >>> josephus_iterative(7, 3) 4 """ circle = list(range(1, num_people + 1)) current = 0 while len(circle) > 1: current = (current + step_size - 1) % len(circle) circle.pop(current) return circle[0] if __name__ == "__main__": import doctest doctest.testmod()
Juggler Sequence Juggler sequence start with any positive integer n. The next term is obtained as follows: If n term is even, the next term is floor value of square root of n . If n is odd, the next term is floor value of 3 time the square root of n. https:en.wikipedia.orgwikiJugglersequence Author : Akshay Dubey https:github.comitsAkshayDubey jugglersequence0 Traceback most recent call last: ... ValueError: Input value of number0 must be a positive integer jugglersequence1 1 jugglersequence2 2, 1 jugglersequence3 3, 5, 11, 36, 6, 2, 1 jugglersequence5 5, 11, 36, 6, 2, 1 jugglersequence10 10, 3, 5, 11, 36, 6, 2, 1 jugglersequence25 25, 125, 1397, 52214, 228, 15, 58, 7, 18, 4, 2, 1 jugglersequence6.0 Traceback most recent call last: ... TypeError: Input value of number6.0 must be an integer jugglersequence1 Traceback most recent call last: ... ValueError: Input value of number1 must be a positive integer
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) import math def juggler_sequence(number: int) -> list[int]: """ >>> juggler_sequence(0) Traceback (most recent call last): ... ValueError: Input value of [number=0] must be a positive integer >>> juggler_sequence(1) [1] >>> juggler_sequence(2) [2, 1] >>> juggler_sequence(3) [3, 5, 11, 36, 6, 2, 1] >>> juggler_sequence(5) [5, 11, 36, 6, 2, 1] >>> juggler_sequence(10) [10, 3, 5, 11, 36, 6, 2, 1] >>> juggler_sequence(25) [25, 125, 1397, 52214, 228, 15, 58, 7, 18, 4, 2, 1] >>> juggler_sequence(6.0) Traceback (most recent call last): ... TypeError: Input value of [number=6.0] must be an integer >>> juggler_sequence(-1) Traceback (most recent call last): ... ValueError: Input value of [number=-1] must be a positive integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be a positive integer" raise ValueError(msg) sequence = [number] while number != 1: if number % 2 == 0: number = math.floor(math.sqrt(number)) else: number = math.floor( math.sqrt(number) * math.sqrt(number) * math.sqrt(number) ) sequence.append(number) return sequence if __name__ == "__main__": import doctest doctest.testmod()
Multiply two numbers using Karatsuba algorithm def karatsubaa: int, b: int int: if lenstra 1 or lenstrb 1: return a b m1 maxlenstra, lenstrb m2 m1 2 a1, a2 divmoda, 10m2 b1, b2 divmodb, 10m2 x karatsubaa2, b2 y karatsubaa1 a2, b1 b2 z karatsubaa1, b1 return z 10 2 m2 y z x 10 m2 x def main: printkaratsuba15463, 23489 if name main: main
def karatsuba(a: int, b: int) -> int: """ >>> karatsuba(15463, 23489) == 15463 * 23489 True >>> karatsuba(3, 9) == 3 * 9 True """ if len(str(a)) == 1 or len(str(b)) == 1: return a * b m1 = max(len(str(a)), len(str(b))) m2 = m1 // 2 a1, a2 = divmod(a, 10**m2) b1, b2 = divmod(b, 10**m2) x = karatsuba(a2, b2) y = karatsuba((a1 + a2), (b1 + b2)) z = karatsuba(a1, b1) return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) def main(): print(karatsuba(15463, 23489)) if __name__ == "__main__": main()
Finds k'th lexicographic permutation in increasing order of 0,1,2,...n1 in On2 time. Examples: First permutation is always 0,1,2,...n kthpermutation0,5 0, 1, 2, 3, 4 The order of permutation of 0,1,2,3 is 0,1,2,3, 0,1,3,2, 0,2,1,3, 0,2,3,1, 0,3,1,2, 0,3,2,1, 1,0,2,3, 1,0,3,2, 1,2,0,3, 1,2,3,0, 1,3,0,2 kthpermutation10,4 1, 3, 0, 2 Factorails from 1! to n1! Find permutation
def kth_permutation(k, n): """ Finds k'th lexicographic permutation (in increasing order) of 0,1,2,...n-1 in O(n^2) time. Examples: First permutation is always 0,1,2,...n >>> kth_permutation(0,5) [0, 1, 2, 3, 4] The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3], [0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3], [1,2,3,0], [1,3,0,2] >>> kth_permutation(10,4) [1, 3, 0, 2] """ # Factorails from 1! to (n-1)! factorials = [1] for i in range(2, n): factorials.append(factorials[-1] * i) assert 0 <= k < factorials[-1] * n, "k out of bounds" permutation = [] elements = list(range(n)) # Find permutation while factorials: factorial = factorials.pop() number, k = divmod(k, factorial) permutation.append(elements[number]) elements.remove(elements[number]) permutation.append(elements[0]) return permutation if __name__ == "__main__": import doctest doctest.testmod()
Author: Abhijeeth S Reduces large number to a more manageable number res5, 7 4.892790030352132 res0, 5 0 res3, 0 1 res1, 5 Traceback most recent call last: ... ValueError: math domain error We use the relation xy ylog10x, where 10 is the base. Read two numbers from input and typecast them to int using map function. Here x is the base and y is the power. We find the log of each number, using the function res, which takes two arguments. We check for the largest number
# Author: Abhijeeth S import math def res(x, y): """ Reduces large number to a more manageable number >>> res(5, 7) 4.892790030352132 >>> res(0, 5) 0 >>> res(3, 0) 1 >>> res(-1, 5) Traceback (most recent call last): ... ValueError: math domain error """ if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.log10(x) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError("This should never happen") if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. prompt = "Enter the base and the power separated by a comma: " x1, y1 = map(int, input(prompt).split(",")) x2, y2 = map(int, input(prompt).split(",")) # We find the log of each number, using the function res(), which takes two # arguments. res1 = res(x1, y1) res2 = res(x2, y2) # We check for the largest number if res1 > res2: print("Largest number is", x1, "^", y1) elif res2 > res1: print("Largest number is", x2, "^", y2) else: print("Both are equal")
Find the least common multiple of two numbers. Learn more: https:en.wikipedia.orgwikiLeastcommonmultiple leastcommonmultipleslow5, 2 10 leastcommonmultipleslow12, 76 228 Find the least common multiple of two numbers. https:en.wikipedia.orgwikiLeastcommonmultipleUsingthegreatestcommondivisor leastcommonmultiplefast5,2 10 leastcommonmultiplefast12,76 228
import unittest from timeit import timeit from maths.greatest_common_divisor import greatest_common_divisor def least_common_multiple_slow(first_num: int, second_num: int) -> int: """ Find the least common multiple of two numbers. Learn more: https://en.wikipedia.org/wiki/Least_common_multiple >>> least_common_multiple_slow(5, 2) 10 >>> least_common_multiple_slow(12, 76) 228 """ max_num = first_num if first_num >= second_num else second_num common_mult = max_num while (common_mult % first_num > 0) or (common_mult % second_num > 0): common_mult += max_num return common_mult def least_common_multiple_fast(first_num: int, second_num: int) -> int: """ Find the least common multiple of two numbers. https://en.wikipedia.org/wiki/Least_common_multiple#Using_the_greatest_common_divisor >>> least_common_multiple_fast(5,2) 10 >>> least_common_multiple_fast(12,76) 228 """ return first_num // greatest_common_divisor(first_num, second_num) * second_num def benchmark(): setup = ( "from __main__ import least_common_multiple_slow, least_common_multiple_fast" ) print( "least_common_multiple_slow():", timeit("least_common_multiple_slow(1000, 999)", setup=setup), ) print( "least_common_multiple_fast():", timeit("least_common_multiple_fast(1000, 999)", setup=setup), ) class TestLeastCommonMultiple(unittest.TestCase): test_inputs = ( (10, 20), (13, 15), (4, 31), (10, 42), (43, 34), (5, 12), (12, 25), (10, 25), (6, 9), ) expected_results = (20, 195, 124, 210, 1462, 60, 300, 50, 18) def test_lcm_function(self): for i, (first_num, second_num) in enumerate(self.test_inputs): slow_result = least_common_multiple_slow(first_num, second_num) fast_result = least_common_multiple_fast(first_num, second_num) with self.subTest(i=i): assert slow_result == self.expected_results[i] assert fast_result == self.expected_results[i] if __name__ == "__main__": benchmark() unittest.main()
Approximates the arc length of a line segment by treating the curve as a sequence of linear lines and summing their lengths :param fnc: a function which defines a curve :param xstart: left end point to indicate the start of line segment :param xend: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases accuracy :return: a float representing the length of the curve def fx: ... return x flinelengthf, 0, 1, 10:.6f '1.414214' def fx: ... return 1 flinelengthf, 5.5, 4.5:.6f '10.000000' def fx: ... return math.sin5 x math.cos10 x x x10 flinelengthf, 0.0, 10.0, 10000:.6f '69.534930' Approximates curve as a sequence of linear lines and sums their length Increment step
from __future__ import annotations import math from collections.abc import Callable def line_length( fnc: Callable[[float], float], x_start: float, x_end: float, steps: int = 100, ) -> float: """ Approximates the arc length of a line segment by treating the curve as a sequence of linear lines and summing their lengths :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases accuracy :return: a float representing the length of the curve >>> def f(x): ... return x >>> f"{line_length(f, 0, 1, 10):.6f}" '1.414214' >>> def f(x): ... return 1 >>> f"{line_length(f, -5.5, 4.5):.6f}" '10.000000' >>> def f(x): ... return math.sin(5 * x) + math.cos(10 * x) + x * x/10 >>> f"{line_length(f, 0.0, 10.0, 10000):.6f}" '69.534930' """ x1 = x_start fx1 = fnc(x_start) length = 0.0 for _ in range(steps): # Approximates curve as a sequence of linear lines and sums their length x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) length += math.hypot(x2 - x1, fx2 - fx1) # Increment step x1 = x2 fx1 = fx2 return length if __name__ == "__main__": def f(x): return math.sin(10 * x) print("f(x) = sin(10 * x)") print("The length of the curve from x = -10 to x = 10 is:") i = 10 while i <= 100000: print(f"With {i} steps: {line_length(f, -10, 10, i)}") i *= 10
Liouville Lambda Function The Liouville Lambda function, denoted by n and n is 1 if n is the product of an even number of prime numbers, and 1 if it is the product of an odd number of primes. https:en.wikipedia.orgwikiLiouvillefunction Author : Akshay Dubey https:github.comitsAkshayDubey This functions takes an integer number as input. returns 1 if n has even number of prime factors and 1 otherwise. liouvillelambda10 1 liouvillelambda11 1 liouvillelambda0 Traceback most recent call last: ... ValueError: Input must be a positive integer liouvillelambda1 Traceback most recent call last: ... ValueError: Input must be a positive integer liouvillelambda11.0 Traceback most recent call last: ... TypeError: Input value of number11.0 must be an integer
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) from maths.prime_factors import prime_factors def liouville_lambda(number: int) -> int: """ This functions takes an integer number as input. returns 1 if n has even number of prime factors and -1 otherwise. >>> liouville_lambda(10) 1 >>> liouville_lambda(11) -1 >>> liouville_lambda(0) Traceback (most recent call last): ... ValueError: Input must be a positive integer >>> liouville_lambda(-1) Traceback (most recent call last): ... ValueError: Input must be a positive integer >>> liouville_lambda(11.0) Traceback (most recent call last): ... TypeError: Input value of [number=11.0] must be an integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: raise ValueError("Input must be a positive integer") return -1 if len(prime_factors(number)) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
In mathematics, the LucasLehmer test LLT is a primality test for Mersenne numbers. https:en.wikipedia.orgwikiLucasE28093Lehmerprimalitytest A Mersenne number is a number that is one less than a power of two. That is Mp 2p 1 https:en.wikipedia.orgwikiMersenneprime The LucasLehmer test is the primality test used by the Great Internet Mersenne Prime Search GIMPS to locate large primes. Primality test 2p 1 Return true if 2p 1 is prime lucaslehmertestp7 True lucaslehmertestp11 False M11 211 1 2047 23 89
# Primality test 2^p - 1 # Return true if 2^p - 1 is prime def lucas_lehmer_test(p: int) -> bool: """ >>> lucas_lehmer_test(p=7) True >>> lucas_lehmer_test(p=11) False # M_11 = 2^11 - 1 = 2047 = 23 * 89 """ if p < 2: raise ValueError("p should not be less than 2!") elif p == 2: return True s = 4 m = (1 << p) - 1 for _ in range(p - 2): s = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
https:en.wikipedia.orgwikiLucasnumber Returns the nth lucas number recursivelucasnumber1 1 recursivelucasnumber20 15127 recursivelucasnumber0 2 recursivelucasnumber25 167761 recursivelucasnumber1.5 Traceback most recent call last: ... TypeError: recursivelucasnumber accepts only integer arguments. Returns the nth lucas number dynamiclucasnumber1 1 dynamiclucasnumber20 15127 dynamiclucasnumber0 2 dynamiclucasnumber25 167761 dynamiclucasnumber1.5 Traceback most recent call last: ... TypeError: dynamiclucasnumber accepts only integer arguments.
def recursive_lucas_number(n_th_number: int) -> int: """ Returns the nth lucas number >>> recursive_lucas_number(1) 1 >>> recursive_lucas_number(20) 15127 >>> recursive_lucas_number(0) 2 >>> recursive_lucas_number(25) 167761 >>> recursive_lucas_number(-1.5) Traceback (most recent call last): ... TypeError: recursive_lucas_number accepts only integer arguments. """ if not isinstance(n_th_number, int): raise TypeError("recursive_lucas_number accepts only integer arguments.") if n_th_number == 0: return 2 if n_th_number == 1: return 1 return recursive_lucas_number(n_th_number - 1) + recursive_lucas_number( n_th_number - 2 ) def dynamic_lucas_number(n_th_number: int) -> int: """ Returns the nth lucas number >>> dynamic_lucas_number(1) 1 >>> dynamic_lucas_number(20) 15127 >>> dynamic_lucas_number(0) 2 >>> dynamic_lucas_number(25) 167761 >>> dynamic_lucas_number(-1.5) Traceback (most recent call last): ... TypeError: dynamic_lucas_number accepts only integer arguments. """ if not isinstance(n_th_number, int): raise TypeError("dynamic_lucas_number accepts only integer arguments.") a, b = 2, 1 for _ in range(n_th_number): a, b = b, a + b return a if __name__ == "__main__": from doctest import testmod testmod() n = int(input("Enter the number of terms in lucas series:\n").strip()) print("Using recursive function to calculate lucas series:") print(" ".join(str(recursive_lucas_number(i)) for i in range(n))) print("\nUsing dynamic function to calculate lucas series:") print(" ".join(str(dynamic_lucas_number(i)) for i in range(n)))
https:en.wikipedia.orgwikiTaylorseriesTrigonometricfunctions Finds the maclaurin approximation of sin :param theta: the angle to which sin is found :param accuracy: the degree of accuracy wanted minimum :return: the value of sine in radians from math import isclose, sin allisclosemaclaurinsinx, 50, sinx for x in range25, 25 True maclaurinsin10 0.5440211108893691 maclaurinsin10 0.5440211108893704 maclaurinsin10, 15 0.544021110889369 maclaurinsin10, 15 0.5440211108893704 maclaurinsin10 Traceback most recent call last: ... ValueError: maclaurinsin requires either an int or float for theta maclaurinsin10, 30 Traceback most recent call last: ... ValueError: maclaurinsin requires a positive int for accuracy maclaurinsin10, 30.5 Traceback most recent call last: ... ValueError: maclaurinsin requires a positive int for accuracy maclaurinsin10, 30 Traceback most recent call last: ... ValueError: maclaurinsin requires a positive int for accuracy Finds the maclaurin approximation of cos :param theta: the angle to which cos is found :param accuracy: the degree of accuracy wanted :return: the value of cosine in radians from math import isclose, cos allisclosemaclaurincosx, 50, cosx for x in range25, 25 True maclaurincos5 0.2836621854632268 maclaurincos5 0.2836621854632265 maclaurincos10, 15 0.8390715290764524 maclaurincos10, 15 0.8390715290764521 maclaurincos10 Traceback most recent call last: ... ValueError: maclaurincos requires either an int or float for theta maclaurincos10, 30 Traceback most recent call last: ... ValueError: maclaurincos requires a positive int for accuracy maclaurincos10, 30.5 Traceback most recent call last: ... ValueError: maclaurincos requires a positive int for accuracy maclaurincos10, 30 Traceback most recent call last: ... ValueError: maclaurincos requires a positive int for accuracy
from math import factorial, pi def maclaurin_sin(theta: float, accuracy: int = 30) -> float: """ Finds the maclaurin approximation of sin :param theta: the angle to which sin is found :param accuracy: the degree of accuracy wanted minimum :return: the value of sine in radians >>> from math import isclose, sin >>> all(isclose(maclaurin_sin(x, 50), sin(x)) for x in range(-25, 25)) True >>> maclaurin_sin(10) -0.5440211108893691 >>> maclaurin_sin(-10) 0.5440211108893704 >>> maclaurin_sin(10, 15) -0.544021110889369 >>> maclaurin_sin(-10, 15) 0.5440211108893704 >>> maclaurin_sin("10") Traceback (most recent call last): ... ValueError: maclaurin_sin() requires either an int or float for theta >>> maclaurin_sin(10, -30) Traceback (most recent call last): ... ValueError: maclaurin_sin() requires a positive int for accuracy >>> maclaurin_sin(10, 30.5) Traceback (most recent call last): ... ValueError: maclaurin_sin() requires a positive int for accuracy >>> maclaurin_sin(10, "30") Traceback (most recent call last): ... ValueError: maclaurin_sin() requires a positive int for accuracy """ if not isinstance(theta, (int, float)): raise ValueError("maclaurin_sin() requires either an int or float for theta") if not isinstance(accuracy, int) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy") theta = float(theta) div = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1) for r in range(accuracy) ) def maclaurin_cos(theta: float, accuracy: int = 30) -> float: """ Finds the maclaurin approximation of cos :param theta: the angle to which cos is found :param accuracy: the degree of accuracy wanted :return: the value of cosine in radians >>> from math import isclose, cos >>> all(isclose(maclaurin_cos(x, 50), cos(x)) for x in range(-25, 25)) True >>> maclaurin_cos(5) 0.2836621854632268 >>> maclaurin_cos(-5) 0.2836621854632265 >>> maclaurin_cos(10, 15) -0.8390715290764524 >>> maclaurin_cos(-10, 15) -0.8390715290764521 >>> maclaurin_cos("10") Traceback (most recent call last): ... ValueError: maclaurin_cos() requires either an int or float for theta >>> maclaurin_cos(10, -30) Traceback (most recent call last): ... ValueError: maclaurin_cos() requires a positive int for accuracy >>> maclaurin_cos(10, 30.5) Traceback (most recent call last): ... ValueError: maclaurin_cos() requires a positive int for accuracy >>> maclaurin_cos(10, "30") Traceback (most recent call last): ... ValueError: maclaurin_cos() requires a positive int for accuracy """ if not isinstance(theta, (int, float)): raise ValueError("maclaurin_cos() requires either an int or float for theta") if not isinstance(accuracy, int) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy") theta = float(theta) div = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r) for r in range(accuracy)) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(10)) print(maclaurin_sin(-10)) print(maclaurin_sin(10, 15)) print(maclaurin_sin(-10, 15)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(10, 15)) print(maclaurin_cos(-10, 15))
Expectts two list of numbers representing two points in the same ndimensional space https:en.wikipedia.orgwikiTaxicabgeometry manhattandistance1,1, 2,2 2.0 manhattandistance1.5,1.5, 2,2 1.0 manhattandistance1.5,1.5, 2.5,2 1.5 manhattandistance3, 3, 3, 0, 0, 0 9.0 manhattandistance1,1, None Traceback most recent call last: ... ValueError: Missing an input manhattandistance1,1, 2, 2, 2 Traceback most recent call last: ... ValueError: Both points must be in the same ndimensional space manhattandistance1,one, 2, 2, 2 Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found str manhattandistance1, 2, 2, 2 Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found int manhattandistance1,1, notalist Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found str validatepointNone Traceback most recent call last: ... ValueError: Missing an input validatepoint1,one Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found str validatepoint1 Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found int validatepointnotalist Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found str Version with one liner manhattandistanceoneliner1,1, 2,2 2.0 manhattandistanceoneliner1.5,1.5, 2,2 1.0 manhattandistanceoneliner1.5,1.5, 2.5,2 1.5 manhattandistanceoneliner3, 3, 3, 0, 0, 0 9.0 manhattandistanceoneliner1,1, None Traceback most recent call last: ... ValueError: Missing an input manhattandistanceoneliner1,1, 2, 2, 2 Traceback most recent call last: ... ValueError: Both points must be in the same ndimensional space manhattandistanceoneliner1,one, 2, 2, 2 Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found str manhattandistanceoneliner1, 2, 2, 2 Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found int manhattandistanceoneliner1,1, notalist Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found str
def manhattan_distance(point_a: list, point_b: list) -> float: """ Expectts two list of numbers representing two points in the same n-dimensional space https://en.wikipedia.org/wiki/Taxicab_geometry >>> manhattan_distance([1,1], [2,2]) 2.0 >>> manhattan_distance([1.5,1.5], [2,2]) 1.0 >>> manhattan_distance([1.5,1.5], [2.5,2]) 1.5 >>> manhattan_distance([-3, -3, -3], [0, 0, 0]) 9.0 >>> manhattan_distance([1,1], None) Traceback (most recent call last): ... ValueError: Missing an input >>> manhattan_distance([1,1], [2, 2, 2]) Traceback (most recent call last): ... ValueError: Both points must be in the same n-dimensional space >>> manhattan_distance([1,"one"], [2, 2, 2]) Traceback (most recent call last): ... TypeError: Expected a list of numbers as input, found str >>> manhattan_distance(1, [2, 2, 2]) Traceback (most recent call last): ... TypeError: Expected a list of numbers as input, found int >>> manhattan_distance([1,1], "not_a_list") Traceback (most recent call last): ... TypeError: Expected a list of numbers as input, found str """ _validate_point(point_a) _validate_point(point_b) if len(point_a) != len(point_b): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(a - b) for a, b in zip(point_a, point_b))) def _validate_point(point: list[float]) -> None: """ >>> _validate_point(None) Traceback (most recent call last): ... ValueError: Missing an input >>> _validate_point([1,"one"]) Traceback (most recent call last): ... TypeError: Expected a list of numbers as input, found str >>> _validate_point(1) Traceback (most recent call last): ... TypeError: Expected a list of numbers as input, found int >>> _validate_point("not_a_list") Traceback (most recent call last): ... TypeError: Expected a list of numbers as input, found str """ if point: if isinstance(point, list): for item in point: if not isinstance(item, (int, float)): msg = ( "Expected a list of numbers as input, found " f"{type(item).__name__}" ) raise TypeError(msg) else: msg = f"Expected a list of numbers as input, found {type(point).__name__}" raise TypeError(msg) else: raise ValueError("Missing an input") def manhattan_distance_one_liner(point_a: list, point_b: list) -> float: """ Version with one liner >>> manhattan_distance_one_liner([1,1], [2,2]) 2.0 >>> manhattan_distance_one_liner([1.5,1.5], [2,2]) 1.0 >>> manhattan_distance_one_liner([1.5,1.5], [2.5,2]) 1.5 >>> manhattan_distance_one_liner([-3, -3, -3], [0, 0, 0]) 9.0 >>> manhattan_distance_one_liner([1,1], None) Traceback (most recent call last): ... ValueError: Missing an input >>> manhattan_distance_one_liner([1,1], [2, 2, 2]) Traceback (most recent call last): ... ValueError: Both points must be in the same n-dimensional space >>> manhattan_distance_one_liner([1,"one"], [2, 2, 2]) Traceback (most recent call last): ... TypeError: Expected a list of numbers as input, found str >>> manhattan_distance_one_liner(1, [2, 2, 2]) Traceback (most recent call last): ... TypeError: Expected a list of numbers as input, found int >>> manhattan_distance_one_liner([1,1], "not_a_list") Traceback (most recent call last): ... TypeError: Expected a list of numbers as input, found str """ _validate_point(point_a) _validate_point(point_b) if len(point_a) != len(point_b): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(x - y) for x, y in zip(point_a, point_b))) if __name__ == "__main__": import doctest doctest.testmod()
Matrix Exponentiation import timeit class Matrix: def initself, arg: if isinstancearg, list: Initializes a matrix identical to the one provided. self.t arg self.n lenarg else: Initializes a square matrix of the given size and set values to zero. self.n arg self.t 0 for in rangeself.n for in rangeself.n def mulself, b: matrix Matrixself.n for i in rangeself.n: for j in rangeself.n: for k in rangeself.n: matrix.tij self.tik b.tkj return matrix def modularexponentiationa, b: matrix Matrix1, 0, 0, 1 while b 0: if b 1: matrix a a a b 1 return matrix def fibonacciwithmatrixexponentiationn, f1, f2: Trivial Cases if n 1: return f1 elif n 2: return f2 matrix Matrix1, 1, 1, 0 matrix modularexponentiationmatrix, n 2 return f2 matrix.t00 f1 matrix.t01 def simplefibonaccin, f1, f2: Trivial Cases if n 1: return f1 elif n 2: return f2 fn1 f1 fn2 f2 n 2 while n 0: fn1, fn2 fn1 fn2, fn1 n 1 return fn1 def matrixexponentiationtime: setup from random import randint from main import fibonacciwithmatrixexponentiation code simplefibonaccirandint1,70000, 1, 1 exectime timeit.timeitsetupsetup, stmtcode, number100 print Without matrix exponentiation the average execution time is , exectime 100 return exectime def main: matrixexponentiationtime simplefibonaccitime if name main: main
import timeit """ Matrix Exponentiation is a technique to solve linear recurrences in logarithmic time. You read more about it here: https://zobayer.blogspot.com/2010/11/matrix-exponentiation.html https://www.hackerearth.com/practice/notes/matrix-exponentiation-1/ """ class Matrix: def __init__(self, arg): if isinstance(arg, list): # Initializes a matrix identical to the one provided. self.t = arg self.n = len(arg) else: # Initializes a square matrix of the given size and set values to zero. self.n = arg self.t = [[0 for _ in range(self.n)] for _ in range(self.n)] def __mul__(self, b): matrix = Matrix(self.n) for i in range(self.n): for j in range(self.n): for k in range(self.n): matrix.t[i][j] += self.t[i][k] * b.t[k][j] return matrix def modular_exponentiation(a, b): matrix = Matrix([[1, 0], [0, 1]]) while b > 0: if b & 1: matrix *= a a *= a b >>= 1 return matrix def fibonacci_with_matrix_exponentiation(n, f1, f2): # Trivial Cases if n == 1: return f1 elif n == 2: return f2 matrix = Matrix([[1, 1], [1, 0]]) matrix = modular_exponentiation(matrix, n - 2) return f2 * matrix.t[0][0] + f1 * matrix.t[0][1] def simple_fibonacci(n, f1, f2): # Trivial Cases if n == 1: return f1 elif n == 2: return f2 fn_1 = f1 fn_2 = f2 n -= 2 while n > 0: fn_1, fn_2 = fn_1 + fn_2, fn_1 n -= 1 return fn_1 def matrix_exponentiation_time(): setup = """ from random import randint from __main__ import fibonacci_with_matrix_exponentiation """ code = "fibonacci_with_matrix_exponentiation(randint(1,70000), 1, 1)" exec_time = timeit.timeit(setup=setup, stmt=code, number=100) print("With matrix exponentiation the average execution time is ", exec_time / 100) return exec_time def simple_fibonacci_time(): setup = """ from random import randint from __main__ import simple_fibonacci """ code = "simple_fibonacci(randint(1,70000), 1, 1)" exec_time = timeit.timeit(setup=setup, stmt=code, number=100) print( "Without matrix exponentiation the average execution time is ", exec_time / 100 ) return exec_time def main(): matrix_exponentiation_time() simple_fibonacci_time() if __name__ == "__main__": main()
Given an array of integer elements and an integer 'k', we are required to find the maximum sum of 'k' consecutive elements in the array. Instead of using a nested for loop, in a Brute force approach we will use a technique called 'Window sliding technique' where the nested loops can be converted to a single loop to reduce time complexity. Returns the maximum sum of k consecutive elements arr 1, 4, 2, 10, 2, 3, 1, 0, 20 k 4 maxsuminarrayarr, k 24 k 10 maxsuminarrayarr,k Traceback most recent call last: ... ValueError: Invalid Input arr 1, 4, 2, 10, 2, 13, 1, 0, 2 k 4 maxsuminarrayarr, k 27
from __future__ import annotations def max_sum_in_array(array: list[int], k: int) -> int: """ Returns the maximum sum of k consecutive elements >>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20] >>> k = 4 >>> max_sum_in_array(arr, k) 24 >>> k = 10 >>> max_sum_in_array(arr,k) Traceback (most recent call last): ... ValueError: Invalid Input >>> arr = [1, 4, 2, 10, 2, 13, 1, 0, 2] >>> k = 4 >>> max_sum_in_array(arr, k) 27 """ if len(array) < k or k < 0: raise ValueError("Invalid Input") max_sum = current_sum = sum(array[:k]) for i in range(len(array) - k): current_sum = current_sum - array[i] + array[i + k] max_sum = max(max_sum, current_sum) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() array = [randint(-1000, 1000) for i in range(100)] k = randint(0, 110) print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
medianoftwoarrays1, 2, 3 2 medianoftwoarrays0, 1.1, 2.5, 1 0.5 medianoftwoarrays, 2.5, 1 1.75 medianoftwoarrays, 0 0 medianoftwoarrays, Traceback most recent call last: ... IndexError: list index out of range
from __future__ import annotations def median_of_two_arrays(nums1: list[float], nums2: list[float]) -> float: """ >>> median_of_two_arrays([1, 2], [3]) 2 >>> median_of_two_arrays([0, -1.1], [2.5, 1]) 0.5 >>> median_of_two_arrays([], [2.5, 1]) 1.75 >>> median_of_two_arrays([], [0]) 0 >>> median_of_two_arrays([], []) Traceback (most recent call last): ... IndexError: list index out of range """ all_numbers = sorted(nums1 + nums2) div, mod = divmod(len(all_numbers), 2) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() array_1 = [float(x) for x in input("Enter the elements of first array: ").split()] array_2 = [float(x) for x in input("Enter the elements of second array: ").split()] print(f"The median of two arrays is: {median_of_two_arrays(array_1, array_2)}")
This function calculates the Minkowski distance for a given order between two ndimensional points represented as lists. For the case of order 1, the Minkowski distance degenerates to the Manhattan distance. For order 2, the usual Euclidean distance is obtained. https:en.wikipedia.orgwikiMinkowskidistance Note: due to floating point calculation errors the output of this function may be inaccurate. minkowskidistance1.0, 1.0, 2.0, 2.0, 1 2.0 minkowskidistance1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 2 8.0 import numpy as np np.isclose5.0, minkowskidistance5.0, 0.0, 3 True minkowskidistance1.0, 2.0, 1 Traceback most recent call last: ... ValueError: The order must be greater than or equal to 1. minkowskidistance1.0, 1.0, 2.0, 1 Traceback most recent call last: ... ValueError: Both points must have the same dimension.
def minkowski_distance( point_a: list[float], point_b: list[float], order: int, ) -> float: """ This function calculates the Minkowski distance for a given order between two n-dimensional points represented as lists. For the case of order = 1, the Minkowski distance degenerates to the Manhattan distance. For order = 2, the usual Euclidean distance is obtained. https://en.wikipedia.org/wiki/Minkowski_distance Note: due to floating point calculation errors the output of this function may be inaccurate. >>> minkowski_distance([1.0, 1.0], [2.0, 2.0], 1) 2.0 >>> minkowski_distance([1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], 2) 8.0 >>> import numpy as np >>> np.isclose(5.0, minkowski_distance([5.0], [0.0], 3)) True >>> minkowski_distance([1.0], [2.0], -1) Traceback (most recent call last): ... ValueError: The order must be greater than or equal to 1. >>> minkowski_distance([1.0], [1.0, 2.0], 1) Traceback (most recent call last): ... ValueError: Both points must have the same dimension. """ if order < 1: raise ValueError("The order must be greater than or equal to 1.") if len(point_a) != len(point_b): raise ValueError("Both points must have the same dimension.") return sum(abs(a - b) ** order for a, b in zip(point_a, point_b)) ** (1 / order) if __name__ == "__main__": import doctest doctest.testmod()
References: https:en.wikipedia.orgwikiMC3B6biusfunction References: wikipedia:square free number psfblack : True ruff : True Mobius function mobius24 0 mobius1 1 mobius'asd' Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'str' mobius10400 0 mobius10400 1 mobius1424 1 mobius1, '2', 2.0 Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'list'
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def mobius(n: int) -> int: """ Mobius function >>> mobius(24) 0 >>> mobius(-1) 1 >>> mobius('asd') Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> mobius(10**400) 0 >>> mobius(10**-400) 1 >>> mobius(-1424) 1 >>> mobius([1, '2', 2.0]) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ factors = prime_factors(n) if is_square_free(factors): return -1 if len(factors) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
Modular Division : An efficient algorithm for dividing b by a modulo n. GCD Greatest Common Divisor or HCF Highest Common Factor Given three integers a, b, and n, such that gcda,n1 and n1, the algorithm should return an integer x such that 0xn1, and baxmodn that is, baxmodn. Theorem: a has a multiplicative inverse modulo n iff gcda,n 1 This find x ba1 mod n Uses ExtendedEuclid to find the inverse of a modulardivision4,8,5 2 modulardivision3,8,5 1 modulardivision4, 11, 5 4 This function find the inverses of a i.e., a1 invertmodulo2, 5 3 invertmodulo8,7 1 Finding Modular division using invertmodulo This function used the above inversion of a to find x ba1mod n modulardivision24,8,5 2 modulardivision23,8,5 1 modulardivision24, 11, 5 4 Extended Euclid's Algorithm : If d divides a and b and d ax by for integers x and y, then d gcda,b extendedgcd10, 6 2, 1, 2 extendedgcd7, 5 1, 2, 3 extendedgcd function is used when d gcda,b is required in output Extended Euclid extendedeuclid10, 6 1, 2 extendedeuclid7, 5 2, 3 Euclid's Lemma : d divides a and b, if and only if d divides ab and b Euclid's Algorithm greatestcommondivisor7,5 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or coprime if the only positive integer factor that divides both of them is 1 i.e., gcda,b 1. greatestcommondivisor121, 11 11
from __future__ import annotations def modular_division(a: int, b: int, n: int) -> int: """ Modular Division : An efficient algorithm for dividing b by a modulo n. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should return an integer x such that 0≤x≤n−1, and b/a=x(modn) (that is, b=ax(modn)). Theorem: a has a multiplicative inverse modulo n iff gcd(a,n) = 1 This find x = b*a^(-1) mod n Uses ExtendedEuclid to find the inverse of a >>> modular_division(4,8,5) 2 >>> modular_division(3,8,5) 1 >>> modular_division(4, 11, 5) 4 """ assert n > 1 assert a > 0 assert greatest_common_divisor(a, n) == 1 (d, t, s) = extended_gcd(n, a) # Implemented below x = (b * s) % n return x def invert_modulo(a: int, n: int) -> int: """ This function find the inverses of a i.e., a^(-1) >>> invert_modulo(2, 5) 3 >>> invert_modulo(8,7) 1 """ (b, x) = extended_euclid(a, n) # Implemented below if b < 0: b = (b % n + n) % n return b # ------------------ Finding Modular division using invert_modulo ------------------- def modular_division2(a: int, b: int, n: int) -> int: """ This function used the above inversion of a to find x = (b*a^(-1))mod n >>> modular_division2(4,8,5) 2 >>> modular_division2(3,8,5) 1 >>> modular_division2(4, 11, 5) 4 """ s = invert_modulo(a, n) x = (b * s) % n return x def extended_gcd(a: int, b: int) -> tuple[int, int, int]: """ Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) ** extended_gcd function is used when d = gcd(a,b) is required in output """ assert a >= 0 assert b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 assert b % d == 0 assert d == a * x + b * y return (d, x, y) def extended_euclid(a: int, b: int) -> tuple[int, int]: """ Extended Euclid >>> extended_euclid(10, 6) (-1, 2) >>> extended_euclid(7, 5) (-2, 3) """ if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y) def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1. >>> greatest_common_divisor(121, 11) 11 """ if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b if __name__ == "__main__": from doctest import testmod testmod(name="modular_division", verbose=True) testmod(name="modular_division2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="extended_euclid", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
Modular Exponential. Modular exponentiation is a type of exponentiation performed over a modulus. For more explanation, please check https:en.wikipedia.orgwikiModularexponentiation Calculate Modular Exponential. def modularexponentialbase: int, power: int, mod: int: if power 0: return 1 base mod result 1 while power 0: if power 1: result result base mod power power 1 base base base mod return result def main:
"""Calculate Modular Exponential.""" def modular_exponential(base: int, power: int, mod: int): """ >>> modular_exponential(5, 0, 10) 1 >>> modular_exponential(2, 8, 7) 4 >>> modular_exponential(3, -2, 9) -1 """ if power < 0: return -1 base %= mod result = 1 while power > 0: if power & 1: result = (result * base) % mod power = power >> 1 base = (base * base) % mod return result def main(): """Call Modular Exponential Function.""" print(modular_exponential(3, 200, 13)) if __name__ == "__main__": import doctest doctest.testmod() main()
author: MatteoRaso An implementation of the Monte Carlo method used to find pi. 1. Draw a 2x2 square centred at 0,0. 2. Inscribe a circle within the square. 3. For each iteration, place a dot anywhere in the square. a. Record the number of dots within the circle. 4. After all the dots are placed, divide the dots in the circle by the total. 5. Multiply this value by 4 to get your estimate of pi. 6. Print the estimated and numpy value of pi A local function to see if a dot lands in the circle. Our circle has a radius of 1, so a distance greater than 1 would land outside the circle. The proportion of guesses that landed in the circle The ratio of the area for circle to square is pi4. An implementation of the Monte Carlo method to find area under a single variable nonnegative realvalued continuous function, say fx, where x lies within a continuous bounded interval, say minvalue, maxvalue, where minvalue and maxvalue are finite numbers 1. Let x be a uniformly distributed random variable between minvalue to maxvalue 2. Expected value of fx integrate fx from minvalue to maxvaluemaxvalue minvalue 3. Finding expected value of fx: a. Repeatedly draw x from uniform distribution b. Evaluate fx at each of the drawn x values c. Expected value average of the function evaluations 4. Estimated value of integral Expected value maxvalue minvalue 5. Returns estimated value Checks estimation error for areaundercurveestimator function for fx x where x lies within minvalue to maxvalue 1. Calls areaundercurveestimator function 2. Compares with the expected value 3. Prints estimated, expected and error value Represents identity function functiontointegratex for x in 2.0, 1.0, 0.0, 1.0, 2.0 2.0, 1.0, 0.0, 1.0, 2.0 Area under curve y sqrt4 x2 where x lies in 0 to 2 is equal to pi Represents semicircle with radius 2 functiontointegratex for x in 2.0, 0.0, 2.0 0.0, 2.0, 0.0
from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def pi_estimator(iterations: int): """ An implementation of the Monte Carlo method used to find pi. 1. Draw a 2x2 square centred at (0,0). 2. Inscribe a circle within the square. 3. For each iteration, place a dot anywhere in the square. a. Record the number of dots within the circle. 4. After all the dots are placed, divide the dots in the circle by the total. 5. Multiply this value by 4 to get your estimate of pi. 6. Print the estimated and numpy value of pi """ # A local function to see if a dot lands in the circle. def is_in_circle(x: float, y: float) -> bool: distance_from_centre = sqrt((x**2) + (y**2)) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle proportion = mean( int(is_in_circle(uniform(-1.0, 1.0), uniform(-1.0, 1.0))) for _ in range(iterations) ) # The ratio of the area for circle to square is pi/4. pi_estimate = proportion * 4 print(f"The estimated value of pi is {pi_estimate}") print(f"The numpy value of pi is {pi}") print(f"The total error is {abs(pi - pi_estimate)}") def area_under_curve_estimator( iterations: int, function_to_integrate: Callable[[float], float], min_value: float = 0.0, max_value: float = 1.0, ) -> float: """ An implementation of the Monte Carlo method to find area under a single variable non-negative real-valued continuous function, say f(x), where x lies within a continuous bounded interval, say [min_value, max_value], where min_value and max_value are finite numbers 1. Let x be a uniformly distributed random variable between min_value to max_value 2. Expected value of f(x) = (integrate f(x) from min_value to max_value)/(max_value - min_value) 3. Finding expected value of f(x): a. Repeatedly draw x from uniform distribution b. Evaluate f(x) at each of the drawn x values c. Expected value = average of the function evaluations 4. Estimated value of integral = Expected value * (max_value - min_value) 5. Returns estimated value """ return mean( function_to_integrate(uniform(min_value, max_value)) for _ in range(iterations) ) * (max_value - min_value) def area_under_line_estimator_check( iterations: int, min_value: float = 0.0, max_value: float = 1.0 ) -> None: """ Checks estimation error for area_under_curve_estimator function for f(x) = x where x lies within min_value to max_value 1. Calls "area_under_curve_estimator" function 2. Compares with the expected value 3. Prints estimated, expected and error value """ def identity_function(x: float) -> float: """ Represents identity function >>> [function_to_integrate(x) for x in [-2.0, -1.0, 0.0, 1.0, 2.0]] [-2.0, -1.0, 0.0, 1.0, 2.0] """ return x estimated_value = area_under_curve_estimator( iterations, identity_function, min_value, max_value ) expected_value = (max_value * max_value - min_value * min_value) / 2 print("******************") print(f"Estimating area under y=x where x varies from {min_value} to {max_value}") print(f"Estimated value is {estimated_value}") print(f"Expected value is {expected_value}") print(f"Total error is {abs(estimated_value - expected_value)}") print("******************") def pi_estimator_using_area_under_curve(iterations: int) -> None: """ Area under curve y = sqrt(4 - x^2) where x lies in 0 to 2 is equal to pi """ def function_to_integrate(x: float) -> float: """ Represents semi-circle with radius 2 >>> [function_to_integrate(x) for x in [-2.0, 0.0, 2.0]] [0.0, 2.0, 0.0] """ return sqrt(4.0 - x * x) estimated_value = area_under_curve_estimator( iterations, function_to_integrate, 0.0, 2.0 ) print("******************") print("Estimating pi using area_under_curve_estimator") print(f"Estimated value is {estimated_value}") print(f"Expected value is {pi}") print(f"Total error is {abs(estimated_value - pi)}") print("******************") if __name__ == "__main__": import doctest doctest.testmod()
Initialize a six sided dice self.sides listrange1, Dice.NUMSIDES 1 def rollself: return random.choiceself.sides def throwdicenumthrows: int, numdice: int 2 listfloat: dices Dice for i in rangenumdice countofsum 0 lendices Dice.NUMSIDES 1 for in rangenumthrows: countofsumsumdice.roll for dice in dices 1 probability roundcount 100 numthrows, 2 for count in countofsum return probabilitynumdice: remove probability of sums that never appear if name main: import doctest doctest.testmod
from __future__ import annotations import random class Dice: NUM_SIDES = 6 def __init__(self): """Initialize a six sided dice""" self.sides = list(range(1, Dice.NUM_SIDES + 1)) def roll(self): return random.choice(self.sides) def throw_dice(num_throws: int, num_dice: int = 2) -> list[float]: """ Return probability list of all possible sums when throwing dice. >>> random.seed(0) >>> throw_dice(10, 1) [10.0, 0.0, 30.0, 50.0, 10.0, 0.0] >>> throw_dice(100, 1) [19.0, 17.0, 17.0, 11.0, 23.0, 13.0] >>> throw_dice(1000, 1) [18.8, 15.5, 16.3, 17.6, 14.2, 17.6] >>> throw_dice(10000, 1) [16.35, 16.89, 16.93, 16.6, 16.52, 16.71] >>> throw_dice(10000, 2) [2.74, 5.6, 7.99, 11.26, 13.92, 16.7, 14.44, 10.63, 8.05, 5.92, 2.75] """ dices = [Dice() for i in range(num_dice)] count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1) for _ in range(num_throws): count_of_sum[sum(dice.roll() for dice in dices)] += 1 probability = [round((count * 100) / num_throws, 2) for count in count_of_sum] return probability[num_dice:] # remove probability of sums that never appear if __name__ == "__main__": import doctest doctest.testmod()
Find the number of digits in a number. numdigits12345 5 numdigits123 3 numdigits0 1 numdigits1 1 numdigits123456 6 numdigits'123' Raises a TypeError for noninteger input Traceback most recent call last: ... TypeError: Input must be an integer Find the number of digits in a number. abs is used as logarithm for negative numbers is not defined. numdigitsfast12345 5 numdigitsfast123 3 numdigitsfast0 1 numdigitsfast1 1 numdigitsfast123456 6 numdigits'123' Raises a TypeError for noninteger input Traceback most recent call last: ... TypeError: Input must be an integer Find the number of digits in a number. abs is used for negative numbers numdigitsfaster12345 5 numdigitsfaster123 3 numdigitsfaster0 1 numdigitsfaster1 1 numdigitsfaster123456 6 numdigits'123' Raises a TypeError for noninteger input Traceback most recent call last: ... TypeError: Input must be an integer Benchmark multiple functions, with three different length int values.
import math from timeit import timeit def num_digits(n: int) -> int: """ Find the number of digits in a number. >>> num_digits(12345) 5 >>> num_digits(123) 3 >>> num_digits(0) 1 >>> num_digits(-1) 1 >>> num_digits(-123456) 6 >>> num_digits('123') # Raises a TypeError for non-integer input Traceback (most recent call last): ... TypeError: Input must be an integer """ if not isinstance(n, int): raise TypeError("Input must be an integer") digits = 0 n = abs(n) while True: n = n // 10 digits += 1 if n == 0: break return digits def num_digits_fast(n: int) -> int: """ Find the number of digits in a number. abs() is used as logarithm for negative numbers is not defined. >>> num_digits_fast(12345) 5 >>> num_digits_fast(123) 3 >>> num_digits_fast(0) 1 >>> num_digits_fast(-1) 1 >>> num_digits_fast(-123456) 6 >>> num_digits('123') # Raises a TypeError for non-integer input Traceback (most recent call last): ... TypeError: Input must be an integer """ if not isinstance(n, int): raise TypeError("Input must be an integer") return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1) def num_digits_faster(n: int) -> int: """ Find the number of digits in a number. abs() is used for negative numbers >>> num_digits_faster(12345) 5 >>> num_digits_faster(123) 3 >>> num_digits_faster(0) 1 >>> num_digits_faster(-1) 1 >>> num_digits_faster(-123456) 6 >>> num_digits('123') # Raises a TypeError for non-integer input Traceback (most recent call last): ... TypeError: Input must be an integer """ if not isinstance(n, int): raise TypeError("Input must be an integer") return len(str(abs(n))) def benchmark() -> None: """ Benchmark multiple functions, with three different length int values. """ from collections.abc import Callable def benchmark_a_function(func: Callable, value: int) -> None: call = f"{func.__name__}({value})" timing = timeit(f"__main__.{call}", setup="import __main__") print(f"{call}: {func(value)} -- {timing} seconds") for value in (262144, 1125899906842624, 1267650600228229401496703205376): for func in (num_digits, num_digits_fast, num_digits_faster): benchmark_a_function(func, value) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
Use the AdamsBashforth methods to solve Ordinary Differential Equations. https:en.wikipedia.orgwikiLinearmultistepmethod Author : Ravi Kumar args: func: An ordinary differential equation ODE as function of x and y. xinitials: List containing initial required values of x. yinitials: List containing initial required values of y. stepsize: The increment value of x. xfinal: The final value of x. Returns: Solution of y at each nodal point def fx, y: ... return x y AdamsBashforthf, 0, 0.2, 0.4, 0, 0.2, 1, 0.2, 1 doctest: ELLIPSIS AdamsBashforthfunc..., xinitials0, 0.2, 0.4, yinitials0, 0.2, 1, step... AdamsBashforthf, 0, 0.2, 1, 0, 0, 0.04, 0.2, 1.step2 Traceback most recent call last: ... ValueError: The final value of x must be greater than the initial values of x. AdamsBashforthf, 0, 0.2, 0.3, 0, 0, 0.04, 0.2, 1.step3 Traceback most recent call last: ... ValueError: xvalues must be equally spaced according to step size. AdamsBashforthf,0,0.2,0.4,0.6,0.8,0,0,0.04,0.128,0.307,0.2,1.step5 Traceback most recent call last: ... ValueError: Step size must be positive. def fx, y: ... return x AdamsBashforthf, 0, 0.2, 0, 0, 0.2, 1.step2 array0. , 0. , 0.06, 0.16, 0.3 , 0.48 AdamsBashforthf, 0, 0.2, 0.4, 0, 0, 0.04, 0.2, 1.step2 Traceback most recent call last: ... ValueError: Insufficient initial points information. def fx, y: ... return x y y AdamsBashforthf, 0, 0.2, 0.4, 0, 0, 0.04, 0.2, 1.step3 y3 0.15533333333333332 AdamsBashforthf, 0, 0.2, 0, 0, 0.2, 1.step3 Traceback most recent call last: ... ValueError: Insufficient initial points information. def fx,y: ... return x y y AdamsBashforth ... f, 0, 0.2, 0.4, 0.6, 0, 0, 0.04, 0.128, 0.2, 1.step4 y4 0.30699999999999994 y5 0.5771083333333333 AdamsBashforthf, 0, 0.2, 0.4, 0, 0, 0.04, 0.2, 1.step4 Traceback most recent call last: ... ValueError: Insufficient initial points information. def fx,y: ... return x y y AdamsBashforth ... f, 0, 0.2, 0.4, 0.6, 0.8, 0, 0.02140, 0.02140, 0.22211, 0.42536, ... 0.2, 1.step5 y1 0.05436839444444452 AdamsBashforthf, 0, 0.2, 0.4, 0, 0, 0.04, 0.2, 1.step5 Traceback most recent call last: ... ValueError: Insufficient initial points information.
from collections.abc import Callable from dataclasses import dataclass import numpy as np @dataclass class AdamsBashforth: """ args: func: An ordinary differential equation (ODE) as function of x and y. x_initials: List containing initial required values of x. y_initials: List containing initial required values of y. step_size: The increment value of x. x_final: The final value of x. Returns: Solution of y at each nodal point >>> def f(x, y): ... return x + y >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0.2, 1], 0.2, 1) # doctest: +ELLIPSIS AdamsBashforth(func=..., x_initials=[0, 0.2, 0.4], y_initials=[0, 0.2, 1], step...) >>> AdamsBashforth(f, [0, 0.2, 1], [0, 0, 0.04], 0.2, 1).step_2() Traceback (most recent call last): ... ValueError: The final value of x must be greater than the initial values of x. >>> AdamsBashforth(f, [0, 0.2, 0.3], [0, 0, 0.04], 0.2, 1).step_3() Traceback (most recent call last): ... ValueError: x-values must be equally spaced according to step size. >>> AdamsBashforth(f,[0,0.2,0.4,0.6,0.8],[0,0,0.04,0.128,0.307],-0.2,1).step_5() Traceback (most recent call last): ... ValueError: Step size must be positive. """ func: Callable[[float, float], float] x_initials: list[float] y_initials: list[float] step_size: float x_final: float def __post_init__(self) -> None: if self.x_initials[-1] >= self.x_final: raise ValueError( "The final value of x must be greater than the initial values of x." ) if self.step_size <= 0: raise ValueError("Step size must be positive.") if not all( round(x1 - x0, 10) == self.step_size for x0, x1 in zip(self.x_initials, self.x_initials[1:]) ): raise ValueError("x-values must be equally spaced according to step size.") def step_2(self) -> np.ndarray: """ >>> def f(x, y): ... return x >>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_2() array([0. , 0. , 0.06, 0.16, 0.3 , 0.48]) >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_2() Traceback (most recent call last): ... ValueError: Insufficient initial points information. """ if len(self.x_initials) != 2 or len(self.y_initials) != 2: raise ValueError("Insufficient initial points information.") x_0, x_1 = self.x_initials[:2] y_0, y_1 = self.y_initials[:2] n = int((self.x_final - x_1) / self.step_size) y = np.zeros(n + 2) y[0] = y_0 y[1] = y_1 for i in range(n): y[i + 2] = y[i + 1] + (self.step_size / 2) * ( 3 * self.func(x_1, y[i + 1]) - self.func(x_0, y[i]) ) x_0 = x_1 x_1 += self.step_size return y def step_3(self) -> np.ndarray: """ >>> def f(x, y): ... return x + y >>> y = AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_3() >>> y[3] 0.15533333333333332 >>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_3() Traceback (most recent call last): ... ValueError: Insufficient initial points information. """ if len(self.x_initials) != 3 or len(self.y_initials) != 3: raise ValueError("Insufficient initial points information.") x_0, x_1, x_2 = self.x_initials[:3] y_0, y_1, y_2 = self.y_initials[:3] n = int((self.x_final - x_2) / self.step_size) y = np.zeros(n + 4) y[0] = y_0 y[1] = y_1 y[2] = y_2 for i in range(n + 1): y[i + 3] = y[i + 2] + (self.step_size / 12) * ( 23 * self.func(x_2, y[i + 2]) - 16 * self.func(x_1, y[i + 1]) + 5 * self.func(x_0, y[i]) ) x_0 = x_1 x_1 = x_2 x_2 += self.step_size return y def step_4(self) -> np.ndarray: """ >>> def f(x,y): ... return x + y >>> y = AdamsBashforth( ... f, [0, 0.2, 0.4, 0.6], [0, 0, 0.04, 0.128], 0.2, 1).step_4() >>> y[4] 0.30699999999999994 >>> y[5] 0.5771083333333333 >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_4() Traceback (most recent call last): ... ValueError: Insufficient initial points information. """ if len(self.x_initials) != 4 or len(self.y_initials) != 4: raise ValueError("Insufficient initial points information.") x_0, x_1, x_2, x_3 = self.x_initials[:4] y_0, y_1, y_2, y_3 = self.y_initials[:4] n = int((self.x_final - x_3) / self.step_size) y = np.zeros(n + 4) y[0] = y_0 y[1] = y_1 y[2] = y_2 y[3] = y_3 for i in range(n): y[i + 4] = y[i + 3] + (self.step_size / 24) * ( 55 * self.func(x_3, y[i + 3]) - 59 * self.func(x_2, y[i + 2]) + 37 * self.func(x_1, y[i + 1]) - 9 * self.func(x_0, y[i]) ) x_0 = x_1 x_1 = x_2 x_2 = x_3 x_3 += self.step_size return y def step_5(self) -> np.ndarray: """ >>> def f(x,y): ... return x + y >>> y = AdamsBashforth( ... f, [0, 0.2, 0.4, 0.6, 0.8], [0, 0.02140, 0.02140, 0.22211, 0.42536], ... 0.2, 1).step_5() >>> y[-1] 0.05436839444444452 >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_5() Traceback (most recent call last): ... ValueError: Insufficient initial points information. """ if len(self.x_initials) != 5 or len(self.y_initials) != 5: raise ValueError("Insufficient initial points information.") x_0, x_1, x_2, x_3, x_4 = self.x_initials[:5] y_0, y_1, y_2, y_3, y_4 = self.y_initials[:5] n = int((self.x_final - x_4) / self.step_size) y = np.zeros(n + 6) y[0] = y_0 y[1] = y_1 y[2] = y_2 y[3] = y_3 y[4] = y_4 for i in range(n + 1): y[i + 5] = y[i + 4] + (self.step_size / 720) * ( 1901 * self.func(x_4, y[i + 4]) - 2774 * self.func(x_3, y[i + 3]) - 2616 * self.func(x_2, y[i + 2]) - 1274 * self.func(x_1, y[i + 1]) + 251 * self.func(x_0, y[i]) ) x_0 = x_1 x_1 = x_2 x_2 = x_3 x_3 = x_4 x_4 += self.step_size return y if __name__ == "__main__": import doctest doctest.testmod()
finds where function becomes 0 in a,b using bolzano bisectionlambda x: x 3 1, 5, 5 1.0000000149011612 bisectionlambda x: x 3 1, 2, 1000 Traceback most recent call last: ... ValueError: could not find root in given interval. bisectionlambda x: x 2 4 x 3, 0, 2 1.0 bisectionlambda x: x 2 4 x 3, 2, 4 3.0 bisectionlambda x: x 2 4 x 3, 4, 1000 Traceback most recent call last: ... ValueError: could not find root in given interval. then this algorithm can't find the root
from collections.abc import Callable def bisection(function: Callable[[float], float], a: float, b: float) -> float: """ finds where function becomes 0 in [a,b] using bolzano >>> bisection(lambda x: x ** 3 - 1, -5, 5) 1.0000000149011612 >>> bisection(lambda x: x ** 3 - 1, 2, 1000) Traceback (most recent call last): ... ValueError: could not find root in given interval. >>> bisection(lambda x: x ** 2 - 4 * x + 3, 0, 2) 1.0 >>> bisection(lambda x: x ** 2 - 4 * x + 3, 2, 4) 3.0 >>> bisection(lambda x: x ** 2 - 4 * x + 3, 4, 1000) Traceback (most recent call last): ... ValueError: could not find root in given interval. """ start: float = a end: float = b if function(a) == 0: # one of the a or b is a root for the function return a elif function(b) == 0: return b elif ( function(a) * function(b) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("could not find root in given interval.") else: mid: float = start + (end - start) / 2.0 while abs(start - mid) > 10**-7: # until precisely equals to 10^-7 if function(mid) == 0: return mid elif function(mid) * function(start) < 0: end = mid else: start = mid mid = start + (end - start) / 2.0 return mid def f(x: float) -> float: return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
Given a function on floating number fx and two floating numbers a and b such that fa fb 0 and fx is continuous in a, b. Here fx represents algebraic or transcendental equation. Find root of function in interval a, b Or find a value of x such that fx is 0 https:en.wikipedia.orgwikiBisectionmethod equation5 15 equation0 10 equation5 15 equation0.1 9.99 equation0.1 9.99 bisection2, 5 3.1611328125 bisection0, 6 3.158203125 bisection2, 3 Traceback most recent call last: ... ValueError: Wrong space! Bolzano theory in order to find if there is a root between a and b Find middle point Check if middle point is root Decide the side to repeat the steps
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))
Author : Syed Faizan 3rd Year IIIT Pune Github : faizan2700 Purpose : You have one function fx which takes float integer and returns float you have to integrate the function in limits a to b. The approximation proposed by Thomas Simpsons in 1743 is one way to calculate integration. read article : https:cpalgorithms.comnummethodssimpsonintegration.html simpsonintegration takes function,lowerlimita,upperlimitb,precision and returns the integration of function in given limit. constants the more the number of steps the more accurate Summary of Simpson Approximation : By simpsons integration : 1. integration of fxdx with limit a to b is fx0 4 fx1 2 fx2 4 fx3 2 fx4..... fxn where x0 a xi a i h xn b Args: function : the function which's integration is desired a : the lower limit of integration b : upper limit of integration precision : precision of the result,error required default is 4 Returns: result : the value of the approximated integration of function in range a to b Raises: AssertionError: function is not callable AssertionError: a is not float or integer AssertionError: function should return float or integer AssertionError: b is not float or integer AssertionError: precision is not positive integer simpsonintegrationlambda x : xx,1,2,3 2.333 simpsonintegrationlambda x : xx,'wronginput',2,3 Traceback most recent call last: ... AssertionError: a should be float or integer your input : wronginput simpsonintegrationlambda x : xx,1,'wronginput',3 Traceback most recent call last: ... AssertionError: b should be float or integer your input : wronginput simpsonintegrationlambda x : xx,1,2,'wronginput' Traceback most recent call last: ... AssertionError: precision should be positive integer your input : wronginput simpsonintegration'wronginput',2,3,4 Traceback most recent call last: ... AssertionError: the functionobject passed should be callable your input : ... simpsonintegrationlambda x : xx,3.45,3.2,1 2.8 simpsonintegrationlambda x : xx,3.45,3.2,0 Traceback most recent call last: ... AssertionError: precision should be positive integer your input : 0 simpsonintegrationlambda x : xx,3.45,3.2,1 Traceback most recent call last: ... AssertionError: precision should be positive integer your input : 1 just applying the formula of simpson for approximate integration written in mentioned article in first comment of this file and above this function
# constants # the more the number of steps the more accurate N_STEPS = 1000 def f(x: float) -> float: return x * x """ Summary of Simpson Approximation : By simpsons integration : 1. integration of fxdx with limit a to b is = f(x0) + 4 * f(x1) + 2 * f(x2) + 4 * f(x3) + 2 * f(x4)..... + f(xn) where x0 = a xi = a + i * h xn = b """ def simpson_integration(function, a: float, b: float, precision: int = 4) -> float: """ Args: function : the function which's integration is desired a : the lower limit of integration b : upper limit of integration precision : precision of the result,error required default is 4 Returns: result : the value of the approximated integration of function in range a to b Raises: AssertionError: function is not callable AssertionError: a is not float or integer AssertionError: function should return float or integer AssertionError: b is not float or integer AssertionError: precision is not positive integer >>> simpson_integration(lambda x : x*x,1,2,3) 2.333 >>> simpson_integration(lambda x : x*x,'wrong_input',2,3) Traceback (most recent call last): ... AssertionError: a should be float or integer your input : wrong_input >>> simpson_integration(lambda x : x*x,1,'wrong_input',3) Traceback (most recent call last): ... AssertionError: b should be float or integer your input : wrong_input >>> simpson_integration(lambda x : x*x,1,2,'wrong_input') Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : wrong_input >>> simpson_integration('wrong_input',2,3,4) Traceback (most recent call last): ... AssertionError: the function(object) passed should be callable your input : ... >>> simpson_integration(lambda x : x*x,3.45,3.2,1) -2.8 >>> simpson_integration(lambda x : x*x,3.45,3.2,0) Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : 0 >>> simpson_integration(lambda x : x*x,3.45,3.2,-1) Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : -1 """ assert callable( function ), f"the function(object) passed should be callable your input : {function}" assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}" assert isinstance(function(a), (float, int)), ( "the function should return integer or float return type of your function, " f"{type(a)}" ) assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}" assert ( isinstance(precision, int) and precision > 0 ), f"precision should be positive integer your input : {precision}" # just applying the formula of simpson for approximate integration written in # mentioned article in first comment of this file and above this function h = (b - a) / N_STEPS result = function(a) + function(b) for i in range(1, N_STEPS): a1 = a + h * i result += function(a1) * (4 if i % 2 else 2) result *= h / 3 return round(result, precision) if __name__ == "__main__": import doctest doctest.testmod()
function is the f we want to find its root x0 and x1 are two random starting points intersectionlambda x: x 3 1, 5, 5 0.9999999999954654 intersectionlambda x: x 3 1, 5, 5 Traceback most recent call last: ... ZeroDivisionError: float division by zero, could not find root intersectionlambda x: x 3 1, 100, 200 1.0000000000003888 intersectionlambda x: x 2 4 x 3, 0, 2 0.9999999998088019 intersectionlambda x: x 2 4 x 3, 2, 4 2.9999999998088023 intersectionlambda x: x 2 4 x 3, 4, 1000 3.0000000001786042 intersectionmath.sin, math.pi, math.pi 0.0 intersectionmath.cos, math.pi, math.pi Traceback most recent call last: ... ZeroDivisionError: float division by zero, could not find root
import math from collections.abc import Callable def intersection(function: Callable[[float], float], x0: float, x1: float) -> float: """ function is the f we want to find its root x0 and x1 are two random starting points >>> intersection(lambda x: x ** 3 - 1, -5, 5) 0.9999999999954654 >>> intersection(lambda x: x ** 3 - 1, 5, 5) Traceback (most recent call last): ... ZeroDivisionError: float division by zero, could not find root >>> intersection(lambda x: x ** 3 - 1, 100, 200) 1.0000000000003888 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 0, 2) 0.9999999998088019 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 2, 4) 2.9999999998088023 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 4, 1000) 3.0000000001786042 >>> intersection(math.sin, -math.pi, math.pi) 0.0 >>> intersection(math.cos, -math.pi, math.pi) Traceback (most recent call last): ... ZeroDivisionError: float division by zero, could not find root """ x_n: float = x0 x_n1: float = x1 while True: if x_n == x_n1 or function(x_n1) == function(x_n): raise ZeroDivisionError("float division by zero, could not find root") x_n2: float = x_n1 - ( function(x_n1) / ((function(x_n1) - function(x_n)) / (x_n1 - x_n)) ) if abs(x_n2 - x_n1) < 10**-5: return x_n2 x_n = x_n1 x_n1 = x_n2 def f(x: float) -> float: return math.pow(x, 3) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
Python program to show how to interpolate and evaluate a polynomial using Neville's method. Nevilles 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.comaaronsc32nevillesmethodpolynomialinterpolation Interpolate and evaluate a polynomial using Neville's method. Arguments: xpoints, ypoints: 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 nevilleinterpolate1,2,3,4,6, 6,7,8,9,11, 50 10.0 pprint.pprintnevilleinterpolate1,2,3,4,6, 6,7,8,9,11, 991 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 nevilleinterpolate1,2,3,4,6, 6,7,8,9,11, 990 104.0 nevilleinterpolate1,2,3,4,6, 6,7,8,9,11, '' Traceback most recent call last: ... TypeError: unsupported operand types for : 'str' and 'int'
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()
https:www.geeksforgeeks.orgnewtonforwardbackwardinterpolation for calculating u value ucal1, 2 0 ucal1.1, 2 0.11000000000000011 ucal1.2, 2 0.23999999999999994 for calculating forward difference table
# https://www.geeksforgeeks.org/newton-forward-backward-interpolation/ from __future__ import annotations import math # for calculating u value def ucal(u: float, p: int) -> float: """ >>> ucal(1, 2) 0 >>> ucal(1.1, 2) 0.11000000000000011 >>> ucal(1.2, 2) 0.23999999999999994 """ temp = u for i in range(1, p): temp = temp * (u - i) return temp def main() -> None: n = int(input("enter the numbers of values: ")) y: list[list[float]] = [] for _ in range(n): y.append([]) for i in range(n): for j in range(n): y[i].append(j) y[i][j] = 0 print("enter the values of parameters in a list: ") x = list(map(int, input().split())) print("enter the values of corresponding parameters: ") for i in range(n): y[i][0] = float(input()) value = int(input("enter the value to interpolate: ")) u = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1, n): for j in range(n - i): y[j][i] = y[j + 1][i - 1] - y[j][i - 1] summ = y[0][0] for i in range(1, n): summ += (ucal(u, i) * y[0][i]) / math.factorial(i) print(f"the value at {value} is {summ}") if __name__ == "__main__": main()
The NewtonRaphson method aka the Newton method is a rootfinding algorithm that approximates a root of a given realvalued function fx. It is an iterative method given by the formula xn 1 xn fxn f'xn with the precision of the approximation increasing as the number of iterations increase. Reference: https:en.wikipedia.orgwikiNewton27smethod Approximate the derivative of a function fx at a point x using the finite difference method import math tolerance 1e5 derivative calcderivativelambda x: x2, 2 math.isclosederivative, 4, abstoltolerance True derivative calcderivativemath.sin, 0 math.isclosederivative, 1, abstoltolerance True Find a root of the given function f using the NewtonRaphson method. :param f: A realvalued singlevariable function :param x0: Initial guess :param maxiter: Maximum number of iterations :param step: Step size of x, used to approximate f'x :param maxerror: Maximum approximation error :param logsteps: bool denoting whether to log intermediate steps :return: A tuple containing the approximation, the error, and the intermediate steps. If logsteps is False, then an empty list is returned for the third element of the tuple. :raises ZeroDivisionError: The derivative approaches 0. :raises ArithmeticError: No solution exists, or the solution isn't found before the iteration limit is reached. import math tolerance 1e15 root, newtonraphsonlambda x: x2 5x 2, 0.4, maxerrortolerance math.iscloseroot, 5 math.sqrt17 2, abstoltolerance True root, newtonraphsonlambda x: math.logx 1, 2, maxerrortolerance math.iscloseroot, math.e, abstoltolerance True root, newtonraphsonmath.sin, 1, maxerrortolerance math.iscloseroot, 0, abstoltolerance True newtonraphsonmath.cos, 0 Traceback most recent call last: ... ZeroDivisionError: No converging solution found, zero derivative newtonraphsonlambda x: x2 1, 2 Traceback most recent call last: ... ArithmeticError: No converging solution found, iteration limit reached
from collections.abc import Callable RealFunc = Callable[[float], float] def calc_derivative(f: RealFunc, x: float, delta_x: float = 1e-3) -> float: """ Approximate the derivative of a function f(x) at a point x using the finite difference method >>> import math >>> tolerance = 1e-5 >>> derivative = calc_derivative(lambda x: x**2, 2) >>> math.isclose(derivative, 4, abs_tol=tolerance) True >>> derivative = calc_derivative(math.sin, 0) >>> math.isclose(derivative, 1, abs_tol=tolerance) True """ return (f(x + delta_x / 2) - f(x - delta_x / 2)) / delta_x def newton_raphson( f: RealFunc, x0: float = 0, max_iter: int = 100, step: float = 1e-6, max_error: float = 1e-6, log_steps: bool = False, ) -> tuple[float, float, list[float]]: """ Find a root of the given function f using the Newton-Raphson method. :param f: A real-valued single-variable function :param x0: Initial guess :param max_iter: Maximum number of iterations :param step: Step size of x, used to approximate f'(x) :param max_error: Maximum approximation error :param log_steps: bool denoting whether to log intermediate steps :return: A tuple containing the approximation, the error, and the intermediate steps. If log_steps is False, then an empty list is returned for the third element of the tuple. :raises ZeroDivisionError: The derivative approaches 0. :raises ArithmeticError: No solution exists, or the solution isn't found before the iteration limit is reached. >>> import math >>> tolerance = 1e-15 >>> root, *_ = newton_raphson(lambda x: x**2 - 5*x + 2, 0.4, max_error=tolerance) >>> math.isclose(root, (5 - math.sqrt(17)) / 2, abs_tol=tolerance) True >>> root, *_ = newton_raphson(lambda x: math.log(x) - 1, 2, max_error=tolerance) >>> math.isclose(root, math.e, abs_tol=tolerance) True >>> root, *_ = newton_raphson(math.sin, 1, max_error=tolerance) >>> math.isclose(root, 0, abs_tol=tolerance) True >>> newton_raphson(math.cos, 0) Traceback (most recent call last): ... ZeroDivisionError: No converging solution found, zero derivative >>> newton_raphson(lambda x: x**2 + 1, 2) Traceback (most recent call last): ... ArithmeticError: No converging solution found, iteration limit reached """ def f_derivative(x: float) -> float: return calc_derivative(f, x, step) a = x0 # Set initial guess steps = [] for _ in range(max_iter): if log_steps: # Log intermediate steps steps.append(a) error = abs(f(a)) if error < max_error: return a, error, steps if f_derivative(a) == 0: raise ZeroDivisionError("No converging solution found, zero derivative") a -= f(a) / f_derivative(a) # Calculate next estimate raise ArithmeticError("No converging solution found, iteration limit reached") if __name__ == "__main__": import doctest from math import exp, tanh doctest.testmod() def func(x: float) -> float: return tanh(x) ** 2 - exp(3 * x) solution, err, steps = newton_raphson( func, x0=10, max_iter=100, step=1e-6, log_steps=True ) print(f"{solution=}, {err=}") print("\n".join(str(x) for x in steps))
Approximates the area under the curve using the trapezoidal rule Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param xstart: left end point to indicate the start of line segment :param xend: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases the accuracy :return: a float representing the length of the curve def fx: ... return 5 '.3f' trapezoidalareaf, 12.0, 14.0, 1000 '10.000' def fx: ... return 9x2 '.4f' trapezoidalareaf, 4.0, 0, 10000 '192.0000' '.4f' trapezoidalareaf, 4.0, 4.0, 10000 '384.0000' Approximates small segments of curve as linear and solve for trapezoidal area Increment step
from __future__ import annotations from collections.abc import Callable def trapezoidal_area( fnc: Callable[[float], float], x_start: float, x_end: float, steps: int = 100, ) -> float: """ Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases the accuracy :return: a float representing the length of the curve >>> def f(x): ... return 5 >>> '%.3f' % trapezoidal_area(f, 12.0, 14.0, 1000) '10.000' >>> def f(x): ... return 9*x**2 >>> '%.4f' % trapezoidal_area(f, -4.0, 0, 10000) '192.0000' >>> '%.4f' % trapezoidal_area(f, -4.0, 4.0, 10000) '384.0000' """ x1 = x_start fx1 = fnc(x_start) area = 0.0 for _ in range(steps): # Approximates small segments of curve as linear and solve # for trapezoidal area x2 = (x_end - x_start) / steps + x1 fx2 = fnc(x2) area += abs(fx2 + fx1) * (x2 - x1) / 2 # Increment step x1 = x2 fx1 = fx2 return area if __name__ == "__main__": def f(x): return x**3 print("f(x) = x^3") print("The area between the curve, x = -10, x = 10 and the x axis is:") i = 10 while i <= 100000: area = trapezoidal_area(f, -5, 5, i) print(f"with {i} steps: {area}") i *= 10
Calculate the numeric solution at each step to the ODE fx, y using RK4 https:en.wikipedia.orgwikiRungeKuttamethods Arguments: f The ode as a function of x and y y0 the initial value for y x0 the initial value for x h the stepsize xend the end value for x the exact solution is math.expx def fx, y: ... return y y0 1 y rungekuttaf, y0, 0.0, 0.01, 5 y1 148.41315904125113
import numpy as np def runge_kutta(f, y0, x0, h, x_end): """ Calculate the numeric solution at each step to the ODE f(x, y) using RK4 https://en.wikipedia.org/wiki/Runge-Kutta_methods Arguments: f -- The ode as a function of x and y y0 -- the initial value for y x0 -- the initial value for x h -- the stepsize x_end -- the end value for x >>> # the exact solution is math.exp(x) >>> def f(x, y): ... return y >>> y0 = 1 >>> y = runge_kutta(f, y0, 0.0, 0.01, 5) >>> y[-1] 148.41315904125113 """ n = int(np.ceil((x_end - x0) / h)) y = np.zeros((n + 1,)) y[0] = y0 x = x0 for k in range(n): k1 = f(x, y[k]) k2 = f(x + 0.5 * h, y[k] + 0.5 * h * k1) k3 = f(x + 0.5 * h, y[k] + 0.5 * h * k2) k4 = f(x + h, y[k] + h * k3) y[k + 1] = y[k] + (1 / 6) * h * (k1 + 2 * k2 + 2 * k3 + k4) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
Use the RungeKuttaFehlberg method to solve Ordinary Differential Equations. Solve an Ordinary Differential Equations using RungeKuttaFehlberg Method rkf45 of order 5. https:en.wikipedia.orgwikiRungeE28093KuttaE28093Fehlbergmethod args: func: An ordinary differential equation ODE as function of x and y. xinitial: The initial value of x. yinitial: The initial value of y. stepsize: The increment value of x. xfinal: The final value of x. Returns: Solution of y at each nodal point exact value of y1 is tan0.2 0.2027100937470787 def fx, y: ... return 1 y2 y rungekuttafehlberg45f, 0, 0, 0.2, 1 y1 0.2027100937470787 def fx,y: ... return x y rungekuttafehlberg45f, 1, 0, 0.2, 0 y1 0.18000000000000002 y rungekuttafehlberg455, 0, 0, 0.1, 1 Traceback most recent call last: ... TypeError: 'int' object is not callable def fx, y: ... return x y y rungekuttafehlberg45f, 0, 0, 0.2, 1 Traceback most recent call last: ... ValueError: The final value of x must be greater than initial value of x. def fx, y: ... return x y rungekuttafehlberg45f, 1, 0, 0.2, 0 Traceback most recent call last: ... ValueError: Step size must be positive.
from collections.abc import Callable import numpy as np def runge_kutta_fehlberg_45( func: Callable, x_initial: float, y_initial: float, step_size: float, x_final: float, ) -> np.ndarray: """ Solve an Ordinary Differential Equations using Runge-Kutta-Fehlberg Method (rkf45) of order 5. https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta%E2%80%93Fehlberg_method args: func: An ordinary differential equation (ODE) as function of x and y. x_initial: The initial value of x. y_initial: The initial value of y. step_size: The increment value of x. x_final: The final value of x. Returns: Solution of y at each nodal point # exact value of y[1] is tan(0.2) = 0.2027100937470787 >>> def f(x, y): ... return 1 + y**2 >>> y = runge_kutta_fehlberg_45(f, 0, 0, 0.2, 1) >>> y[1] 0.2027100937470787 >>> def f(x,y): ... return x >>> y = runge_kutta_fehlberg_45(f, -1, 0, 0.2, 0) >>> y[1] -0.18000000000000002 >>> y = runge_kutta_fehlberg_45(5, 0, 0, 0.1, 1) Traceback (most recent call last): ... TypeError: 'int' object is not callable >>> def f(x, y): ... return x + y >>> y = runge_kutta_fehlberg_45(f, 0, 0, 0.2, -1) Traceback (most recent call last): ... ValueError: The final value of x must be greater than initial value of x. >>> def f(x, y): ... return x >>> y = runge_kutta_fehlberg_45(f, -1, 0, -0.2, 0) Traceback (most recent call last): ... ValueError: Step size must be positive. """ if x_initial >= x_final: raise ValueError( "The final value of x must be greater than initial value of x." ) if step_size <= 0: raise ValueError("Step size must be positive.") n = int((x_final - x_initial) / step_size) y = np.zeros( (n + 1), ) x = np.zeros(n + 1) y[0] = y_initial x[0] = x_initial for i in range(n): k1 = step_size * func(x[i], y[i]) k2 = step_size * func(x[i] + step_size / 4, y[i] + k1 / 4) k3 = step_size * func( x[i] + (3 / 8) * step_size, y[i] + (3 / 32) * k1 + (9 / 32) * k2 ) k4 = step_size * func( x[i] + (12 / 13) * step_size, y[i] + (1932 / 2197) * k1 - (7200 / 2197) * k2 + (7296 / 2197) * k3, ) k5 = step_size * func( x[i] + step_size, y[i] + (439 / 216) * k1 - 8 * k2 + (3680 / 513) * k3 - (845 / 4104) * k4, ) k6 = step_size * func( x[i] + step_size / 2, y[i] - (8 / 27) * k1 + 2 * k2 - (3544 / 2565) * k3 + (1859 / 4104) * k4 - (11 / 40) * k5, ) y[i + 1] = ( y[i] + (16 / 135) * k1 + (6656 / 12825) * k3 + (28561 / 56430) * k4 - (9 / 50) * k5 + (2 / 55) * k6 ) x[i + 1] = step_size + x[i] return y if __name__ == "__main__": import doctest doctest.testmod()
Use the RungeKuttaGill's method of order 4 to solve Ordinary Differential Equations. https:www.geeksforgeeks.orggills4thordermethodtosolvedifferentialequations Author : Ravi Kumar Solve an Ordinary Differential Equations using RungeKuttaGills Method of order 4. args: func: An ordinary differential equation ODE as function of x and y. xinitial: The initial value of x. yinitial: The initial value of y. stepsize: The increment value of x. xfinal: The final value of x. Returns: Solution of y at each nodal point def fx, y: ... return xy2 y rungekuttagillsf, 0, 3, 0.2, 5 y1 3.4104259225717537 def fx,y: ... return x y rungekuttagillsf, 1, 0, 0.2, 0 y array 0. , 0.18, 0.32, 0.42, 0.48, 0.5 def fx, y: ... return x y y rungekuttagillsf, 0, 0, 0.2, 1 Traceback most recent call last: ... ValueError: The final value of x must be greater than initial value of x. def fx, y: ... return x y rungekuttagillsf, 1, 0, 0.2, 0 Traceback most recent call last: ... ValueError: Step size must be positive.
from collections.abc import Callable from math import sqrt import numpy as np def runge_kutta_gills( func: Callable[[float, float], float], x_initial: float, y_initial: float, step_size: float, x_final: float, ) -> np.ndarray: """ Solve an Ordinary Differential Equations using Runge-Kutta-Gills Method of order 4. args: func: An ordinary differential equation (ODE) as function of x and y. x_initial: The initial value of x. y_initial: The initial value of y. step_size: The increment value of x. x_final: The final value of x. Returns: Solution of y at each nodal point >>> def f(x, y): ... return (x-y)/2 >>> y = runge_kutta_gills(f, 0, 3, 0.2, 5) >>> y[-1] 3.4104259225717537 >>> def f(x,y): ... return x >>> y = runge_kutta_gills(f, -1, 0, 0.2, 0) >>> y array([ 0. , -0.18, -0.32, -0.42, -0.48, -0.5 ]) >>> def f(x, y): ... return x + y >>> y = runge_kutta_gills(f, 0, 0, 0.2, -1) Traceback (most recent call last): ... ValueError: The final value of x must be greater than initial value of x. >>> def f(x, y): ... return x >>> y = runge_kutta_gills(f, -1, 0, -0.2, 0) Traceback (most recent call last): ... ValueError: Step size must be positive. """ if x_initial >= x_final: raise ValueError( "The final value of x must be greater than initial value of x." ) if step_size <= 0: raise ValueError("Step size must be positive.") n = int((x_final - x_initial) / step_size) y = np.zeros(n + 1) y[0] = y_initial for i in range(n): k1 = step_size * func(x_initial, y[i]) k2 = step_size * func(x_initial + step_size / 2, y[i] + k1 / 2) k3 = step_size * func( x_initial + step_size / 2, y[i] + (-0.5 + 1 / sqrt(2)) * k1 + (1 - 1 / sqrt(2)) * k2, ) k4 = step_size * func( x_initial + step_size, y[i] - (1 / sqrt(2)) * k2 + (1 + 1 / sqrt(2)) * k3 ) y[i + 1] = y[i] + (k1 + (2 - sqrt(2)) * k2 + (2 + sqrt(2)) * k3 + k4) / 6 x_initial += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
Implementing Secant method in Python Author: dimgrichr f5 39.98652410600183 secantmethod1, 3, 2 0.2139409276214589
from math import exp def f(x: float) -> float: """ >>> f(5) 39.98652410600183 """ return 8 * x - 2 * exp(-x) def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float: """ >>> secant_method(1, 3, 2) 0.2139409276214589 """ x0 = lower_bound x1 = upper_bound for _ in range(repeats): x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0)) return x1 if __name__ == "__main__": print(f"Example: {secant_method(1, 3, 2)}")
Numerical integration or quadrature for a smooth function f with known values at xi This method is the classical approach of summing 'Equally Spaced Abscissas' method 2: Simpson Rule Simpson Rule intf deltax2 ba3f1 4f2 2f3 ... fn Calculate the definite integral of a function using Simpson's Rule. :param boundary: A list containing the lower and upper bounds of integration. :param steps: The number of steps or resolution for the integration. :return: The approximate integral value. roundmethod20, 2, 4, 10, 10 2.6666666667 roundmethod22, 0, 10, 10 0.2666666667 roundmethod22, 1, 10, 10 2.172 roundmethod20, 1, 10, 10 0.3333333333 roundmethod20, 2, 10, 10 2.6666666667 roundmethod20, 2, 100, 10 2.5621226667 roundmethod20, 1, 1000, 10 0.3320026653 roundmethod20, 2, 0, 10 Traceback most recent call last: ... ZeroDivisionError: Number of steps must be greater than zero roundmethod20, 2, 10, 10 Traceback most recent call last: ... ZeroDivisionError: Number of steps must be greater than zero
def method_2(boundary: list[int], steps: int) -> float: # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) """ Calculate the definite integral of a function using Simpson's Rule. :param boundary: A list containing the lower and upper bounds of integration. :param steps: The number of steps or resolution for the integration. :return: The approximate integral value. >>> round(method_2([0, 2, 4], 10), 10) 2.6666666667 >>> round(method_2([2, 0], 10), 10) -0.2666666667 >>> round(method_2([-2, -1], 10), 10) 2.172 >>> round(method_2([0, 1], 10), 10) 0.3333333333 >>> round(method_2([0, 2], 10), 10) 2.6666666667 >>> round(method_2([0, 2], 100), 10) 2.5621226667 >>> round(method_2([0, 1], 1000), 10) 0.3320026653 >>> round(method_2([0, 2], 0), 10) Traceback (most recent call last): ... ZeroDivisionError: Number of steps must be greater than zero >>> round(method_2([0, 2], -10), 10) Traceback (most recent call last): ... ZeroDivisionError: Number of steps must be greater than zero """ if steps <= 0: raise ZeroDivisionError("Number of steps must be greater than zero") 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 # number of steps or resolution boundary = [a, b] # boundary of integration y = method_2(boundary, steps) print(f"y = {y}") if __name__ == "__main__": import doctest doctest.testmod() main()
Square root approximated using Newton's method. https:en.wikipedia.orgwikiNewton27smethod allabssquarerootiterativei math.sqrti 1e14 for i in range500 True squarerootiterative1 Traceback most recent call last: ... ValueError: math domain error squarerootiterative4 2.0 squarerootiterative3.2 1.788854381999832 squarerootiterative140 11.832159566199232
import math def fx(x: float, a: float) -> float: return math.pow(x, 2) - a def fx_derivative(x: float) -> float: return 2 * x def get_initial_point(a: float) -> float: start = 2.0 while start <= a: start = math.pow(start, 2) return start def square_root_iterative( a: float, max_iter: int = 9999, tolerance: float = 1e-14 ) -> float: """ Square root approximated using Newton's method. https://en.wikipedia.org/wiki/Newton%27s_method >>> all(abs(square_root_iterative(i) - math.sqrt(i)) <= 1e-14 for i in range(500)) True >>> square_root_iterative(-1) Traceback (most recent call last): ... ValueError: math domain error >>> square_root_iterative(4) 2.0 >>> square_root_iterative(3.2) 1.788854381999832 >>> square_root_iterative(140) 11.832159566199232 """ if a < 0: raise ValueError("math domain error") value = get_initial_point(a) for _ in range(max_iter): prev_value = value value = value - fx(value, a) / fx_derivative(value) if abs(prev_value - value) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
Returns the prime numbers num. The prime numbers are calculated using an odd sieve implementation of the Sieve of Eratosthenes algorithm see for reference https:en.wikipedia.orgwikiSieveofEratosthenes. oddsieve2 oddsieve3 2 oddsieve10 2, 3, 5, 7 oddsieve20 2, 3, 5, 7, 11, 13, 17, 19 Odd sieve for numbers in range 3, num 1
from itertools import compress, repeat from math import ceil, sqrt def odd_sieve(num: int) -> list[int]: """ Returns the prime numbers < `num`. The prime numbers are calculated using an odd sieve implementation of the Sieve of Eratosthenes algorithm (see for reference https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes). >>> odd_sieve(2) [] >>> odd_sieve(3) [2] >>> odd_sieve(10) [2, 3, 5, 7] >>> odd_sieve(20) [2, 3, 5, 7, 11, 13, 17, 19] """ if num <= 2: return [] if num == 3: return [2] # Odd sieve for numbers in range [3, num - 1] sieve = bytearray(b"\x01") * ((num >> 1) - 1) for i in range(3, int(sqrt(num)) + 1, 2): if sieve[(i >> 1) - 1]: i_squared = i**2 sieve[(i_squared >> 1) - 1 :: i] = repeat( 0, ceil((num - i_squared) / (i << 1)) ) return [2] + list(compress(range(3, num, 2), sieve)) if __name__ == "__main__": import doctest doctest.testmod()
Check if a number is a perfect cube or not. perfectcube27 True perfectcube4 False Check if a number is a perfect cube or not using binary search. Time complexity : OLogn Space complexity: O1 perfectcubebinarysearch27 True perfectcubebinarysearch64 True perfectcubebinarysearch4 False perfectcubebinarysearcha Traceback most recent call last: ... TypeError: perfectcubebinarysearch only accepts integers perfectcubebinarysearch0.1 Traceback most recent call last: ... TypeError: perfectcubebinarysearch only accepts integers
def perfect_cube(n: int) -> bool: """ Check if a number is a perfect cube or not. >>> perfect_cube(27) True >>> perfect_cube(4) False """ val = n ** (1 / 3) return (val * val * val) == n def perfect_cube_binary_search(n: int) -> bool: """ Check if a number is a perfect cube or not using binary search. Time complexity : O(Log(n)) Space complexity: O(1) >>> perfect_cube_binary_search(27) True >>> perfect_cube_binary_search(64) True >>> perfect_cube_binary_search(4) False >>> perfect_cube_binary_search("a") Traceback (most recent call last): ... TypeError: perfect_cube_binary_search() only accepts integers >>> perfect_cube_binary_search(0.1) Traceback (most recent call last): ... TypeError: perfect_cube_binary_search() only accepts integers """ if not isinstance(n, int): raise TypeError("perfect_cube_binary_search() only accepts integers") if n < 0: n = -n left = 0 right = n while left <= right: mid = left + (right - left) // 2 if mid * mid * mid == n: return True elif mid * mid * mid < n: left = mid + 1 else: right = mid - 1 return False if __name__ == "__main__": import doctest doctest.testmod()
Perfect Number In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For example: 6 divisors1, 2, 3, 6 Excluding 6, the sumdivisors is 1 2 3 6 So, 6 is a Perfect Number Other examples of Perfect Numbers: 28, 486, ... https:en.wikipedia.orgwikiPerfectnumber Check if a number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors excluding itself. Args: number: The number to be checked. Returns: True if the number is a perfect number otherwise, False. Start from 1 because dividing by 0 will raise ZeroDivisionError. A number at most can be divisible by the half of the number except the number itself. For example, 6 is at most can be divisible by 3 except by 6 itself. Examples: perfect27 False perfect28 True perfect29 False perfect6 True perfect12 False perfect496 True perfect8128 True perfect0 False perfect1 False perfect12.34 Traceback most recent call last: ... ValueError: number must an integer perfectHello Traceback most recent call last: ... ValueError: number must an integer
def perfect(number: int) -> bool: """ Check if a number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). Args: number: The number to be checked. Returns: True if the number is a perfect number otherwise, False. Start from 1 because dividing by 0 will raise ZeroDivisionError. A number at most can be divisible by the half of the number except the number itself. For example, 6 is at most can be divisible by 3 except by 6 itself. Examples: >>> perfect(27) False >>> perfect(28) True >>> perfect(29) False >>> perfect(6) True >>> perfect(12) False >>> perfect(496) True >>> perfect(8128) True >>> perfect(0) False >>> perfect(-1) False >>> perfect(12.34) Traceback (most recent call last): ... ValueError: number must an integer >>> perfect("Hello") Traceback (most recent call last): ... ValueError: number must an integer """ if not isinstance(number, int): raise ValueError("number must an integer") if number <= 0: return False return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number if __name__ == "__main__": from doctest import testmod testmod() print("Program to check whether a number is a Perfect number or not...") try: number = int(input("Enter a positive integer: ").strip()) except ValueError: msg = "number must an integer" print(msg) raise ValueError(msg) print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
Check if a number is perfect square number or not :param num: the number to be checked :return: True if number is square number, otherwise False perfectsquare9 True perfectsquare16 True perfectsquare1 True perfectsquare0 True perfectsquare10 False Check if a number is perfect square using binary search. Time complexity : OLogn Space complexity: O1 perfectsquarebinarysearch9 True perfectsquarebinarysearch16 True perfectsquarebinarysearch1 True perfectsquarebinarysearch0 True perfectsquarebinarysearch10 False perfectsquarebinarysearch1 False perfectsquarebinarysearch1.1 False perfectsquarebinarysearcha Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'str' perfectsquarebinarysearchNone Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'NoneType' perfectsquarebinarysearch Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'list'
import math def perfect_square(num: int) -> bool: """ Check if a number is perfect square number or not :param num: the number to be checked :return: True if number is square number, otherwise False >>> perfect_square(9) True >>> perfect_square(16) True >>> perfect_square(1) True >>> perfect_square(0) True >>> perfect_square(10) False """ return math.sqrt(num) * math.sqrt(num) == num def perfect_square_binary_search(n: int) -> bool: """ Check if a number is perfect square using binary search. Time complexity : O(Log(n)) Space complexity: O(1) >>> perfect_square_binary_search(9) True >>> perfect_square_binary_search(16) True >>> perfect_square_binary_search(1) True >>> perfect_square_binary_search(0) True >>> perfect_square_binary_search(10) False >>> perfect_square_binary_search(-1) False >>> perfect_square_binary_search(1.1) False >>> perfect_square_binary_search("a") Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> perfect_square_binary_search(None) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'NoneType' >>> perfect_square_binary_search([]) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ left = 0 right = n while left <= right: mid = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: right = mid - 1 else: left = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
Return the persistence of a given number. https:en.wikipedia.orgwikiPersistenceofanumber multiplicativepersistence217 2 multiplicativepersistence1 Traceback most recent call last: ... ValueError: multiplicativepersistence does not accept negative values multiplicativepersistencelong number Traceback most recent call last: ... ValueError: multiplicativepersistence only accepts integral values Return the persistence of a given number. https:en.wikipedia.orgwikiPersistenceofanumber additivepersistence199 3 additivepersistence1 Traceback most recent call last: ... ValueError: additivepersistence does not accept negative values additivepersistencelong number Traceback most recent call last: ... ValueError: additivepersistence only accepts integral values
def multiplicative_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> multiplicative_persistence(217) 2 >>> multiplicative_persistence(-1) Traceback (most recent call last): ... ValueError: multiplicative_persistence() does not accept negative values >>> multiplicative_persistence("long number") Traceback (most recent call last): ... ValueError: multiplicative_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("multiplicative_persistence() only accepts integral values") if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 1 for i in range(len(numbers)): total *= numbers[i] num_string = str(total) steps += 1 return steps def additive_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> additive_persistence(199) 3 >>> additive_persistence(-1) Traceback (most recent call last): ... ValueError: additive_persistence() does not accept negative values >>> additive_persistence("long number") Traceback (most recent call last): ... ValueError: additive_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("additive_persistence() only accepts integral values") if num < 0: raise ValueError("additive_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 0 for i in range(len(numbers)): total += numbers[i] num_string = str(total) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
https:en.wikipedia.orgwikiLeibnizformulaforCF80 Leibniz Formula for Pi The Leibniz formula is the special case arctan1 pi 4. Leibniz's formula converges extremely slowly: it exhibits sublinear convergence. Convergence https:en.wikipedia.orgwikiLeibnizformulaforCF80Convergence We cannot try to prove against an interrupted, uncompleted generation. https:en.wikipedia.orgwikiLeibnizformulaforCF80Unusualbehaviour The errors can in fact be predicted, but those calculations also approach infinity for accuracy. Our output will be a string so that we can definitely store all digits. import math floatcalculatepi15 math.pi True Since we cannot predict errors or interrupt any infinite alternating series generation since they approach infinity, or interrupt any alternating series, we'll need math.isclose math.isclosefloatcalculatepi50, math.pi True math.isclosefloatcalculatepi100, math.pi True Since math.pi contains only 16 digits, here are some tests with known values: calculatepi50 '3.14159265358979323846264338327950288419716939937510' calculatepi80 '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899' Variables used for the iteration process We can't compare against anything if we make a generator, so we'll stick with plain return logic
def calculate_pi(limit: int) -> str: """ https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 Leibniz Formula for Pi The Leibniz formula is the special case arctan(1) = pi / 4. Leibniz's formula converges extremely slowly: it exhibits sublinear convergence. Convergence (https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80#Convergence) We cannot try to prove against an interrupted, uncompleted generation. https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80#Unusual_behaviour The errors can in fact be predicted, but those calculations also approach infinity for accuracy. Our output will be a string so that we can definitely store all digits. >>> import math >>> float(calculate_pi(15)) == math.pi True Since we cannot predict errors or interrupt any infinite alternating series generation since they approach infinity, or interrupt any alternating series, we'll need math.isclose() >>> math.isclose(float(calculate_pi(50)), math.pi) True >>> math.isclose(float(calculate_pi(100)), math.pi) True Since math.pi contains only 16 digits, here are some tests with known values: >>> calculate_pi(50) '3.14159265358979323846264338327950288419716939937510' >>> calculate_pi(80) '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899' """ # Variables used for the iteration process q = 1 r = 0 t = 1 k = 1 n = 3 l = 3 decimal = limit counter = 0 result = "" # We can't compare against anything if we make a generator, # so we'll stick with plain return logic while counter != decimal + 1: if 4 * q + r - t < n * t: result += str(n) if counter == 0: result += "." if decimal == counter: break counter += 1 nr = 10 * (r - n * t) n = ((10 * (3 * q + r)) // t) - 10 * n q *= 10 r = nr else: nr = (2 * q + r) * l nn = (q * (7 * k) + 2 + (r * l)) // (t * l) q *= k t *= l l += 2 k += 1 n = nn r = nr return result def main() -> None: print(f"{calculate_pi(50) = }") import doctest doctest.testmod() if __name__ == "__main__": main()
True, if the point lies in the unit circle False, otherwise Generates a point randomly drawn from the unit square 0, 1 x 0, 1. Generates an estimate of the mathematical constant PI. See https:en.wikipedia.orgwikiMonteCarlomethodOverview The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from the unit square 0, 1 x 0, 1. The probability that U lies in the unit circle is: PU in unit circle 14 PI and therefore PI 4 PU in unit circle We can get an estimate of the probability PU in unit circle. See https:en.wikipedia.orgwikiEmpiricalprobability by: 1. Draw a point uniformly from the unit square. 2. Repeat the first step n times and count the number of points in the unit circle, which is called m. 3. An estimate of PU in unit circle is mn import doctest doctest.testmod
import random class Point: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y def is_in_unit_circle(self) -> bool: """ True, if the point lies in the unit circle False, otherwise """ return (self.x**2 + self.y**2) <= 1 @classmethod def random_unit_square(cls): """ Generates a point randomly drawn from the unit square [0, 1) x [0, 1). """ return cls(x=random.random(), y=random.random()) def estimate_pi(number_of_simulations: int) -> float: """ Generates an estimate of the mathematical constant PI. See https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is: P[U in unit circle] = 1/4 PI and therefore PI = 4 * P[U in unit circle] We can get an estimate of the probability P[U in unit circle]. See https://en.wikipedia.org/wiki/Empirical_probability by: 1. Draw a point uniformly from the unit square. 2. Repeat the first step n times and count the number of points in the unit circle, which is called m. 3. An estimate of P[U in unit circle] is m/n """ if number_of_simulations < 1: raise ValueError("At least one simulation is necessary to estimate PI.") number_in_unit_circle = 0 for _ in range(number_of_simulations): random_point = Point.random_unit_square() if random_point.is_in_unit_circle(): number_in_unit_circle += 1 return 4 * number_in_unit_circle / number_of_simulations if __name__ == "__main__": # import doctest # doctest.testmod() from math import pi prompt = "Please enter the desired number of Monte Carlo simulations: " my_pi = estimate_pi(int(input(prompt).strip())) print(f"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}")
Check if three points are collinear in 3D. In short, the idea is that we are able to create a triangle using three points, and the area of that triangle can determine if the three points are collinear or not. First, we create two vectors with the same initial point from the three points, then we will calculate the crossproduct of them. The length of the cross vector is numerically equal to the area of a parallelogram. Finally, the area of the triangle is equal to half of the area of the parallelogram. Since we are only differentiating between zero and anything else, we can get rid of the square root when calculating the length of the vector, and also the division by two at the end. From a second perspective, if the two vectors are parallel and overlapping, we can't get a nonzero perpendicular vector, since there will be an infinite number of orthogonal vectors. To simplify the solution we will not calculate the length, but we will decide directly from the vector whether it is equal to 0, 0, 0 or not. Read More: https:math.stackexchange.coma1951650 Pass two points to get the vector from them in the form x, y, z. createvector0, 0, 0, 1, 1, 1 1, 1, 1 createvector45, 70, 24, 47, 32, 1 2, 38, 23 createvector14, 1, 8, 7, 6, 4 7, 7, 12 Get the cross of the two vectors AB and AC. I used determinant of 2x2 to get the determinant of the 3x3 matrix in the process. Read More: https:en.wikipedia.orgwikiCrossproduct https:en.wikipedia.orgwikiDeterminant get3dvectorscross3, 4, 7, 4, 9, 2 55, 22, 11 get3dvectorscross1, 1, 1, 1, 1, 1 0, 0, 0 get3dvectorscross4, 3, 0, 3, 9, 12 36, 48, 27 get3dvectorscross17.67, 4.7, 6.78, 9.5, 4.78, 19.33 123.2594, 277.15110000000004, 129.11260000000001 Check if vector is equal to 0, 0, 0 of not. Sine the algorithm is very accurate, we will never get a zero vector, so we need to round the vector axis, because we want a result that is either True or False. In other applications, we can return a float that represents the collinearity ratio. iszerovector0, 0, 0, accuracy10 True iszerovector15, 74, 32, accuracy10 False iszerovector15, 74, 32, accuracy10 False Check if three points are collinear or not. 1 Create tow vectors AB and AC. 2 Get the cross vector of the tow vectors. 3 Calcolate the length of the cross vector. 4 If the length is zero then the points are collinear, else they are not. The use of the accuracy parameter is explained in iszerovector docstring. arecollinear4.802293498137402, 3.536233125455244, 0, ... 2.186788107953106, 9.24561398001649, 7.141509524846482, ... 1.530169574640268, 2.447927606600034, 3.343487096469054 True arecollinear6, 2, 6, ... 6.200213806439997, 4.930157614926678, 4.482371908289856, ... 4.085171149525941, 2.459889509029438, 4.354787180795383 True arecollinear2.399001826862445, 2.452009976680793, 4.464656666157666, ... 3.682816335934376, 5.753788986533145, 9.490993909044244, ... 1.962903518985307, 3.741415730125627, 7 False arecollinear1.875375340689544, 7.268426006071538, 7.358196269835993, ... 3.546599383667157, 4.630005261513976, 3.208784032924246, ... 2.564606140206386, 3.937845170672183, 7 False
Vector3d = tuple[float, float, float] Point3d = tuple[float, float, float] def create_vector(end_point1: Point3d, end_point2: Point3d) -> Vector3d: """ Pass two points to get the vector from them in the form (x, y, z). >>> create_vector((0, 0, 0), (1, 1, 1)) (1, 1, 1) >>> create_vector((45, 70, 24), (47, 32, 1)) (2, -38, -23) >>> create_vector((-14, -1, -8), (-7, 6, 4)) (7, 7, 12) """ x = end_point2[0] - end_point1[0] y = end_point2[1] - end_point1[1] z = end_point2[2] - end_point1[2] return (x, y, z) def get_3d_vectors_cross(ab: Vector3d, ac: Vector3d) -> Vector3d: """ Get the cross of the two vectors AB and AC. I used determinant of 2x2 to get the determinant of the 3x3 matrix in the process. Read More: https://en.wikipedia.org/wiki/Cross_product https://en.wikipedia.org/wiki/Determinant >>> get_3d_vectors_cross((3, 4, 7), (4, 9, 2)) (-55, 22, 11) >>> get_3d_vectors_cross((1, 1, 1), (1, 1, 1)) (0, 0, 0) >>> get_3d_vectors_cross((-4, 3, 0), (3, -9, -12)) (-36, -48, 27) >>> get_3d_vectors_cross((17.67, 4.7, 6.78), (-9.5, 4.78, -19.33)) (-123.2594, 277.15110000000004, 129.11260000000001) """ x = ab[1] * ac[2] - ab[2] * ac[1] # *i y = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j z = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def is_zero_vector(vector: Vector3d, accuracy: int) -> bool: """ Check if vector is equal to (0, 0, 0) of not. Sine the algorithm is very accurate, we will never get a zero vector, so we need to round the vector axis, because we want a result that is either True or False. In other applications, we can return a float that represents the collinearity ratio. >>> is_zero_vector((0, 0, 0), accuracy=10) True >>> is_zero_vector((15, 74, 32), accuracy=10) False >>> is_zero_vector((-15, -74, -32), accuracy=10) False """ return tuple(round(x, accuracy) for x in vector) == (0, 0, 0) def are_collinear(a: Point3d, b: Point3d, c: Point3d, accuracy: int = 10) -> bool: """ Check if three points are collinear or not. 1- Create tow vectors AB and AC. 2- Get the cross vector of the tow vectors. 3- Calcolate the length of the cross vector. 4- If the length is zero then the points are collinear, else they are not. The use of the accuracy parameter is explained in is_zero_vector docstring. >>> are_collinear((4.802293498137402, 3.536233125455244, 0), ... (-2.186788107953106, -9.24561398001649, 7.141509524846482), ... (1.530169574640268, -2.447927606600034, 3.343487096469054)) True >>> are_collinear((-6, -2, 6), ... (6.200213806439997, -4.930157614926678, -4.482371908289856), ... (-4.085171149525941, -2.459889509029438, 4.354787180795383)) True >>> are_collinear((2.399001826862445, -2.452009976680793, 4.464656666157666), ... (-3.682816335934376, 5.753788986533145, 9.490993909044244), ... (1.962903518985307, 3.741415730125627, 7)) False >>> are_collinear((1.875375340689544, -7.268426006071538, 7.358196269835993), ... (-3.546599383667157, -4.630005261513976, 3.208784032924246), ... (-2.564606140206386, 3.937845170672183, 7)) False """ ab = create_vector(a, b) ac = create_vector(a, c) return is_zero_vector(get_3d_vectors_cross(ab, ac), accuracy)
Use Pollard's Rho algorithm to return a nontrivial factor of num. The returned factor may be composite and require further factorization. If the algorithm will return None if it fails to find a factor within the specified number of attempts or within the specified number of steps. If num is prime, this algorithm is guaranteed to return None. https:en.wikipedia.orgwikiPollard27srhoalgorithm pollardrho18446744073709551617 274177 pollardrho97546105601219326301 9876543191 pollardrho100 2 pollardrho17 pollardrho173 17 pollardrho173, attempts1 pollardrho357 21 pollardrho1 Traceback most recent call last: ... ValueError: The input value cannot be less than 2 A value less than 2 can cause an infinite loop in the algorithm. Because of the relationship between ffx and fx, this algorithm struggles to find factors that are divisible by two. As a workaround, we specifically check for two and even inputs. See: https:math.stackexchange.coma2856214165820 Pollard's Rho algorithm requires a function that returns pseudorandom values between 0 X num. It doesn't need to be random in the sense that the output value is cryptographically secure or difficult to calculate, it only needs to be random in the sense that all output values should be equally likely to appear. For this reason, Pollard suggested using fx x2 1 num However, the success of Pollard's algorithm isn't guaranteed and is determined in part by the initial seed and the chosen random function. To make retries easier, we will instead use fx x2 C num where C is a value that we can modify between each attempt. Returns a pseudorandom value modulo modulus based on the input value and attemptspecific step size. randfn0, 0, 0 Traceback most recent call last: ... ZeroDivisionError: integer division or modulo by zero randfn1, 2, 3 0 randfn0, 10, 7 3 randfn1234, 1, 17 16 These track the position within the cycle detection logic. At each iteration, the tortoise moves one step and the hare moves two. At some point both the tortoise and the hare will enter a cycle whose length p is a divisor of num. Once in that cycle, at some point the tortoise and hare will end up on the same value modulo p. We can detect when this happens because the position difference between the tortoise and the hare will share a common divisor with num. No common divisor yet, just keep searching. We found a common divisor! Unfortunately, the divisor is num itself and is useless. The divisor is a nontrivial factor of num! If we made it here, then this attempt failed. We need to pick a new starting seed for the tortoise and hare in addition to a new step value for the random function. To keep this example implementation deterministic, the new values will be generated based on currently available values instead of using something like random.randint. We can use the hare's position as the new seed. This is actually what Richard Brent's the optimized variant does. The new step value for the random function can just be incremented. At first the results will be similar to what the old function would have produced, but the value will quickly diverge after a bit. We haven't found a divisor within the requested number of attempts. We were unlucky or num itself is actually prime.
from __future__ import annotations from math import gcd def pollard_rho( num: int, seed: int = 2, step: int = 1, attempts: int = 3, ) -> int | None: """ Use Pollard's Rho algorithm to return a nontrivial factor of ``num``. The returned factor may be composite and require further factorization. If the algorithm will return None if it fails to find a factor within the specified number of attempts or within the specified number of steps. If ``num`` is prime, this algorithm is guaranteed to return None. https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm >>> pollard_rho(18446744073709551617) 274177 >>> pollard_rho(97546105601219326301) 9876543191 >>> pollard_rho(100) 2 >>> pollard_rho(17) >>> pollard_rho(17**3) 17 >>> pollard_rho(17**3, attempts=1) >>> pollard_rho(3*5*7) 21 >>> pollard_rho(1) Traceback (most recent call last): ... ValueError: The input value cannot be less than 2 """ # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError("The input value cannot be less than 2") # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(value: int, step: int, modulus: int) -> int: """ Returns a pseudorandom value modulo ``modulus`` based on the input ``value`` and attempt-specific ``step`` size. >>> rand_fn(0, 0, 0) Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero >>> rand_fn(1, 2, 3) 0 >>> rand_fn(0, 10, 7) 3 >>> rand_fn(1234, 1, 17) 16 """ return (pow(value, 2) + step) % modulus for _ in range(attempts): # These track the position within the cycle detection logic. tortoise = seed hare = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. tortoise = rand_fn(tortoise, step, num) hare = rand_fn(hare, step, num) hare = rand_fn(hare, step, num) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. divisor = gcd(hare - tortoise, num) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. seed = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument( "num", type=int, help="The value to find a divisor of", ) parser.add_argument( "--attempts", type=int, default=3, help="The number of attempts before giving up", ) args = parser.parse_args() divisor = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(f"{args.num} is probably prime") else: quotient = args.num // divisor print(f"{args.num} = {divisor} * {quotient}")
Evaluate a polynomial fx at specified point x and return the value. Arguments: poly the coefficients of a polynomial as an iterable in order of ascending degree x the point at which to evaluate the polynomial evaluatepoly0.0, 0.0, 5.0, 9.3, 7.0, 10.0 79800.0 Evaluate a polynomial at specified point using Horner's method. In terms of computational complexity, Horner's method is an efficient method of evaluating a polynomial. It avoids the use of expensive exponentiation, and instead uses only multiplication and addition to evaluate the polynomial in On, where n is the degree of the polynomial. https:en.wikipedia.orgwikiHorner'smethod Arguments: poly the coefficients of a polynomial as an iterable in order of ascending degree x the point at which to evaluate the polynomial horner0.0, 0.0, 5.0, 9.3, 7.0, 10.0 79800.0 Example: poly 0.0, 0.0, 5.0, 9.3, 7.0 fx 7.0x4 9.3x3 5.0x2 x 13.0 f13 7.0134 9.3133 5.0132 180339.9 evaluatepolypoly, x 180339.9
from collections.abc import Sequence def evaluate_poly(poly: Sequence[float], x: float) -> float: """Evaluate a polynomial f(x) at specified point x and return the value. Arguments: poly -- the coefficients of a polynomial as an iterable in order of ascending degree x -- the point at which to evaluate the polynomial >>> evaluate_poly((0.0, 0.0, 5.0, 9.3, 7.0), 10.0) 79800.0 """ return sum(c * (x**i) for i, c in enumerate(poly)) def horner(poly: Sequence[float], x: float) -> float: """Evaluate a polynomial at specified point using Horner's method. In terms of computational complexity, Horner's method is an efficient method of evaluating a polynomial. It avoids the use of expensive exponentiation, and instead uses only multiplication and addition to evaluate the polynomial in O(n), where n is the degree of the polynomial. https://en.wikipedia.org/wiki/Horner's_method Arguments: poly -- the coefficients of a polynomial as an iterable in order of ascending degree x -- the point at which to evaluate the polynomial >>> horner((0.0, 0.0, 5.0, 9.3, 7.0), 10.0) 79800.0 """ result = 0.0 for coeff in reversed(poly): result = result * x + coeff return result if __name__ == "__main__": """ Example: >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7.0x^4 + 9.3x^3 + 5.0x^2 >>> x = -13.0 >>> # f(-13) = 7.0(-13)^4 + 9.3(-13)^3 + 5.0(-13)^2 = 180339.9 >>> evaluate_poly(poly, x) 180339.9 """ poly = (0.0, 0.0, 5.0, 9.3, 7.0) x = 10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
This module implements a single indeterminate polynomials class with some basic operations Reference: https:en.wikipedia.orgwikiPolynomial The coefficients should be in order of degree, from smallest to largest. p Polynomial2, 1, 2, 3 p Polynomial2, 1, 2, 3, 4 Traceback most recent call last: ... ValueError: The number of coefficients should be equal to the degree 1. Polynomial addition p Polynomial2, 1, 2, 3 q Polynomial2, 1, 2, 3 p q 6x2 4x 2 Polynomial subtraction p Polynomial2, 1, 2, 4 q Polynomial2, 1, 2, 3 p q 1x2 Polynomial negation p Polynomial2, 1, 2, 3 p 3x2 2x 1 Polynomial multiplication p Polynomial2, 1, 2, 3 q Polynomial2, 1, 2, 3 p q 9x4 12x3 10x2 4x 1 Evaluates the polynomial at x. p Polynomial2, 1, 2, 3 p.evaluate2 17 p Polynomial2, 1, 2, 3 printp 3x2 2x 1 p Polynomial2, 1, 2, 3 p 3x2 2x 1 Returns the derivative of the polynomial. p Polynomial2, 1, 2, 3 p.derivative 6x 2 Returns the integral of the polynomial. p Polynomial2, 1, 2, 3 p.integral 1.0x3 1.0x2 1.0x Checks if two polynomials are equal. p Polynomial2, 1, 2, 3 q Polynomial2, 1, 2, 3 p q True Checks if two polynomials are not equal. p Polynomial2, 1, 2, 3 q Polynomial2, 1, 2, 3 p ! q False
from __future__ import annotations from collections.abc import MutableSequence class Polynomial: def __init__(self, degree: int, coefficients: MutableSequence[float]) -> None: """ The coefficients should be in order of degree, from smallest to largest. >>> p = Polynomial(2, [1, 2, 3]) >>> p = Polynomial(2, [1, 2, 3, 4]) Traceback (most recent call last): ... ValueError: The number of coefficients should be equal to the degree + 1. """ if len(coefficients) != degree + 1: raise ValueError( "The number of coefficients should be equal to the degree + 1." ) self.coefficients: list[float] = list(coefficients) self.degree = degree def __add__(self, polynomial_2: Polynomial) -> Polynomial: """ Polynomial addition >>> p = Polynomial(2, [1, 2, 3]) >>> q = Polynomial(2, [1, 2, 3]) >>> p + q 6x^2 + 4x + 2 """ if self.degree > polynomial_2.degree: coefficients = self.coefficients[:] for i in range(polynomial_2.degree + 1): coefficients[i] += polynomial_2.coefficients[i] return Polynomial(self.degree, coefficients) else: coefficients = polynomial_2.coefficients[:] for i in range(self.degree + 1): coefficients[i] += self.coefficients[i] return Polynomial(polynomial_2.degree, coefficients) def __sub__(self, polynomial_2: Polynomial) -> Polynomial: """ Polynomial subtraction >>> p = Polynomial(2, [1, 2, 4]) >>> q = Polynomial(2, [1, 2, 3]) >>> p - q 1x^2 """ return self + polynomial_2 * Polynomial(0, [-1]) def __neg__(self) -> Polynomial: """ Polynomial negation >>> p = Polynomial(2, [1, 2, 3]) >>> -p - 3x^2 - 2x - 1 """ return Polynomial(self.degree, [-c for c in self.coefficients]) def __mul__(self, polynomial_2: Polynomial) -> Polynomial: """ Polynomial multiplication >>> p = Polynomial(2, [1, 2, 3]) >>> q = Polynomial(2, [1, 2, 3]) >>> p * q 9x^4 + 12x^3 + 10x^2 + 4x + 1 """ coefficients: list[float] = [0] * (self.degree + polynomial_2.degree + 1) for i in range(self.degree + 1): for j in range(polynomial_2.degree + 1): coefficients[i + j] += ( self.coefficients[i] * polynomial_2.coefficients[j] ) return Polynomial(self.degree + polynomial_2.degree, coefficients) def evaluate(self, substitution: float) -> float: """ Evaluates the polynomial at x. >>> p = Polynomial(2, [1, 2, 3]) >>> p.evaluate(2) 17 """ result: int | float = 0 for i in range(self.degree + 1): result += self.coefficients[i] * (substitution**i) return result def __str__(self) -> str: """ >>> p = Polynomial(2, [1, 2, 3]) >>> print(p) 3x^2 + 2x + 1 """ polynomial = "" for i in range(self.degree, -1, -1): if self.coefficients[i] == 0: continue elif self.coefficients[i] > 0: if polynomial: polynomial += " + " else: polynomial += " - " if i == 0: polynomial += str(abs(self.coefficients[i])) elif i == 1: polynomial += str(abs(self.coefficients[i])) + "x" else: polynomial += str(abs(self.coefficients[i])) + "x^" + str(i) return polynomial def __repr__(self) -> str: """ >>> p = Polynomial(2, [1, 2, 3]) >>> p 3x^2 + 2x + 1 """ return self.__str__() def derivative(self) -> Polynomial: """ Returns the derivative of the polynomial. >>> p = Polynomial(2, [1, 2, 3]) >>> p.derivative() 6x + 2 """ coefficients: list[float] = [0] * self.degree for i in range(self.degree): coefficients[i] = self.coefficients[i + 1] * (i + 1) return Polynomial(self.degree - 1, coefficients) def integral(self, constant: float = 0) -> Polynomial: """ Returns the integral of the polynomial. >>> p = Polynomial(2, [1, 2, 3]) >>> p.integral() 1.0x^3 + 1.0x^2 + 1.0x """ coefficients: list[float] = [0] * (self.degree + 2) coefficients[0] = constant for i in range(self.degree + 1): coefficients[i + 1] = self.coefficients[i] / (i + 1) return Polynomial(self.degree + 1, coefficients) def __eq__(self, polynomial_2: object) -> bool: """ Checks if two polynomials are equal. >>> p = Polynomial(2, [1, 2, 3]) >>> q = Polynomial(2, [1, 2, 3]) >>> p == q True """ if not isinstance(polynomial_2, Polynomial): return False if self.degree != polynomial_2.degree: return False for i in range(self.degree + 1): if self.coefficients[i] != polynomial_2.coefficients[i]: return False return True def __ne__(self, polynomial_2: object) -> bool: """ Checks if two polynomials are not equal. >>> p = Polynomial(2, [1, 2, 3]) >>> q = Polynomial(2, [1, 2, 3]) >>> p != q False """ return not self.__eq__(polynomial_2)
Raise base to the power of exponent using recursion Input Enter the base: 3 Enter the exponent: 4 Output 3 to the power of 4 is 81 Input Enter the base: 2 Enter the exponent: 0 Output 2 to the power of 0 is 1 Calculate the power of a base raised to an exponent. power3, 4 81 power2, 0 1 allpowerbase, exponent powbase, exponent ... for base in range10, 10 for exponent in range10 True power'a', 1 'a' power'a', 2 Traceback most recent call last: ... TypeError: can't multiply sequence by nonint of type 'str' power'a', 'b' Traceback most recent call last: ... TypeError: unsupported operand types for : 'str' and 'int' power2, 1 Traceback most recent call last: ... RecursionError: maximum recursion depth exceeded
def power(base: int, exponent: int) -> float: """ Calculate the power of a base raised to an exponent. >>> power(3, 4) 81 >>> power(2, 0) 1 >>> all(power(base, exponent) == pow(base, exponent) ... for base in range(-10, 10) for exponent in range(10)) True >>> power('a', 1) 'a' >>> power('a', 2) Traceback (most recent call last): ... TypeError: can't multiply sequence by non-int of type 'str' >>> power('a', 'b') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'str' and 'int' >>> power(2, -1) Traceback (most recent call last): ... RecursionError: maximum recursion depth exceeded """ return base * power(base, (exponent - 1)) if exponent else 1 if __name__ == "__main__": from doctest import testmod testmod() print("Raise base to the power of exponent using recursion...") base = int(input("Enter the base: ").strip()) exponent = int(input("Enter the exponent: ").strip()) result = power(base, abs(exponent)) if exponent < 0: # power() does not properly deal w/ negative exponents result = 1 / result print(f"{base} to the power of {exponent} is {result}")
Prime Check. import math import unittest import pytest def isprimenumber: int bool: precondition if not isinstancenumber, int or not number 0: raise ValueErrorisprime only accepts positive integers if 1 number 4: 2 and 3 are primes return True elif number 2 or number 2 0 or number 3 0: Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False All primes number are in format of 6k 1 for i in range5, intmath.sqrtnumber 1, 6: if number i 0 or number i 2 0: return False return True class Testunittest.TestCase: def testprimesself: assert isprime2 assert isprime3 assert isprime5 assert isprime7 assert isprime11 assert isprime13 assert isprime17 assert isprime19 assert isprime23 assert isprime29 def testnotprimesself: with pytest.raisesValueError: isprime19 assert not isprime 0 , Zero doesn't have any positive factors, primes must have exactly two. assert not isprime 1 , One only has 1 positive factor, primes must have exactly two. assert not isprime2 2 assert not isprime2 3 assert not isprime3 3 assert not isprime3 5 assert not isprime3 5 7 if name main: unittest.main
import math import unittest import pytest def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False >>> is_prime(16.1) Traceback (most recent call last): ... ValueError: is_prime() only accepts positive integers >>> is_prime(-4) Traceback (most recent call last): ... ValueError: is_prime() only accepts positive integers """ # precondition if not isinstance(number, int) or not number >= 0: raise ValueError("is_prime() only accepts positive integers") if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True class Test(unittest.TestCase): def test_primes(self): assert is_prime(2) assert is_prime(3) assert is_prime(5) assert is_prime(7) assert is_prime(11) assert is_prime(13) assert is_prime(17) assert is_prime(19) assert is_prime(23) assert is_prime(29) def test_not_primes(self): with pytest.raises(ValueError): is_prime(-19) assert not is_prime( 0 ), "Zero doesn't have any positive factors, primes must have exactly two." assert not is_prime( 1 ), "One only has 1 positive factor, primes must have exactly two." assert not is_prime(2 * 2) assert not is_prime(2 * 3) assert not is_prime(3 * 3) assert not is_prime(3 * 5) assert not is_prime(3 * 5 * 7) if __name__ == "__main__": unittest.main()
pythonblack : True Returns prime factors of n as a list. primefactors0 primefactors100 2, 2, 5, 5 primefactors2560 2, 2, 2, 2, 2, 2, 2, 2, 2, 5 primefactors102 primefactors0.02 x primefactors10241 doctest: NORMALIZEWHITESPACE x 2241 5241 True primefactors10354 primefactors'hello' Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'str' primefactors1,2,'hello' Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'list'
from __future__ import annotations def prime_factors(n: int) -> list[int]: """ Returns prime factors of n as a list. >>> prime_factors(0) [] >>> prime_factors(100) [2, 2, 5, 5] >>> prime_factors(2560) [2, 2, 2, 2, 2, 2, 2, 2, 2, 5] >>> prime_factors(10**-2) [] >>> prime_factors(0.02) [] >>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE >>> x == [2]*241 + [5]*241 True >>> prime_factors(10**-354) [] >>> prime_factors('hello') Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> prime_factors([1,2,'hello']) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors if __name__ == "__main__": import doctest doctest.testmod()
Return a list of all primes numbers up to max. listslowprimes0 listslowprimes1 listslowprimes10 listslowprimes25 2, 3, 5, 7, 11, 13, 17, 19, 23 listslowprimes11 2, 3, 5, 7, 11 listslowprimes33 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 listslowprimes10001 997 Return a list of all primes numbers up to max. listprimes0 listprimes1 listprimes10 listprimes25 2, 3, 5, 7, 11, 13, 17, 19, 23 listprimes11 2, 3, 5, 7, 11 listprimes33 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 listprimes10001 997 only need to check for factors up to sqrti Return a list of all primes numbers up to max. listfastprimes0 listfastprimes1 listfastprimes10 listfastprimes25 2, 3, 5, 7, 11, 13, 17, 19, 23 listfastprimes11 2, 3, 5, 7, 11 listfastprimes33 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 listfastprimes10001 997 It's useless to test even numbers as they will not be prime As we removed the even numbers, we don't need them now Let's benchmark our functions sidebyside...
import math from collections.abc import Generator def slow_primes(max_n: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(slow_primes(0)) [] >>> list(slow_primes(-1)) [] >>> list(slow_primes(-10)) [] >>> list(slow_primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(slow_primes(11)) [2, 3, 5, 7, 11] >>> list(slow_primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(slow_primes(1000))[-1] 997 """ numbers: Generator = (i for i in range(1, (max_n + 1))) for i in (n for n in numbers if n > 1): for j in range(2, i): if (i % j) == 0: break else: yield i def primes(max_n: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(primes(0)) [] >>> list(primes(-1)) [] >>> list(primes(-10)) [] >>> list(primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(primes(11)) [2, 3, 5, 7, 11] >>> list(primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(primes(1000))[-1] 997 """ numbers: Generator = (i for i in range(1, (max_n + 1))) for i in (n for n in numbers if n > 1): # only need to check for factors up to sqrt(i) bound = int(math.sqrt(i)) + 1 for j in range(2, bound): if (i % j) == 0: break else: yield i def fast_primes(max_n: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(fast_primes(0)) [] >>> list(fast_primes(-1)) [] >>> list(fast_primes(-10)) [] >>> list(fast_primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(fast_primes(11)) [2, 3, 5, 7, 11] >>> list(fast_primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(fast_primes(1000))[-1] 997 """ numbers: Generator = (i for i in range(1, (max_n + 1), 2)) # It's useless to test even numbers as they will not be prime if max_n > 2: yield 2 # Because 2 will not be tested, it's necessary to yield it now for i in (n for n in numbers if n > 1): bound = int(math.sqrt(i)) + 1 for j in range(3, bound, 2): # As we removed the even numbers, we don't need them now if (i % j) == 0: break else: yield i def benchmark(): """ Let's benchmark our functions side-by-side... """ from timeit import timeit setup = "from __main__ import slow_primes, primes, fast_primes" print(timeit("slow_primes(1_000_000_000_000)", setup=setup, number=1_000_000)) print(timeit("primes(1_000_000_000_000)", setup=setup, number=1_000_000)) print(timeit("fast_primes(1_000_000_000_000)", setup=setup, number=1_000_000)) if __name__ == "__main__": number = int(input("Calculate primes up to:\n>> ").strip()) for ret in primes(number): print(ret) benchmark()
Sieve of Eratosthenes Input: n 10 Output: 2 3 5 7 Input: n 20 Output: 2 3 5 7 11 13 17 19 you can read in detail about this at https:en.wikipedia.orgwikiSieveofEratosthenes Print the prime numbers up to n primesieveeratosthenes10 2, 3, 5, 7 primesieveeratosthenes20 2, 3, 5, 7, 11, 13, 17, 19 primesieveeratosthenes2 2 primesieveeratosthenes1 primesieveeratosthenes1 Traceback most recent call last: ... ValueError: Input must be a positive integer
def prime_sieve_eratosthenes(num: int) -> list[int]: """ Print the prime numbers up to n >>> prime_sieve_eratosthenes(10) [2, 3, 5, 7] >>> prime_sieve_eratosthenes(20) [2, 3, 5, 7, 11, 13, 17, 19] >>> prime_sieve_eratosthenes(2) [2] >>> prime_sieve_eratosthenes(1) [] >>> prime_sieve_eratosthenes(-1) Traceback (most recent call last): ... ValueError: Input must be a positive integer """ if num <= 0: raise ValueError("Input must be a positive integer") primes = [True] * (num + 1) p = 2 while p * p <= num: if primes[p]: for i in range(p * p, num + 1, p): primes[i] = False p += 1 return [prime for prime in range(2, num + 1) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() user_num = int(input("Enter a positive integer: ").strip()) print(prime_sieve_eratosthenes(user_num))
Created on Thu Oct 5 16:44:23 2017 author: Christian Bender This Python library contains some useful functions to deal with prime numbers and whole numbers. Overview: isprimenumber sieveerN getprimenumbersN primefactorizationnumber greatestprimefactornumber smallestprimefactornumber getprimen getprimesbetweenpNumber1, pNumber2 isevennumber isoddnumber kgvnumber1, number2 least common multiple getdivisorsnumber all divisors of 'number' inclusive 1, number isperfectnumbernumber NEWFUNCTIONS simplifyfractionnumerator, denominator factorial n n! fib n calculate the nth fibonacci term. goldbachnumber Goldbach's assumption input: positive integer 'number' returns true if 'number' is prime otherwise false. isprime3 True isprime10 False isprime97 True isprime9991 False isprime1 Traceback most recent call last: ... AssertionError: 'number' must been an int and positive isprimetest Traceback most recent call last: ... AssertionError: 'number' must been an int and positive precondition 0 and 1 are none primes. if 'number' divisible by 'divisor' then sets 'status' of false and break up the loop. precondition input: positive integer 'N' 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes. sieveer8 2, 3, 5, 7 sieveer1 Traceback most recent call last: ... AssertionError: 'N' must been an int and 2 sieveertest Traceback most recent call last: ... AssertionError: 'N' must been an int and 2 precondition beginList: contains all natural numbers from 2 up to N actual sieve of erathostenes filters actual prime numbers. precondition input: positive integer 'N' 2 returns a list of prime numbers from 2 up to N inclusive This function is more efficient as function 'sieveEr...' getprimenumbers8 2, 3, 5, 7 getprimenumbers1 Traceback most recent call last: ... AssertionError: 'N' must been an int and 2 getprimenumberstest Traceback most recent call last: ... AssertionError: 'N' must been an int and 2 precondition iterates over all numbers between 2 up to N1 if a number is prime then appends to list 'ans' precondition input: positive integer 'number' returns a list of the prime number factors of 'number' primefactorization0 0 primefactorization8 2, 2, 2 primefactorization287 7, 41 primefactorization1 Traceback most recent call last: ... AssertionError: 'number' must been an int and 0 primefactorizationtest Traceback most recent call last: ... AssertionError: 'number' must been an int and 0 precondition potential prime number factors. if 'number' not prime then builds the prime factorization of 'number' precondition input: positive integer 'number' 0 returns the greatest prime number factor of 'number' greatestprimefactor0 0 greatestprimefactor8 2 greatestprimefactor287 41 greatestprimefactor1 Traceback most recent call last: ... AssertionError: 'number' must been an int and 0 greatestprimefactortest Traceback most recent call last: ... AssertionError: 'number' must been an int and 0 precondition prime factorization of 'number' precondition input: integer 'number' 0 returns the smallest prime number factor of 'number' smallestprimefactor0 0 smallestprimefactor8 2 smallestprimefactor287 7 smallestprimefactor1 Traceback most recent call last: ... AssertionError: 'number' must been an int and 0 smallestprimefactortest Traceback most recent call last: ... AssertionError: 'number' must been an int and 0 precondition prime factorization of 'number' precondition input: integer 'number' returns true if 'number' is even, otherwise false. iseven0 True iseven8 True iseven287 False iseven1 False iseventest Traceback most recent call last: ... AssertionError: 'number' must been an int precondition input: integer 'number' returns true if 'number' is odd, otherwise false. isodd0 False isodd8 False isodd287 True isodd1 True isoddtest Traceback most recent call last: ... AssertionError: 'number' must been an int precondition Goldbach's assumption input: a even positive integer 'number' 2 returns a list of two prime numbers whose sum is equal to 'number' goldbach8 3, 5 goldbach824 3, 821 goldbach0 Traceback most recent call last: ... AssertionError: 'number' must been an int, even and 2 goldbach1 Traceback most recent call last: ... AssertionError: 'number' must been an int, even and 2 goldbachtest Traceback most recent call last: ... AssertionError: 'number' must been an int, even and 2 precondition creates a list of prime numbers between 2 up to 'number' run variable for whileloops. exit variable. for break up the loops precondition Least common multiple input: two positive integer 'number1' and 'number2' returns the least common multiple of 'number1' and 'number2' kgv8,10 40 kgv824,67 55208 kgv1, 10 10 kgv0 Traceback most recent call last: ... TypeError: kgv missing 1 required positional argument: 'number2' kgv10,1 Traceback most recent call last: ... AssertionError: 'number1' and 'number2' must been positive integer. kgvtest,test2 Traceback most recent call last: ... AssertionError: 'number1' and 'number2' must been positive integer. precondition for kgV x,1 builds the prime factorization of 'number1' and 'number2' iterates through primeFac1 iterates through primeFac2 precondition Gets the nth prime number. input: positive integer 'n' 0 returns the nth prime number, beginning at index 0 getprime0 2 getprime8 23 getprime824 6337 getprime1 Traceback most recent call last: ... AssertionError: 'number' must been a positive int getprimetest Traceback most recent call last: ... AssertionError: 'number' must been a positive int precondition if ans not prime then runs to the next prime number. precondition input: prime numbers 'pNumber1' and 'pNumber2' pNumber1 pNumber2 returns a list of all prime numbers between 'pNumber1' exclusive and 'pNumber2' exclusive getprimesbetween3, 67 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61 getprimesbetween0 Traceback most recent call last: ... TypeError: getprimesbetween missing 1 required positional argument: 'pnumber2' getprimesbetween0, 1 Traceback most recent call last: ... AssertionError: The arguments must been prime numbers and 'pNumber1' 'pNumber2' getprimesbetween1, 3 Traceback most recent call last: ... AssertionError: 'number' must been an int and positive getprimesbetweentest,test Traceback most recent call last: ... AssertionError: 'number' must been an int and positive precondition if number is not prime then fetch the next prime number. fetch the next prime number. precondition 'ans' contains not 'pNumber1' and 'pNumber2' ! input: positive integer 'n' 1 returns all divisors of n inclusive 1 and 'n' getdivisors8 1, 2, 4, 8 getdivisors824 1, 2, 4, 8, 103, 206, 412, 824 getdivisors1 Traceback most recent call last: ... AssertionError: 'n' must been int and 1 getdivisorstest Traceback most recent call last: ... AssertionError: 'n' must been int and 1 precondition precondition input: positive integer 'number' 1 returns true if 'number' is a perfect number otherwise false. isperfectnumber28 True isperfectnumber824 False isperfectnumber1 Traceback most recent call last: ... AssertionError: 'number' must been an int and 1 isperfectnumbertest Traceback most recent call last: ... AssertionError: 'number' must been an int and 1 precondition precondition summed all divisors up to 'number' exclusive, hence :1 input: two integer 'numerator' and 'denominator' assumes: 'denominator' ! 0 returns: a tuple with simplify numerator and denominator. simplifyfraction10, 20 1, 2 simplifyfraction10, 1 10, 1 simplifyfractiontest,test Traceback most recent call last: ... AssertionError: The arguments must been from type int and 'denominator' ! 0 precondition build the greatest common divisor of numerator and denominator. precondition input: positive integer 'n' returns the factorial of 'n' n! factorial0 1 factorial20 2432902008176640000 factorial1 Traceback most recent call last: ... AssertionError: 'n' must been a int and 0 factorialtest Traceback most recent call last: ... AssertionError: 'n' must been a int and 0 precondition input: positive integer 'n' returns the nth fibonacci term , indexing by 0 fib0 1 fib5 8 fib20 10946 fib99 354224848179261915075 fib1 Traceback most recent call last: ... AssertionError: 'n' must been an int and 0 fibtest Traceback most recent call last: ... AssertionError: 'n' must been an int and 0 precondition
from math import sqrt from maths.greatest_common_divisor import gcd_by_iterative def is_prime(number: int) -> bool: """ input: positive integer 'number' returns true if 'number' is prime otherwise false. >>> is_prime(3) True >>> is_prime(10) False >>> is_prime(97) True >>> is_prime(9991) False >>> is_prime(-1) Traceback (most recent call last): ... AssertionError: 'number' must been an int and positive >>> is_prime("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int and positive """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' must been an int and positive" status = True # 0 and 1 are none primes. if number <= 1: status = False for divisor in range(2, int(round(sqrt(number))) + 1): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: status = False break # precondition assert isinstance(status, bool), "'status' must been from type bool" return status # ------------------------------------------ def sieve_er(n): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes. >>> sieve_er(8) [2, 3, 5, 7] >>> sieve_er(-1) Traceback (most recent call last): ... AssertionError: 'N' must been an int and > 2 >>> sieve_er("test") Traceback (most recent call last): ... AssertionError: 'N' must been an int and > 2 """ # precondition assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N begin_list = list(range(2, n + 1)) ans = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(begin_list)): for j in range(i + 1, len(begin_list)): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): begin_list[j] = 0 # filters actual prime numbers. ans = [x for x in begin_list if x != 0] # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # -------------------------------- def get_prime_numbers(n): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N (inclusive) This function is more efficient as function 'sieveEr(...)' >>> get_prime_numbers(8) [2, 3, 5, 7] >>> get_prime_numbers(-1) Traceback (most recent call last): ... AssertionError: 'N' must been an int and > 2 >>> get_prime_numbers("test") Traceback (most recent call last): ... AssertionError: 'N' must been an int and > 2 """ # precondition assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2" ans = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2, n + 1): if is_prime(number): ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # ----------------------------------------- def prime_factorization(number): """ input: positive integer 'number' returns a list of the prime number factors of 'number' >>> prime_factorization(0) [0] >>> prime_factorization(8) [2, 2, 2] >>> prime_factorization(287) [7, 41] >>> prime_factorization(-1) Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 0 >>> prime_factorization("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 0 """ # precondition assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0" ans = [] # this list will be returns of the function. # potential prime number factors. factor = 2 quotient = number if number in {0, 1}: ans.append(number) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(number): while quotient != 1: if is_prime(factor) and (quotient % factor == 0): ans.append(factor) quotient /= factor else: factor += 1 else: ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # ----------------------------------------- def greatest_prime_factor(number): """ input: positive integer 'number' >= 0 returns the greatest prime number factor of 'number' >>> greatest_prime_factor(0) 0 >>> greatest_prime_factor(8) 2 >>> greatest_prime_factor(287) 41 >>> greatest_prime_factor(-1) Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 0 >>> greatest_prime_factor("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 0 """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' must been an int and >= 0" ans = 0 # prime factorization of 'number' prime_factors = prime_factorization(number) ans = max(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------------------------------- def smallest_prime_factor(number): """ input: integer 'number' >= 0 returns the smallest prime number factor of 'number' >>> smallest_prime_factor(0) 0 >>> smallest_prime_factor(8) 2 >>> smallest_prime_factor(287) 7 >>> smallest_prime_factor(-1) Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 0 >>> smallest_prime_factor("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 0 """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' must been an int and >= 0" ans = 0 # prime factorization of 'number' prime_factors = prime_factorization(number) ans = min(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------- def is_even(number): """ input: integer 'number' returns true if 'number' is even, otherwise false. >>> is_even(0) True >>> is_even(8) True >>> is_even(287) False >>> is_even(-1) False >>> is_even("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 == 0, bool), "compare must been from type bool" return number % 2 == 0 # ------------------------ def is_odd(number): """ input: integer 'number' returns true if 'number' is odd, otherwise false. >>> is_odd(0) False >>> is_odd(8) False >>> is_odd(287) True >>> is_odd(-1) True >>> is_odd("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 != 0, bool), "compare must been from type bool" return number % 2 != 0 # ------------------------ def goldbach(number): """ Goldbach's assumption input: a even positive integer 'number' > 2 returns a list of two prime numbers whose sum is equal to 'number' >>> goldbach(8) [3, 5] >>> goldbach(824) [3, 821] >>> goldbach(0) Traceback (most recent call last): ... AssertionError: 'number' must been an int, even and > 2 >>> goldbach(-1) Traceback (most recent call last): ... AssertionError: 'number' must been an int, even and > 2 >>> goldbach("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int, even and > 2 """ # precondition assert ( isinstance(number, int) and (number > 2) and is_even(number) ), "'number' must been an int, even and > 2" ans = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' prime_numbers = get_prime_numbers(number) len_pn = len(prime_numbers) # run variable for while-loops. i = 0 j = None # exit variable. for break up the loops loop = True while i < len_pn and loop: j = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: loop = False ans.append(prime_numbers[i]) ans.append(prime_numbers[j]) j += 1 i += 1 # precondition assert ( isinstance(ans, list) and (len(ans) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0]) and is_prime(ans[1]) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans # ---------------------------------------------- def kg_v(number1, number2): """ Least common multiple input: two positive integer 'number1' and 'number2' returns the least common multiple of 'number1' and 'number2' >>> kg_v(8,10) 40 >>> kg_v(824,67) 55208 >>> kg_v(1, 10) 10 >>> kg_v(0) Traceback (most recent call last): ... TypeError: kg_v() missing 1 required positional argument: 'number2' >>> kg_v(10,-1) Traceback (most recent call last): ... AssertionError: 'number1' and 'number2' must been positive integer. >>> kg_v("test","test2") Traceback (most recent call last): ... AssertionError: 'number1' and 'number2' must been positive integer. """ # precondition assert ( isinstance(number1, int) and isinstance(number2, int) and (number1 >= 1) and (number2 >= 1) ), "'number1' and 'number2' must been positive integer." ans = 1 # actual answer that will be return. # for kgV (x,1) if number1 > 1 and number2 > 1: # builds the prime factorization of 'number1' and 'number2' prime_fac_1 = prime_factorization(number1) prime_fac_2 = prime_factorization(number2) elif number1 == 1 or number2 == 1: prime_fac_1 = [] prime_fac_2 = [] ans = max(number1, number2) count1 = 0 count2 = 0 done = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_1: if n not in done: if n in prime_fac_2: count1 = prime_fac_1.count(n) count2 = prime_fac_2.count(n) for _ in range(max(count1, count2)): ans *= n else: count1 = prime_fac_1.count(n) for _ in range(count1): ans *= n done.append(n) # iterates through primeFac2 for n in prime_fac_2: if n not in done: count2 = prime_fac_2.count(n) for _ in range(count2): ans *= n done.append(n) # precondition assert isinstance(ans, int) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans # ---------------------------------- def get_prime(n): """ Gets the n-th prime number. input: positive integer 'n' >= 0 returns the n-th prime number, beginning at index 0 >>> get_prime(0) 2 >>> get_prime(8) 23 >>> get_prime(824) 6337 >>> get_prime(-1) Traceback (most recent call last): ... AssertionError: 'number' must been a positive int >>> get_prime("test") Traceback (most recent call last): ... AssertionError: 'number' must been a positive int """ # precondition assert isinstance(n, int) and (n >= 0), "'number' must been a positive int" index = 0 ans = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(ans): ans += 1 # precondition assert isinstance(ans, int) and is_prime( ans ), "'ans' must been a prime number and from type int" return ans # --------------------------------------------------- def get_primes_between(p_number_1, p_number_2): """ input: prime numbers 'pNumber1' and 'pNumber2' pNumber1 < pNumber2 returns a list of all prime numbers between 'pNumber1' (exclusive) and 'pNumber2' (exclusive) >>> get_primes_between(3, 67) [5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61] >>> get_primes_between(0) Traceback (most recent call last): ... TypeError: get_primes_between() missing 1 required positional argument: 'p_number_2' >>> get_primes_between(0, 1) Traceback (most recent call last): ... AssertionError: The arguments must been prime numbers and 'pNumber1' < 'pNumber2' >>> get_primes_between(-1, 3) Traceback (most recent call last): ... AssertionError: 'number' must been an int and positive >>> get_primes_between("test","test") Traceback (most recent call last): ... AssertionError: 'number' must been an int and positive """ # precondition assert ( is_prime(p_number_1) and is_prime(p_number_2) and (p_number_1 < p_number_2) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" number = p_number_1 + 1 # jump to the next number ans = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(number): number += 1 while number < p_number_2: ans.append(number) number += 1 # fetch the next prime number. while not is_prime(number): number += 1 # precondition assert ( isinstance(ans, list) and ans[0] != p_number_1 and ans[len(ans) - 1] != p_number_2 ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans # ---------------------------------------------------- def get_divisors(n): """ input: positive integer 'n' >= 1 returns all divisors of n (inclusive 1 and 'n') >>> get_divisors(8) [1, 2, 4, 8] >>> get_divisors(824) [1, 2, 4, 8, 103, 206, 412, 824] >>> get_divisors(-1) Traceback (most recent call last): ... AssertionError: 'n' must been int and >= 1 >>> get_divisors("test") Traceback (most recent call last): ... AssertionError: 'n' must been int and >= 1 """ # precondition assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1" ans = [] # will be returned. for divisor in range(1, n + 1): if n % divisor == 0: ans.append(divisor) # precondition assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)" return ans # ---------------------------------------------------- def is_perfect_number(number): """ input: positive integer 'number' > 1 returns true if 'number' is a perfect number otherwise false. >>> is_perfect_number(28) True >>> is_perfect_number(824) False >>> is_perfect_number(-1) Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 1 >>> is_perfect_number("test") Traceback (most recent call last): ... AssertionError: 'number' must been an int and >= 1 """ # precondition assert isinstance(number, int) and ( number > 1 ), "'number' must been an int and >= 1" divisors = get_divisors(number) # precondition assert ( isinstance(divisors, list) and (divisors[0] == 1) and (divisors[len(divisors) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1]) == number # ------------------------------------------------------------ def simplify_fraction(numerator, denominator): """ input: two integer 'numerator' and 'denominator' assumes: 'denominator' != 0 returns: a tuple with simplify numerator and denominator. >>> simplify_fraction(10, 20) (1, 2) >>> simplify_fraction(10, -1) (10, -1) >>> simplify_fraction("test","test") Traceback (most recent call last): ... AssertionError: The arguments must been from type int and 'denominator' != 0 """ # precondition assert ( isinstance(numerator, int) and isinstance(denominator, int) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. gcd_of_fraction = gcd_by_iterative(abs(numerator), abs(denominator)) # precondition assert ( isinstance(gcd_of_fraction, int) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd_by_iterative(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) # ----------------------------------------------------------------- def factorial(n): """ input: positive integer 'n' returns the factorial of 'n' (n!) >>> factorial(0) 1 >>> factorial(20) 2432902008176640000 >>> factorial(-1) Traceback (most recent call last): ... AssertionError: 'n' must been a int and >= 0 >>> factorial("test") Traceback (most recent call last): ... AssertionError: 'n' must been a int and >= 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0" ans = 1 # this will be return. for factor in range(1, n + 1): ans *= factor return ans # ------------------------------------------------------------------- def fib(n: int) -> int: """ input: positive integer 'n' returns the n-th fibonacci term , indexing by 0 >>> fib(0) 1 >>> fib(5) 8 >>> fib(20) 10946 >>> fib(99) 354224848179261915075 >>> fib(-1) Traceback (most recent call last): ... AssertionError: 'n' must been an int and >= 0 >>> fib("test") Traceback (most recent call last): ... AssertionError: 'n' must been an int and >= 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0" tmp = 0 fib1 = 1 ans = 1 # this will be return for _ in range(n - 1): tmp = ans ans += fib1 fib1 = tmp return ans if __name__ == "__main__": import doctest doctest.testmod()
Prints the multiplication table of a given number till the given number of terms printmultiplicationtable3, 5 3 1 3 3 2 6 3 3 9 3 4 12 3 5 15 printmultiplicationtable4, 6 4 1 4 4 2 8 4 3 12 4 4 16 4 5 20 4 6 24
def multiplication_table(number: int, number_of_terms: int) -> str: """ Prints the multiplication table of a given number till the given number of terms >>> print(multiplication_table(3, 5)) 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12 3 * 5 = 15 >>> print(multiplication_table(-4, 6)) -4 * 1 = -4 -4 * 2 = -8 -4 * 3 = -12 -4 * 4 = -16 -4 * 5 = -20 -4 * 6 = -24 """ return "\n".join( f"{number} * {i} = {number * i}" for i in range(1, number_of_terms + 1) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=10))
Uses Pythagoras theorem to calculate the distance between two points in space. import math class Point: def initself, x, y, z: self.x x self.y y self.z z def reprself str: return fPointself.x, self.y, self.z def distancea: Point, b: Point float: return math.sqrtabsb.x a.x 2 b.y a.y 2 b.z a.z 2 if name main: import doctest doctest.testmod
import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: """ >>> point1 = Point(2, -1, 7) >>> point2 = Point(1, -3, 5) >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 """ return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) if __name__ == "__main__": import doctest doctest.testmod()
Return a QRdecomposition of the matrix A using Householder reflection. The QRdecomposition decomposes the matrix A of shape m, n into an orthogonal matrix Q of shape m, m and an upper triangular matrix R of shape m, n. Note that the matrix A does not have to be square. This method of decomposing A uses the Householder reflection, which is numerically stable and of complexity On3. https:en.wikipedia.orgwikiQRdecompositionUsingHouseholderreflections Arguments: A a numpy.ndarray of shape m, n Note: several optimizations can be made for numeric efficiency, but this is intended to demonstrate how it would be represented in a mathematics textbook. In cases where efficiency is particularly important, an optimized version from BLAS should be used. A np.array12, 51, 4, 6, 167, 68, 4, 24, 41, dtypefloat Q, R qrhouseholderA check that the decomposition is correct np.allcloseQR, A True check that Q is orthogonal np.allcloseQQ.T, np.eyeA.shape0 True np.allcloseQ.TQ, np.eyeA.shape0 True check that R is upper triangular np.allclosenp.triuR, R True select a column of modified matrix A': construct first basis vector determine scaling factor construct vector v for Householder reflection construct the Householder matrix pad with ones and zeros as necessary
import numpy as np def qr_householder(a: np.ndarray): """Return a QR-decomposition of the matrix A using Householder reflection. The QR-decomposition decomposes the matrix A of shape (m, n) into an orthogonal matrix Q of shape (m, m) and an upper triangular matrix R of shape (m, n). Note that the matrix A does not have to be square. This method of decomposing A uses the Householder reflection, which is numerically stable and of complexity O(n^3). https://en.wikipedia.org/wiki/QR_decomposition#Using_Householder_reflections Arguments: A -- a numpy.ndarray of shape (m, n) Note: several optimizations can be made for numeric efficiency, but this is intended to demonstrate how it would be represented in a mathematics textbook. In cases where efficiency is particularly important, an optimized version from BLAS should be used. >>> A = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]], dtype=float) >>> Q, R = qr_householder(A) >>> # check that the decomposition is correct >>> np.allclose(Q@R, A) True >>> # check that Q is orthogonal >>> np.allclose(Q@Q.T, np.eye(A.shape[0])) True >>> np.allclose(Q.T@Q, np.eye(A.shape[0])) True >>> # check that R is upper triangular >>> np.allclose(np.triu(R), R) True """ m, n = a.shape t = min(m, n) q = np.eye(m) r = a.copy() for k in range(t - 1): # select a column of modified matrix A': x = r[k:, [k]] # construct first basis vector e1 = np.zeros_like(x) e1[0] = 1.0 # determine scaling factor alpha = np.linalg.norm(x) # construct vector v for Householder reflection v = x + np.sign(x[0]) * alpha * e1 v /= np.linalg.norm(v) # construct the Householder matrix q_k = np.eye(m - k) - 2.0 * v @ v.T # pad with ones and zeros as necessary q_k = np.block([[np.eye(k), np.zeros((k, m - k))], [np.zeros((m - k, k)), q_k]]) q = q @ q_k.T r = q_k @ r return q, r if __name__ == "__main__": import doctest doctest.testmod()
Given the numerical coefficients a, b and c, calculates the roots for any quadratic equation of the form ax2 bx c quadraticrootsa1, b3, c4 1.0, 4.0 quadraticroots5, 6, 1 0.2, 1.0 quadraticroots1, 6, 25 34j, 34j
from __future__ import annotations from cmath import sqrt def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: """ Given the numerical coefficients a, b and c, calculates the roots for any quadratic equation of the form ax^2 + bx + c >>> quadratic_roots(a=1, b=3, c=-4) (1.0, -4.0) >>> quadratic_roots(5, 6, 1) (-0.2, -1.0) >>> quadratic_roots(1, -6, 25) ((3+4j), (3-4j)) """ if a == 0: raise ValueError("Coefficient 'a' must not be zero.") delta = b * b - 4 * a * c root_1 = (-b + sqrt(delta)) / (2 * a) root_2 = (-b - sqrt(delta)) / (2 * a) return ( root_1.real if not root_1.imag else root_1, root_2.real if not root_2.imag else root_2, ) def main(): solution1, solution2 = quadratic_roots(a=5, b=6, c=1) print(f"The solutions are: {solution1} and {solution2}") if __name__ == "__main__": main()
Converts the given angle from degrees to radians https:en.wikipedia.orgwikiRadian radians180 3.141592653589793 radians92 1.6057029118347832 radians274 4.782202150464463 radians109.82 1.9167205845401725 from math import radians as mathradians allabsradiansi mathradiansi 1e8 for i in range2, 361 True
from math import pi def radians(degree: float) -> float: """ Converts the given angle from degrees to radians https://en.wikipedia.org/wiki/Radian >>> radians(180) 3.141592653589793 >>> radians(92) 1.6057029118347832 >>> radians(274) 4.782202150464463 >>> radians(109.82) 1.9167205845401725 >>> from math import radians as math_radians >>> all(abs(radians(i) - math_radians(i)) <= 1e-8 for i in range(-2, 361)) True """ return degree / (180 / pi) if __name__ == "__main__": from doctest import testmod testmod()
Fast Polynomial Multiplication using radix2 fast Fourier Transform. Fast Polynomial Multiplication using radix2 fast Fourier Transform. Reference: https:en.wikipedia.orgwikiCooleyE28093TukeyFFTalgorithmTheradix2DITcase For polynomials of degree m and n the algorithms has complexity Onlogn mlogm The main part of the algorithm is split in two parts: 1 DFT: We compute the discrete fourier transform DFT of A and B using a bottomup dynamic approach 2 multiply: Once we obtain the DFT of AB, we can similarly invert it to obtain AB The class FFT takes two polynomials A and B with complex coefficients as arguments; The two polynomials should be represented as a sequence of coefficients starting from the free term. Thus, for instance x 2x3 could be represented as 0,1,0,2 or 0,1,0,2. The constructor adds some zeros at the end so that the polynomials have the same length which is a power of 2 at least the length of their product. Example: Create two polynomials as sequences A 0, 1, 0, 2 x2x3 B 2, 3, 4, 0 23x4x2 Create an FFT object with them x FFTA, B Print product x.product 2x 3x2 8x3 4x4 6x5 00j, 20j, 30j, 80j, 60j, 80j str test printx A 0x0 1x1 2x0 3x2 B 0x2 1x3 2x4 AB 0x00j 1x20j 2x30j 3x80j 4x60j 5x80j Input as list Remove leading zero coefficients Add 0 to make lengths equal a power of 2 A complex root used for the fourier transform The product Discrete fourier transform of A and B Corner case First half of next step Second half of next step Update multiply the DFTs of A and B and find AB Corner Case Inverse DFT First half of next step Even positions Odd positions Update Unpack Remove leading 0's Overwrite str for print; Shows A, B and AB Unit tests
import mpmath # for roots of unity import numpy as np class FFT: """ Fast Polynomial Multiplication using radix-2 fast Fourier Transform. Reference: https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case For polynomials of degree m and n the algorithms has complexity O(n*logn + m*logm) The main part of the algorithm is split in two parts: 1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a bottom-up dynamic approach - 2) __multiply: Once we obtain the DFT of A*B, we can similarly invert it to obtain A*B The class FFT takes two polynomials A and B with complex coefficients as arguments; The two polynomials should be represented as a sequence of coefficients starting from the free term. Thus, for instance x + 2*x^3 could be represented as [0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the polynomials have the same length which is a power of 2 at least the length of their product. Example: Create two polynomials as sequences >>> A = [0, 1, 0, 2] # x+2x^3 >>> B = (2, 3, 4, 0) # 2+3x+4x^2 Create an FFT object with them >>> x = FFT(A, B) Print product >>> x.product # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5 [(-0+0j), (2+0j), (3+0j), (8+0j), (6+0j), (8+0j)] __str__ test >>> print(x) A = 0*x^0 + 1*x^1 + 2*x^0 + 3*x^2 B = 0*x^2 + 1*x^3 + 2*x^4 A*B = 0*x^(-0+0j) + 1*x^(2+0j) + 2*x^(3+0j) + 3*x^(8+0j) + 4*x^(6+0j) + 5*x^(8+0j) """ def __init__(self, poly_a=None, poly_b=None): # Input as list self.polyA = list(poly_a or [0])[:] self.polyB = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() self.len_A = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() self.len_B = len(self.polyB) # Add 0 to make lengths equal a power of 2 self.c_max_length = int( 2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1)) ) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform self.root = complex(mpmath.root(x=1, n=self.c_max_length, k=1)) # The product self.product = self.__multiply() # Discrete fourier transform of A and B def __dft(self, which): dft = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB] # Corner case if len(dft) <= 1: return dft[0] # next_ncol = self.c_max_length // 2 while next_ncol > 0: new_dft = [[] for i in range(next_ncol)] root = self.root**next_ncol # First half of next step current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update dft = new_dft next_ncol = next_ncol // 2 return dft[0] # multiply the DFTs of A and B and find A*B def __multiply(self): dft_a = self.__dft("A") dft_b = self.__dft("B") inverce_c = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT next_ncol = 2 while next_ncol <= self.c_max_length: new_inverse_c = [[] for i in range(next_ncol)] root = self.root ** (next_ncol // 2) current_root = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update inverce_c = new_inverse_c next_ncol *= 2 # Unpack inverce_c = [round(x[0].real, 8) + round(x[0].imag, 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c # Overwrite __str__ for print(); Shows A, B and A*B def __str__(self): a = "A = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyA[: self.len_A]) ) b = "B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyB[: self.len_B]) ) c = "A*B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.product) ) return f"{a}\n{b}\n{c}" # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
returns the biggest possible result that can be achieved by removing one digit from the given number removedigit152 52 removedigit6385 685 removedigit11 1 removedigit2222222 222222 removedigit2222222 Traceback most recent call last: TypeError: only integers accepted as input removedigitstring input Traceback most recent call last: TypeError: only integers accepted as input
def remove_digit(num: int) -> int: """ returns the biggest possible result that can be achieved by removing one digit from the given number >>> remove_digit(152) 52 >>> remove_digit(6385) 685 >>> remove_digit(-11) 1 >>> remove_digit(2222222) 222222 >>> remove_digit("2222222") Traceback (most recent call last): TypeError: only integers accepted as input >>> remove_digit("string input") Traceback (most recent call last): TypeError: only integers accepted as input """ if not isinstance(num, int): raise TypeError("only integers accepted as input") else: num_str = str(abs(num)) num_transpositions = [list(num_str) for char in range(len(num_str))] for index in range(len(num_str)): num_transpositions[index].pop(index) return max( int("".join(list(transposition))) for transposition in num_transpositions ) if __name__ == "__main__": __import__("doctest").testmod()
Segmented Sieve. import math def sieven: int listint: if n 0 or isinstancen, float: msg fNumber n must instead be a positive integer raise ValueErrormsg inprime start 2 end intmath.sqrtn Size of every segment temp True end 1 prime while start end: if tempstart is True: inprime.appendstart for i in rangestart start, end 1, start: tempi False start 1 prime inprime low end 1 high min2 end, n while low n: temp True high low 1 for each in inprime: t math.floorlow each each if t low: t each for j in ranget, high 1, each: tempj low False for j in rangelentemp: if tempj is True: prime.appendj low low high 1 high minhigh end, n return prime if name main: import doctest doctest.testmod printfsieve106
import math def sieve(n: int) -> list[int]: """ Segmented Sieve. Examples: >>> sieve(8) [2, 3, 5, 7] >>> sieve(27) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> sieve(0) Traceback (most recent call last): ... ValueError: Number 0 must instead be a positive integer >>> sieve(-1) Traceback (most recent call last): ... ValueError: Number -1 must instead be a positive integer >>> sieve(22.2) Traceback (most recent call last): ... ValueError: Number 22.2 must instead be a positive integer """ if n <= 0 or isinstance(n, float): msg = f"Number {n} must instead be a positive integer" raise ValueError(msg) in_prime = [] start = 2 end = int(math.sqrt(n)) # Size of every segment temp = [True] * (end + 1) prime = [] while start <= end: if temp[start] is True: in_prime.append(start) for i in range(start * start, end + 1, start): temp[i] = False start += 1 prime += in_prime low = end + 1 high = min(2 * end, n) while low <= n: temp = [True] * (high - low + 1) for each in in_prime: t = math.floor(low / each) * each if t < low: t += each for j in range(t, high + 1, each): temp[j - low] = False for j in range(len(temp)): if temp[j] is True: prime.append(j + low) low = high + 1 high = min(high + end, n) return prime if __name__ == "__main__": import doctest doctest.testmod() print(f"{sieve(10**6) = }")
Arithmetic mean Reference: https:en.wikipedia.orgwikiArithmeticmean Arithmetic series Reference: https:en.wikipedia.orgwikiArithmeticseries The URL above will redirect you to arithmetic progression checking whether the input series is arithmetic series or not isarithmeticseries2, 4, 6 True isarithmeticseries3, 6, 12, 24 False isarithmeticseries1, 2, 3 True isarithmeticseries4 Traceback most recent call last: ... ValueError: Input series is not valid, valid series 2, 4, 6 isarithmeticseries Traceback most recent call last: ... ValueError: Input list must be a non empty list return the arithmetic mean of series arithmeticmean2, 4, 6 4.0 arithmeticmean3, 6, 9, 12 7.5 arithmeticmean4 Traceback most recent call last: ... ValueError: Input series is not valid, valid series 2, 4, 6 arithmeticmean4, 8, 1 4.333333333333333 arithmeticmean1, 2, 3 2.0 arithmeticmean Traceback most recent call last: ... ValueError: Input list must be a non empty list
def is_arithmetic_series(series: list) -> bool: """ checking whether the input series is arithmetic series or not >>> is_arithmetic_series([2, 4, 6]) True >>> is_arithmetic_series([3, 6, 12, 24]) False >>> is_arithmetic_series([1, 2, 3]) True >>> is_arithmetic_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> is_arithmetic_series([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True common_diff = series[1] - series[0] for index in range(len(series) - 1): if series[index + 1] - series[index] != common_diff: return False return True def arithmetic_mean(series: list) -> float: """ return the arithmetic mean of series >>> arithmetic_mean([2, 4, 6]) 4.0 >>> arithmetic_mean([3, 6, 9, 12]) 7.5 >>> arithmetic_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> arithmetic_mean([4, 8, 1]) 4.333333333333333 >>> arithmetic_mean([1, 2, 3]) 2.0 >>> arithmetic_mean([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 0 for val in series: answer += val return answer / len(series) if __name__ == "__main__": import doctest doctest.testmod()
Geometric Mean Reference : https:en.wikipedia.orgwikiGeometricmean Geometric series Reference: https:en.wikipedia.orgwikiGeometricseries checking whether the input series is geometric series or not isgeometricseries2, 4, 8 True isgeometricseries3, 6, 12, 24 True isgeometricseries1, 2, 3 False isgeometricseries0, 0, 3 False isgeometricseries Traceback most recent call last: ... ValueError: Input list must be a non empty list isgeometricseries4 Traceback most recent call last: ... ValueError: Input series is not valid, valid series 2, 4, 8 return the geometric mean of series geometricmean2, 4, 8 3.9999999999999996 geometricmean3, 6, 12, 24 8.48528137423857 geometricmean4, 8, 16 7.999999999999999 geometricmean4 Traceback most recent call last: ... ValueError: Input series is not valid, valid series 2, 4, 8 geometricmean1, 2, 3 1.8171205928321397 geometricmean0, 2, 3 0.0 geometricmean Traceback most recent call last: ... ValueError: Input list must be a non empty list
def is_geometric_series(series: list) -> bool: """ checking whether the input series is geometric series or not >>> is_geometric_series([2, 4, 8]) True >>> is_geometric_series([3, 6, 12, 24]) True >>> is_geometric_series([1, 2, 3]) False >>> is_geometric_series([0, 0, 3]) False >>> is_geometric_series([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list >>> is_geometric_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 8] """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 8]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True try: common_ratio = series[1] / series[0] for index in range(len(series) - 1): if series[index + 1] / series[index] != common_ratio: return False except ZeroDivisionError: return False return True def geometric_mean(series: list) -> float: """ return the geometric mean of series >>> geometric_mean([2, 4, 8]) 3.9999999999999996 >>> geometric_mean([3, 6, 12, 24]) 8.48528137423857 >>> geometric_mean([4, 8, 16]) 7.999999999999999 >>> geometric_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 8] >>> geometric_mean([1, 2, 3]) 1.8171205928321397 >>> geometric_mean([0, 2, 3]) 0.0 >>> geometric_mean([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 8]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 1 for value in series: answer *= value return pow(answer, 1 / len(series)) if __name__ == "__main__": import doctest doctest.testmod()
This is a pure Python implementation of the Geometric Series algorithm https:en.wikipedia.orgwikiGeometricseries Run the doctests with the following command: python3 m doctest v geometricseries.py or python m doctest v geometricseries.py For manual testing run: python3 geometricseries.py Pure Python implementation of Geometric Series algorithm :param nthterm: The last term nth term of Geometric Series :param startterma : The first term of Geometric Series :param commonratior : The common ratio between all the terms :return: The Geometric Series starting from first term a and multiple of common ration with first term with increase in power till last term nth term Examples: geometricseries4, 2, 2 2, 4.0, 8.0, 16.0 geometricseries4.0, 2.0, 2.0 2.0, 4.0, 8.0, 16.0 geometricseries4.1, 2.1, 2.1 2.1, 4.41, 9.261000000000001, 19.448100000000004 geometricseries4, 2, 2 2, 4.0, 8.0, 16.0 geometricseries4, 2, 2 2, 4.0, 8.0, 16.0 geometricseries4, 2, 2 geometricseries0, 100, 500 geometricseries1, 1, 1 1 geometricseries0, 0, 0
from __future__ import annotations def geometric_series( nth_term: float, start_term_a: float, common_ratio_r: float, ) -> list[float]: """ Pure Python implementation of Geometric Series algorithm :param nth_term: The last term (nth term of Geometric Series) :param start_term_a : The first term of Geometric Series :param common_ratio_r : The common ratio between all the terms :return: The Geometric Series starting from first term a and multiple of common ration with first term with increase in power till last term (nth term) Examples: >>> geometric_series(4, 2, 2) [2, 4.0, 8.0, 16.0] >>> geometric_series(4.0, 2.0, 2.0) [2.0, 4.0, 8.0, 16.0] >>> geometric_series(4.1, 2.1, 2.1) [2.1, 4.41, 9.261000000000001, 19.448100000000004] >>> geometric_series(4, 2, -2) [2, -4.0, 8.0, -16.0] >>> geometric_series(4, -2, 2) [-2, -4.0, -8.0, -16.0] >>> geometric_series(-4, 2, 2) [] >>> geometric_series(0, 100, 500) [] >>> geometric_series(1, 1, 1) [1] >>> geometric_series(0, 0, 0) [] """ if not all((nth_term, start_term_a, common_ratio_r)): return [] series: list[float] = [] power = 1 multiple = common_ratio_r for _ in range(int(nth_term)): if not series: series.append(start_term_a) else: power += 1 series.append(float(start_term_a * multiple)) multiple = pow(float(common_ratio_r), power) return series if __name__ == "__main__": import doctest doctest.testmod() nth_term = float(input("Enter the last number (n term) of the Geometric Series")) start_term_a = float(input("Enter the starting term (a) of the Geometric Series")) common_ratio_r = float( input("Enter the common ratio between two terms (r) of the Geometric Series") ) print("Formula of Geometric Series => a + ar + ar^2 ... +ar^n") print(geometric_series(nth_term, start_term_a, common_ratio_r))
Harmonic mean Reference: https:en.wikipedia.orgwikiHarmonicmean Harmonic series Reference: https:en.wikipedia.orgwikiHarmonicseriesmathematics checking whether the input series is arithmetic series or not isharmonicseries 1, 23, 12, 25, 13 True isharmonicseries 1, 23, 25, 13 False isharmonicseries1, 2, 3 False isharmonicseries12, 13, 14 True isharmonicseries25, 210, 215, 220, 225 True isharmonicseries4 Traceback most recent call last: ... ValueError: Input series is not valid, valid series 1, 23, 2 isharmonicseries Traceback most recent call last: ... ValueError: Input list must be a non empty list isharmonicseries0 Traceback most recent call last: ... ValueError: Input series cannot have 0 as an element isharmonicseries1,2,0,6 Traceback most recent call last: ... ValueError: Input series cannot have 0 as an element return the harmonic mean of series harmonicmean1, 4, 4 2.0 harmonicmean3, 6, 9, 12 5.759999999999999 harmonicmean4 Traceback most recent call last: ... ValueError: Input series is not valid, valid series 2, 4, 6 harmonicmean1, 2, 3 1.6363636363636365 harmonicmean Traceback most recent call last: ... ValueError: Input list must be a non empty list
def is_harmonic_series(series: list) -> bool: """ checking whether the input series is arithmetic series or not >>> is_harmonic_series([ 1, 2/3, 1/2, 2/5, 1/3]) True >>> is_harmonic_series([ 1, 2/3, 2/5, 1/3]) False >>> is_harmonic_series([1, 2, 3]) False >>> is_harmonic_series([1/2, 1/3, 1/4]) True >>> is_harmonic_series([2/5, 2/10, 2/15, 2/20, 2/25]) True >>> is_harmonic_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [1, 2/3, 2] >>> is_harmonic_series([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list >>> is_harmonic_series([0]) Traceback (most recent call last): ... ValueError: Input series cannot have 0 as an element >>> is_harmonic_series([1,2,0,6]) Traceback (most recent call last): ... ValueError: Input series cannot have 0 as an element """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [1, 2/3, 2]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1 and series[0] != 0: return True rec_series = [] series_len = len(series) for i in range(series_len): if series[i] == 0: raise ValueError("Input series cannot have 0 as an element") rec_series.append(1 / series[i]) common_diff = rec_series[1] - rec_series[0] for index in range(2, series_len): if rec_series[index] - rec_series[index - 1] != common_diff: return False return True def harmonic_mean(series: list) -> float: """ return the harmonic mean of series >>> harmonic_mean([1, 4, 4]) 2.0 >>> harmonic_mean([3, 6, 9, 12]) 5.759999999999999 >>> harmonic_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> harmonic_mean([1, 2, 3]) 1.6363636363636365 >>> harmonic_mean([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ if not isinstance(series, list): raise ValueError("Input series is not valid, valid series - [2, 4, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 0 for val in series: answer += 1 / val return len(series) / answer if __name__ == "__main__": import doctest doctest.testmod()
This is a pure Python implementation of the Harmonic Series algorithm https:en.wikipedia.orgwikiHarmonicseriesmathematics For doctests run following command: python m doctest v harmonicseries.py or python3 m doctest v harmonicseries.py For manual testing run: python3 harmonicseries.py Pure Python implementation of Harmonic Series algorithm :param nterm: The last nth term of Harmonic Series :return: The Harmonic Series starting from 1 to last nth term Examples: harmonicseries5 '1', '12', '13', '14', '15' harmonicseries5.0 '1', '12', '13', '14', '15' harmonicseries5.1 '1', '12', '13', '14', '15' harmonicseries5 harmonicseries0 harmonicseries1 '1'
def harmonic_series(n_term: str) -> list: """Pure Python implementation of Harmonic Series algorithm :param n_term: The last (nth) term of Harmonic Series :return: The Harmonic Series starting from 1 to last (nth) term Examples: >>> harmonic_series(5) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(5.0) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(5.1) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(-5) [] >>> harmonic_series(0) [] >>> harmonic_series(1) ['1'] """ if n_term == "": return [] series: list = [] for temp in range(int(n_term)): series.append(f"1/{temp + 1}" if series else "1") return series if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
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 n2n1 where: h is nth element of the sequence n is the number of element in the sequence referenceHexagonal number Wikipedia https:en.wikipedia.orgwikiHexagonalnumber :param len: max number of elements :type len: int :return: Hexagonal numbers as a list Tests: hexagonalnumbers10 0, 1, 6, 15, 28, 45, 66, 91, 120, 153 hexagonalnumbers5 0, 1, 6, 15, 28 hexagonalnumbers0 Traceback most recent call last: ... ValueError: Length must be a positive integer.
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))
This is a pure Python implementation of the PSeries algorithm https:en.wikipedia.orgwikiHarmonicseriesmathematicsPseries For doctests run following command: python m doctest v pseries.py or python3 m doctest v pseries.py For manual testing run: python3 pseries.py Pure Python implementation of PSeries algorithm :return: The PSeries starting from 1 to last nth term Examples: pseries5, 2 '1', '1 4', '1 9', '1 16', '1 25' pseries5, 2 pseries5, 2 '1', '1 0.25', '1 0.1111111111111111', '1 0.0625', '1 0.04' pseries, 1000 '' pseries0, 0 pseries1, 1 '1'
from __future__ import annotations def p_series(nth_term: float | str, power: float | str) -> list[str]: """ Pure Python implementation of P-Series algorithm :return: The P-Series starting from 1 to last (nth) term Examples: >>> p_series(5, 2) ['1', '1 / 4', '1 / 9', '1 / 16', '1 / 25'] >>> p_series(-5, 2) [] >>> p_series(5, -2) ['1', '1 / 0.25', '1 / 0.1111111111111111', '1 / 0.0625', '1 / 0.04'] >>> p_series("", 1000) [''] >>> p_series(0, 0) [] >>> p_series(1, 1) ['1'] """ if nth_term == "": return [""] nth_term = int(nth_term) power = int(power) series: list[str] = [] for temp in range(int(nth_term)): series.append(f"1 / {pow(temp + 1, int(power))}" if series else "1") return series if __name__ == "__main__": import doctest doctest.testmod() nth_term = int(input("Enter the last number (nth term) of the P-Series")) power = int(input("Enter the power for P-Series")) print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p") print(p_series(nth_term, power))
Sieve of Eratosthones The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or equal to a given value. Illustration: https:upload.wikimedia.orgwikipediacommonsbb9SieveofEratosthenesanimation.gif Reference: https:en.wikipedia.orgwikiSieveofEratosthenes doctest provider: Bruno Simas Hadlich https:github.combrunohadlich Also thanks to Dmitry https:github.comLizardWizzard for finding the problem Returns a list with all prime numbers up to n. primesieve50 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 primesieve25 2, 3, 5, 7, 11, 13, 17, 19, 23 primesieve10 2, 3, 5, 7 primesieve9 2, 3, 5, 7 primesieve2 2 primesieve1 If start is a prime Set multiples of start be False
from __future__ import annotations import math def prime_sieve(num: int) -> list[int]: """ Returns a list with all prime numbers up to n. >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] >>> prime_sieve(25) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> prime_sieve(10) [2, 3, 5, 7] >>> prime_sieve(9) [2, 3, 5, 7] >>> prime_sieve(2) [2] >>> prime_sieve(1) [] """ if num <= 0: msg = f"{num}: Invalid input, please enter a positive integer." raise ValueError(msg) sieve = [True] * (num + 1) prime = [] start = 2 end = int(math.sqrt(num)) while start <= end: # If start is a prime if sieve[start] is True: prime.append(start) # Set multiples of start be False for i in range(start * start, num + 1, start): if sieve[i] is True: sieve[i] = False start += 1 for j in range(end + 1, num + 1): if sieve[j] is True: prime.append(j) return prime if __name__ == "__main__": print(prime_sieve(int(input("Enter a positive integer: ").strip())))
This script demonstrates the implementation of the Sigmoid function. The function takes a vector of K real numbers as input and then 1 1 expx. After through Sigmoid, the element of the vector mostly 0 between 1. or 1 between 1. Script inspired from its corresponding Wikipedia article https:en.wikipedia.orgwikiSigmoidfunction Implements the sigmoid function Parameters: vector np.array: A numpy array of shape 1,n consisting of real values Returns: sigmoidvec np.array: The input numpy array, after applying sigmoid. Examples: sigmoidnp.array1.0, 1.0, 2.0 array0.26894142, 0.73105858, 0.88079708 sigmoidnp.array0.0 array0.5
import numpy as np def sigmoid(vector: np.ndarray) -> np.ndarray: """ Implements the sigmoid function Parameters: vector (np.array): A numpy array of shape (1,n) consisting of real values Returns: sigmoid_vec (np.array): The input numpy array, after applying sigmoid. Examples: >>> sigmoid(np.array([-1.0, 1.0, 2.0])) array([0.26894142, 0.73105858, 0.88079708]) >>> sigmoid(np.array([0.0])) array([0.5]) """ return 1 / (1 + np.exp(-vector)) if __name__ == "__main__": import doctest doctest.testmod()
Signum function https:en.wikipedia.orgwikiSignfunction Applies signum function on the number Custom test cases: signum10 1 signum10 1 signum0 0 signum20.5 1 signum20.5 1 signum1e6 1 signum1e6 1 signumHello Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int' signum Traceback most recent call last: ... TypeError: '' not supported between instances of 'list' and 'int' Tests the signum function testsignum
def signum(num: float) -> int: """ Applies signum function on the number Custom test cases: >>> signum(-10) -1 >>> signum(10) 1 >>> signum(0) 0 >>> signum(-20.5) -1 >>> signum(20.5) 1 >>> signum(-1e-6) -1 >>> signum(1e-6) 1 >>> signum("Hello") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' >>> signum([]) Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'list' and 'int' """ if num < 0: return -1 return 1 if num else 0 def test_signum() -> None: """ Tests the signum function >>> test_signum() """ assert signum(5) == 1 assert signum(-5) == -1 assert signum(0) == 0 assert signum(10.5) == 1 assert signum(-10.5) == -1 assert signum(1e-6) == 1 assert signum(-1e-6) == -1 assert signum(123456789) == 1 assert signum(-123456789) == -1 if __name__ == "__main__": print(signum(12)) print(signum(-12)) print(signum(0))
https:en.wikipedia.orgwikiAugmentedmatrix This algorithm solves simultaneous linear equations of the form a b c d ... as , , , , ..., Where are individual coefficients, the no. of equations no. of coefficients 1 Note in order to work there must exist 1 equation where all instances of and ! 0 simplify1, 2, 3, 4, 5, 6 1.0, 2.0, 3.0, 0.0, 0.75, 1.5 simplify5, 2, 5, 5, 1, 10 1.0, 0.4, 1.0, 0.0, 0.2, 1.0 Divide each row by magnitude of first term creates 'unit' matrix Subtract to cancel term If first term is 0, it is already in form we want, so we preserve it Create next recursion iteration set solvesimultaneous1, 2, 3,4, 5, 6 1.0, 2.0 solvesimultaneous0, 3, 1, 7,3, 2, 1, 11,5, 1, 2, 12 6.4, 1.2, 10.6 solvesimultaneous Traceback most recent call last: ... IndexError: solvesimultaneous requires n lists of length n1 solvesimultaneous1, 2, 3,1, 2 Traceback most recent call last: ... IndexError: solvesimultaneous requires n lists of length n1 solvesimultaneous1, 2, 3,a, 7, 8 Traceback most recent call last: ... ValueError: solvesimultaneous requires lists of integers solvesimultaneous0, 2, 3,4, 0, 6 Traceback most recent call last: ... ValueError: solvesimultaneous requires at least 1 full equation
def simplify(current_set: list[list]) -> list[list]: """ >>> simplify([[1, 2, 3], [4, 5, 6]]) [[1.0, 2.0, 3.0], [0.0, 0.75, 1.5]] >>> simplify([[5, 2, 5], [5, 1, 10]]) [[1.0, 0.4, 1.0], [0.0, 0.2, -1.0]] """ # Divide each row by magnitude of first term --> creates 'unit' matrix duplicate_set = current_set.copy() for row_index, row in enumerate(duplicate_set): magnitude = row[0] for column_index, column in enumerate(row): if magnitude == 0: current_set[row_index][column_index] = column continue current_set[row_index][column_index] = column / magnitude # Subtract to cancel term first_row = current_set[0] final_set = [first_row] current_set = current_set[1::] for row in current_set: temp_row = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(row) continue for column_index in range(len(row)): temp_row.append(first_row[column_index] - row[column_index]) final_set.append(temp_row) # Create next recursion iteration set if len(final_set[0]) != 3: current_first_row = final_set[0] current_first_column = [] next_iteration = [] for row in final_set[1::]: current_first_column.append(row[0]) next_iteration.append(row[1::]) resultant = simplify(next_iteration) for i in range(len(resultant)): resultant[i].insert(0, current_first_column[i]) resultant.insert(0, current_first_row) final_set = resultant return final_set def solve_simultaneous(equations: list[list]) -> list: """ >>> solve_simultaneous([[1, 2, 3],[4, 5, 6]]) [-1.0, 2.0] >>> solve_simultaneous([[0, -3, 1, 7],[3, 2, -1, 11],[5, 1, -2, 12]]) [6.4, 1.2, 10.6] >>> solve_simultaneous([]) Traceback (most recent call last): ... IndexError: solve_simultaneous() requires n lists of length n+1 >>> solve_simultaneous([[1, 2, 3],[1, 2]]) Traceback (most recent call last): ... IndexError: solve_simultaneous() requires n lists of length n+1 >>> solve_simultaneous([[1, 2, 3],["a", 7, 8]]) Traceback (most recent call last): ... ValueError: solve_simultaneous() requires lists of integers >>> solve_simultaneous([[0, 2, 3],[4, 0, 6]]) Traceback (most recent call last): ... ValueError: solve_simultaneous() requires at least 1 full equation """ if len(equations) == 0: raise IndexError("solve_simultaneous() requires n lists of length n+1") _length = len(equations) + 1 if any(len(item) != _length for item in equations): raise IndexError("solve_simultaneous() requires n lists of length n+1") for row in equations: if any(not isinstance(column, (int, float)) for column in row): raise ValueError("solve_simultaneous() requires lists of integers") if len(equations) == 1: return [equations[0][-1] / equations[0][0]] data_set = equations.copy() if any(0 in row for row in data_set): temp_data = data_set.copy() full_row = [] for row_index, row in enumerate(temp_data): if 0 not in row: full_row = data_set.pop(row_index) break if not full_row: raise ValueError("solve_simultaneous() requires at least 1 full equation") data_set.insert(0, full_row) useable_form = data_set.copy() simplified = simplify(useable_form) simplified = simplified[::-1] solutions: list = [] for row in simplified: current_solution = row[-1] if not solutions: if row[-2] == 0: solutions.append(0) continue solutions.append(current_solution / row[-2]) continue temp_row = row.copy()[: len(row) - 1 :] while temp_row[0] == 0: temp_row.pop(0) if len(temp_row) == 0: solutions.append(0) continue temp_row = temp_row[1::] temp_row = temp_row[::-1] for column_index, column in enumerate(temp_row): current_solution -= column * solutions[column_index] solutions.append(current_solution) final = [] for item in solutions: final.append(float(round(item, 5))) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() eq = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
Calculate sin function. It's not a perfect function so I am rounding the result to 10 decimal places by default. Formula: sinx x x33! x55! x77! ... Where: x angle in randians. Source: https:www.homeschoolmath.netteachingsinecalculator.php Implement sin function. sin0.0 0.0 sin90.0 1.0 sin180.0 0.0 sin270.0 1.0 sin0.68 0.0118679603 sin1.97 0.0343762121 sin64.0 0.8987940463 sin9999.0 0.9876883406 sin689.0 0.5150380749 sin89.7 0.9999862922 Simplify the angle to be between 360 and 360 degrees. Converting from degrees to radians
from math import factorial, radians def sin( angle_in_degrees: float, accuracy: int = 18, rounded_values_count: int = 10 ) -> float: """ Implement sin function. >>> sin(0.0) 0.0 >>> sin(90.0) 1.0 >>> sin(180.0) 0.0 >>> sin(270.0) -1.0 >>> sin(0.68) 0.0118679603 >>> sin(1.97) 0.0343762121 >>> sin(64.0) 0.8987940463 >>> sin(9999.0) -0.9876883406 >>> sin(-689.0) 0.5150380749 >>> sin(89.7) 0.9999862922 """ # Simplify the angle to be between 360 and -360 degrees. angle_in_degrees = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians angle_in_radians = radians(angle_in_degrees) result = angle_in_radians a = 3 b = -1 for _ in range(accuracy): result += (b * (angle_in_radians**a)) / factorial(a) b = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(result, rounded_values_count) if __name__ == "__main__": __import__("doctest").testmod()
sockmerchant10, 20, 20, 10, 10, 30, 50, 10, 20 3 sockmerchant1, 1, 3, 3 2
from collections import Counter def sock_merchant(colors: list[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([1, 1, 3, 3]) 2 """ return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values()) if __name__ == "__main__": import doctest doctest.testmod() colors = [int(x) for x in input("Enter socks by color :").rstrip().split()] print(f"sock_merchant({colors}) = {sock_merchant(colors)}")
This script demonstrates the implementation of the Softmax function. Its a function that takes as input a vector of K real numbers, and normalizes it into a probability distribution consisting of K probabilities proportional to the exponentials of the input numbers. After softmax, the elements of the vector always sum up to 1. Script inspired from its corresponding Wikipedia article https:en.wikipedia.orgwikiSoftmaxfunction Implements the softmax function Parameters: vector np.array,list,tuple: A numpy array of shape 1,n consisting of real values or a similar list,tuple Returns: softmaxvec np.array: The input numpy array after applying softmax. The softmax vector adds up to one. We need to ceil to mitigate for precision np.ceilnp.sumsoftmax1,2,3,4 1.0 vec np.array5,5 softmaxvec array0.5, 0.5 softmax0 array1. Calculate ex for each x in your vector where e is Euler's number approximately 2.718 Add up the all the exponentials Divide every exponent by the sum of all exponents
import numpy as np def softmax(vector): """ Implements the softmax function Parameters: vector (np.array,list,tuple): A numpy array of shape (1,n) consisting of real values or a similar list,tuple Returns: softmax_vec (np.array): The input numpy array after applying softmax. The softmax vector adds up to one. We need to ceil to mitigate for precision >>> np.ceil(np.sum(softmax([1,2,3,4]))) 1.0 >>> vec = np.array([5,5]) >>> softmax(vec) array([0.5, 0.5]) >>> softmax([0]) array([1.]) """ # Calculate e^x for each x in your vector where e is Euler's # number (approximately 2.718) exponent_vector = np.exp(vector) # Add up the all the exponentials sum_of_exponents = np.sum(exponent_vector) # Divide every exponent by the sum of all exponents softmax_vector = exponent_vector / sum_of_exponents return softmax_vector if __name__ == "__main__": print(softmax((0,)))
This script implements the SolovayStrassen Primality test. This probabilistic primality test is based on Euler's criterion. It is similar to the Fermat test but uses quadratic residues. It can quickly identify composite numbers but may occasionally classify composite numbers as prime. More details and concepts about this can be found on: https:en.wikipedia.orgwikiSolovayE28093Strassenprimalitytest Calculate the Jacobi symbol. The Jacobi symbol is a generalization of the Legendre symbol, which can be used to simplify computations involving quadratic residues. The Jacobi symbol is used in primality tests, like the SolovayStrassen test, because it helps determine if an integer is a quadratic residue modulo a given modulus, providing valuable information about the number's potential primality or compositeness. Parameters: randoma: A randomly chosen integer from 2 to n2 inclusive number: The number that is tested for primality Returns: jacobisymbol: The Jacobi symbol is a mathematical function used to determine whether an integer is a quadratic residue modulo another integer usually prime or not. jacobisymbol2, 13 1 jacobisymbol5, 19 1 jacobisymbol7, 14 0 Check whether the input number is prime or not using the SolovayStrassen Primality test Parameters: number: The number that is tested for primality iterations: The number of times that the test is run which effects the accuracy Returns: result: True if number is probably prime and false if not random.seed10 solovaystrassen13, 5 True solovaystrassen9, 10 False solovaystrassen17, 15 True
import random def jacobi_symbol(random_a: int, number: int) -> int: """ Calculate the Jacobi symbol. The Jacobi symbol is a generalization of the Legendre symbol, which can be used to simplify computations involving quadratic residues. The Jacobi symbol is used in primality tests, like the Solovay-Strassen test, because it helps determine if an integer is a quadratic residue modulo a given modulus, providing valuable information about the number's potential primality or compositeness. Parameters: random_a: A randomly chosen integer from 2 to n-2 (inclusive) number: The number that is tested for primality Returns: jacobi_symbol: The Jacobi symbol is a mathematical function used to determine whether an integer is a quadratic residue modulo another integer (usually prime) or not. >>> jacobi_symbol(2, 13) -1 >>> jacobi_symbol(5, 19) 1 >>> jacobi_symbol(7, 14) 0 """ if random_a in (0, 1): return random_a random_a %= number t = 1 while random_a != 0: while random_a % 2 == 0: random_a //= 2 r = number % 8 if r in (3, 5): t = -t random_a, number = number, random_a if random_a % 4 == number % 4 == 3: t = -t random_a %= number return t if number == 1 else 0 def solovay_strassen(number: int, iterations: int) -> bool: """ Check whether the input number is prime or not using the Solovay-Strassen Primality test Parameters: number: The number that is tested for primality iterations: The number of times that the test is run which effects the accuracy Returns: result: True if number is probably prime and false if not >>> random.seed(10) >>> solovay_strassen(13, 5) True >>> solovay_strassen(9, 10) False >>> solovay_strassen(17, 15) True """ if number <= 1: return False if number <= 3: return True for _ in range(iterations): a = random.randint(2, number - 2) x = jacobi_symbol(a, number) y = pow(a, (number - 1) // 2, number) if x == 0 or y != x % number: return False return True if __name__ == "__main__": import doctest doctest.testmod()
Assigns ranks to elements in the array. :param data: List of floats. :return: List of ints representing the ranks. Example: assignranks3.2, 1.5, 4.0, 2.7, 5.1 3, 1, 4, 2, 5 assignranks10.5, 8.1, 12.4, 9.3, 11.0 3, 1, 5, 2, 4 Calculates Spearman's rank correlation coefficient. :param variable1: List of floats representing the first variable. :param variable2: List of floats representing the second variable. :return: Spearman's rank correlation coefficient. Example Usage: x 1, 2, 3, 4, 5 y 5, 4, 3, 2, 1 calculatespearmanrankcorrelationx, y 1.0 x 1, 2, 3, 4, 5 y 2, 4, 6, 8, 10 calculatespearmanrankcorrelationx, y 1.0 x 1, 2, 3, 4, 5 y 5, 1, 2, 9, 5 calculatespearmanrankcorrelationx, y 0.6 Calculate differences of ranks Calculate the sum of squared differences Calculate the Spearman's rank correlation coefficient Example usage:
from collections.abc import Sequence def assign_ranks(data: Sequence[float]) -> list[int]: """ Assigns ranks to elements in the array. :param data: List of floats. :return: List of ints representing the ranks. Example: >>> assign_ranks([3.2, 1.5, 4.0, 2.7, 5.1]) [3, 1, 4, 2, 5] >>> assign_ranks([10.5, 8.1, 12.4, 9.3, 11.0]) [3, 1, 5, 2, 4] """ ranked_data = sorted((value, index) for index, value in enumerate(data)) ranks = [0] * len(data) for position, (_, index) in enumerate(ranked_data): ranks[index] = position + 1 return ranks def calculate_spearman_rank_correlation( variable_1: Sequence[float], variable_2: Sequence[float] ) -> float: """ Calculates Spearman's rank correlation coefficient. :param variable_1: List of floats representing the first variable. :param variable_2: List of floats representing the second variable. :return: Spearman's rank correlation coefficient. Example Usage: >>> x = [1, 2, 3, 4, 5] >>> y = [5, 4, 3, 2, 1] >>> calculate_spearman_rank_correlation(x, y) -1.0 >>> x = [1, 2, 3, 4, 5] >>> y = [2, 4, 6, 8, 10] >>> calculate_spearman_rank_correlation(x, y) 1.0 >>> x = [1, 2, 3, 4, 5] >>> y = [5, 1, 2, 9, 5] >>> calculate_spearman_rank_correlation(x, y) 0.6 """ n = len(variable_1) rank_var1 = assign_ranks(variable_1) rank_var2 = assign_ranks(variable_2) # Calculate differences of ranks d = [rx - ry for rx, ry in zip(rank_var1, rank_var2)] # Calculate the sum of squared differences d_squared = sum(di**2 for di in d) # Calculate the Spearman's rank correlation coefficient rho = 1 - (6 * d_squared) / (n * (n**2 - 1)) return rho if __name__ == "__main__": import doctest doctest.testmod() # Example usage: print( f"{calculate_spearman_rank_correlation([1, 2, 3, 4, 5], [2, 4, 6, 8, 10]) = }" ) print(f"{calculate_spearman_rank_correlation([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]) = }") print(f"{calculate_spearman_rank_correlation([1, 2, 3, 4, 5], [5, 1, 2, 9, 5]) = }")
An Armstrong number is equal to the sum of its own digits each raised to the power of the number of digits. For example, 370 is an Armstrong number because 333 777 000 370. Armstrong numbers are also called Narcissistic numbers and Pluperfect numbers. OnLine Encyclopedia of Integer Sequences entry: https:oeis.orgA005188 Return True if n is an Armstrong number or False if it is not. allarmstrongnumbern for n in PASSING True anyarmstrongnumbern for n in FAILING False Initialization of sum and number of digits. Calculation of digits of the number Dividing number into separate digits and find Armstrong number Return True if n is a pluperfect number or False if it is not allarmstrongnumbern for n in PASSING True anyarmstrongnumbern for n in FAILING False Init a histogram of the digits Return True if n is a narcissistic number or False if it is not. allarmstrongnumbern for n in PASSING True anyarmstrongnumbern for n in FAILING False check if sum of each digit multiplied expo times is equal to number Request that user input an integer and tell them if it is Armstrong number.
PASSING = (1, 153, 370, 371, 1634, 24678051, 115132219018763992565095597973971522401) FAILING: tuple = (-153, -1, 0, 1.2, 200, "A", [], {}, None) def armstrong_number(n: int) -> bool: """ Return True if n is an Armstrong number or False if it is not. >>> all(armstrong_number(n) for n in PASSING) True >>> any(armstrong_number(n) for n in FAILING) False """ if not isinstance(n, int) or n < 1: return False # Initialization of sum and number of digits. total = 0 number_of_digits = 0 temp = n # Calculation of digits of the number number_of_digits = len(str(n)) # Dividing number into separate digits and find Armstrong number temp = n while temp > 0: rem = temp % 10 total += rem**number_of_digits temp //= 10 return n == total def pluperfect_number(n: int) -> bool: """Return True if n is a pluperfect number or False if it is not >>> all(armstrong_number(n) for n in PASSING) True >>> any(armstrong_number(n) for n in FAILING) False """ if not isinstance(n, int) or n < 1: return False # Init a "histogram" of the digits digit_histogram = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] digit_total = 0 total = 0 temp = n while temp > 0: temp, rem = divmod(temp, 10) digit_histogram[rem] += 1 digit_total += 1 for cnt, i in zip(digit_histogram, range(len(digit_histogram))): total += cnt * i**digit_total return n == total def narcissistic_number(n: int) -> bool: """Return True if n is a narcissistic number or False if it is not. >>> all(armstrong_number(n) for n in PASSING) True >>> any(armstrong_number(n) for n in FAILING) False """ if not isinstance(n, int) or n < 1: return False expo = len(str(n)) # the power that all digits will be raised to # check if sum of each digit multiplied expo times is equal to number return n == sum(int(i) ** expo for i in str(n)) def main(): """ Request that user input an integer and tell them if it is Armstrong number. """ num = int(input("Enter an integer to see if it is an Armstrong number: ").strip()) print(f"{num} is {'' if armstrong_number(num) else 'not '}an Armstrong number.") print(f"{num} is {'' if narcissistic_number(num) else 'not '}an Armstrong number.") print(f"{num} is {'' if pluperfect_number(num) else 'not '}an Armstrong number.") if __name__ == "__main__": import doctest doctest.testmod() main()
Automorphic Numbers A number n is said to be a Automorphic number if the square of n ends in the same digits as n itself. Examples of Automorphic Numbers: 0, 1, 5, 6, 25, 76, 376, 625, 9376, 90625, ... https:en.wikipedia.orgwikiAutomorphicnumber Author : Akshay Dubey https:github.comitsAkshayDubey Time Complexity : Olog10n doctest: NORMALIZEWHITESPACE This functions takes an integer number as input. returns True if the number is automorphic. isautomorphicnumber1 False isautomorphicnumber0 True isautomorphicnumber5 True isautomorphicnumber6 True isautomorphicnumber7 False isautomorphicnumber25 True isautomorphicnumber259918212890625 True isautomorphicnumber259918212890636 False isautomorphicnumber740081787109376 True isautomorphicnumber5.0 Traceback most recent call last: ... TypeError: Input value of number5.0 must be an integer
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) # Time Complexity : O(log10n) def is_automorphic_number(number: int) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes an integer number as input. returns True if the number is automorphic. >>> is_automorphic_number(-1) False >>> is_automorphic_number(0) True >>> is_automorphic_number(5) True >>> is_automorphic_number(6) True >>> is_automorphic_number(7) False >>> is_automorphic_number(25) True >>> is_automorphic_number(259918212890625) True >>> is_automorphic_number(259918212890636) False >>> is_automorphic_number(740081787109376) True >>> is_automorphic_number(5.0) Traceback (most recent call last): ... TypeError: Input value of [number=5.0] must be an integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 0: return False number_square = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
Bell numbers represent the number of ways to partition a set into nonempty subsets. This module provides functions to calculate Bell numbers for sets of integers. In other words, the first n 1 Bell numbers. For more information about Bell numbers, refer to: https:en.wikipedia.orgwikiBellnumber Calculate Bell numbers for the sets of lengths from 0 to maxsetlength. In other words, calculate first maxsetlength 1 Bell numbers. Args: maxsetlength int: The maximum length of the sets for which Bell numbers are calculated. Returns: list: A list of Bell numbers for sets of lengths from 0 to maxsetlength. Examples: bellnumbers0 1 bellnumbers1 1, 1 bellnumbers5 1, 1, 2, 5, 15, 52 Calculate the binomial coefficient Ctotalelements, elementstochoose Args: totalelements int: The total number of elements. elementstochoose int: The number of elements to choose. Returns: int: The binomial coefficient Ctotalelements, elementstochoose. Examples: binomialcoefficient5, 2 10 binomialcoefficient6, 3 20
def bell_numbers(max_set_length: int) -> list[int]: """ Calculate Bell numbers for the sets of lengths from 0 to max_set_length. In other words, calculate first (max_set_length + 1) Bell numbers. Args: max_set_length (int): The maximum length of the sets for which Bell numbers are calculated. Returns: list: A list of Bell numbers for sets of lengths from 0 to max_set_length. Examples: >>> bell_numbers(0) [1] >>> bell_numbers(1) [1, 1] >>> bell_numbers(5) [1, 1, 2, 5, 15, 52] """ if max_set_length < 0: raise ValueError("max_set_length must be non-negative") bell = [0] * (max_set_length + 1) bell[0] = 1 for i in range(1, max_set_length + 1): for j in range(i): bell[i] += _binomial_coefficient(i - 1, j) * bell[j] return bell def _binomial_coefficient(total_elements: int, elements_to_choose: int) -> int: """ Calculate the binomial coefficient C(total_elements, elements_to_choose) Args: total_elements (int): The total number of elements. elements_to_choose (int): The number of elements to choose. Returns: int: The binomial coefficient C(total_elements, elements_to_choose). Examples: >>> _binomial_coefficient(5, 2) 10 >>> _binomial_coefficient(6, 3) 20 """ if elements_to_choose in {0, total_elements}: return 1 if elements_to_choose > total_elements - elements_to_choose: elements_to_choose = total_elements - elements_to_choose coefficient = 1 for i in range(elements_to_choose): coefficient *= total_elements - i coefficient //= i + 1 return coefficient if __name__ == "__main__": import doctest doctest.testmod()
Carmichael Numbers A number n is said to be a Carmichael number if it satisfies the following modular arithmetic condition: powerb, n1 MOD n 1, for all b ranging from 1 to n such that b and n are relatively prime, i.e, gcdb, n 1 Examples of Carmichael Numbers: 561, 1105, ... https:en.wikipedia.orgwikiCarmichaelnumber Examples: power2, 15, 3 2 power5, 1, 30 5 Examples: iscarmichaelnumber4 False iscarmichaelnumber561 True iscarmichaelnumber562 False iscarmichaelnumber900 False iscarmichaelnumber1105 True iscarmichaelnumber8911 True iscarmichaelnumber5.1 Traceback most recent call last: ... ValueError: Number 5.1 must instead be a positive integer iscarmichaelnumber7 Traceback most recent call last: ... ValueError: Number 7 must instead be a positive integer iscarmichaelnumber0 Traceback most recent call last: ... ValueError: Number 0 must instead be a positive integer
from maths.greatest_common_divisor import greatest_common_divisor def power(x: int, y: int, mod: int) -> int: """ Examples: >>> power(2, 15, 3) 2 >>> power(5, 1, 30) 5 """ if y == 0: return 1 temp = power(x, y // 2, mod) % mod temp = (temp * temp) % mod if y % 2 == 1: temp = (temp * x) % mod return temp def is_carmichael_number(n: int) -> bool: """ Examples: >>> is_carmichael_number(4) False >>> is_carmichael_number(561) True >>> is_carmichael_number(562) False >>> is_carmichael_number(900) False >>> is_carmichael_number(1105) True >>> is_carmichael_number(8911) True >>> is_carmichael_number(5.1) Traceback (most recent call last): ... ValueError: Number 5.1 must instead be a positive integer >>> is_carmichael_number(-7) Traceback (most recent call last): ... ValueError: Number -7 must instead be a positive integer >>> is_carmichael_number(0) Traceback (most recent call last): ... ValueError: Number 0 must instead be a positive integer """ if n <= 0 or not isinstance(n, int): msg = f"Number {n} must instead be a positive integer" raise ValueError(msg) return all( power(b, n - 1, n) == 1 for b in range(2, n) if greatest_common_divisor(b, n) == 1 ) if __name__ == "__main__": import doctest doctest.testmod() number = int(input("Enter number: ").strip()) if is_carmichael_number(number): print(f"{number} is a Carmichael Number.") else: print(f"{number} is not a Carmichael Number.")
Calculate the nth Catalan number Source: https:en.wikipedia.orgwikiCatalannumber :param number: nth catalan number to calculate :return: the nth catalan number Note: A catalan number is only defined for positive integers catalan5 14 catalan0 Traceback most recent call last: ... ValueError: Input value of number0 must be 0 catalan1 Traceback most recent call last: ... ValueError: Input value of number1 must be 0 catalan5.0 Traceback most recent call last: ... TypeError: Input value of number5.0 must be an integer
def catalan(number: int) -> int: """ :param number: nth catalan number to calculate :return: the nth catalan number Note: A catalan number is only defined for positive integers >>> catalan(5) 14 >>> catalan(0) Traceback (most recent call last): ... ValueError: Input value of [number=0] must be > 0 >>> catalan(-1) Traceback (most recent call last): ... ValueError: Input value of [number=-1] must be > 0 >>> catalan(5.0) Traceback (most recent call last): ... TypeError: Input value of [number=5.0] must be an integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be > 0" raise ValueError(msg) current_number = 1 for i in range(1, number): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
A Hamming number is a positive integer of the form 2i3j5k, for some nonnegative integers i, j, and k. They are often referred to as regular numbers. More info at: https:en.wikipedia.orgwikiRegularnumber. 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 nelement: The number of elements on the list :return: The nth element of the list hamming5 1, 2, 3, 4, 5 hamming10 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 hamming15 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24
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 happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. :param number: The number to check for happiness. :return: True if the number is a happy number, False otherwise. ishappynumber19 True ishappynumber2 False ishappynumber23 True ishappynumber1 True ishappynumber0 Traceback most recent call last: ... ValueError: number0 must be a positive integer ishappynumber19 Traceback most recent call last: ... ValueError: number19 must be a positive integer ishappynumber19.1 Traceback most recent call last: ... ValueError: number19.1 must be a positive integer ishappynumberhappy Traceback most recent call last: ... ValueError: number'happy' must be a positive integer
def is_happy_number(number: int) -> bool: """ A happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. :param number: The number to check for happiness. :return: True if the number is a happy number, False otherwise. >>> is_happy_number(19) True >>> is_happy_number(2) False >>> is_happy_number(23) True >>> is_happy_number(1) True >>> is_happy_number(0) Traceback (most recent call last): ... ValueError: number=0 must be a positive integer >>> is_happy_number(-19) Traceback (most recent call last): ... ValueError: number=-19 must be a positive integer >>> is_happy_number(19.1) Traceback (most recent call last): ... ValueError: number=19.1 must be a positive integer >>> is_happy_number("happy") Traceback (most recent call last): ... ValueError: number='happy' must be a positive integer """ if not isinstance(number, int) or number <= 0: msg = f"{number=} must be a positive integer" raise ValueError(msg) seen = set() while number != 1 and number not in seen: seen.add(number) number = sum(int(digit) ** 2 for digit in str(number)) return number == 1 if __name__ == "__main__": import doctest doctest.testmod()
A harshad number or more specifically an nharshad number is a number that's divisible by the sum of its digits in some given base n. Reference: https:en.wikipedia.orgwikiHarshadnumber Convert a given positive decimal integer to base 'base'. Where 'base' ranges from 2 to 36. Examples: inttobase23, 2 '10111' inttobase58, 5 '213' inttobase167, 16 'A7' bases below 2 and beyond 36 will error inttobase98, 1 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive inttobase98, 37 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive Calculate the sum of digit values in a positive integer converted to the given 'base'. Where 'base' ranges from 2 to 36. Examples: sumofdigits103, 12 '13' sumofdigits1275, 4 '30' sumofdigits6645, 2 '1001' bases below 2 and beyond 36 will error sumofdigits543, 1 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive sumofdigits543, 37 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive Finds all Harshad numbers smaller than num in base 'base'. Where 'base' ranges from 2 to 36. Examples: harshadnumbersinbase15, 2 '1', '10', '100', '110', '1000', '1010', '1100' harshadnumbersinbase12, 34 '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B' harshadnumbersinbase12, 4 '1', '2', '3', '10', '12', '20', '21' bases below 2 and beyond 36 will error harshadnumbersinbase234, 37 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive harshadnumbersinbase234, 1 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive Determines whether n in base 'base' is a harshad number. Where 'base' ranges from 2 to 36. Examples: isharshadnumberinbase18, 10 True isharshadnumberinbase21, 10 True isharshadnumberinbase21, 5 False bases below 2 and beyond 36 will error isharshadnumberinbase45, 37 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive isharshadnumberinbase45, 1 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive
def int_to_base(number: int, base: int) -> str: """ Convert a given positive decimal integer to base 'base'. Where 'base' ranges from 2 to 36. Examples: >>> int_to_base(23, 2) '10111' >>> int_to_base(58, 5) '213' >>> int_to_base(167, 16) 'A7' >>> # bases below 2 and beyond 36 will error >>> int_to_base(98, 1) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive >>> int_to_base(98, 37) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive """ if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" result = "" if number < 0: raise ValueError("number must be a positive integer") while number > 0: number, remainder = divmod(number, base) result = digits[remainder] + result if result == "": result = "0" return result def sum_of_digits(num: int, base: int) -> str: """ Calculate the sum of digit values in a positive integer converted to the given 'base'. Where 'base' ranges from 2 to 36. Examples: >>> sum_of_digits(103, 12) '13' >>> sum_of_digits(1275, 4) '30' >>> sum_of_digits(6645, 2) '1001' >>> # bases below 2 and beyond 36 will error >>> sum_of_digits(543, 1) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive >>> sum_of_digits(543, 37) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive """ if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") num_str = int_to_base(num, base) res = sum(int(char, base) for char in num_str) res_str = int_to_base(res, base) return res_str def harshad_numbers_in_base(limit: int, base: int) -> list[str]: """ Finds all Harshad numbers smaller than num in base 'base'. Where 'base' ranges from 2 to 36. Examples: >>> harshad_numbers_in_base(15, 2) ['1', '10', '100', '110', '1000', '1010', '1100'] >>> harshad_numbers_in_base(12, 34) ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B'] >>> harshad_numbers_in_base(12, 4) ['1', '2', '3', '10', '12', '20', '21'] >>> # bases below 2 and beyond 36 will error >>> harshad_numbers_in_base(234, 37) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive >>> harshad_numbers_in_base(234, 1) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive """ if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") if limit < 0: return [] numbers = [ int_to_base(i, base) for i in range(1, limit) if i % int(sum_of_digits(i, base), base) == 0 ] return numbers def is_harshad_number_in_base(num: int, base: int) -> bool: """ Determines whether n in base 'base' is a harshad number. Where 'base' ranges from 2 to 36. Examples: >>> is_harshad_number_in_base(18, 10) True >>> is_harshad_number_in_base(21, 10) True >>> is_harshad_number_in_base(-21, 5) False >>> # bases below 2 and beyond 36 will error >>> is_harshad_number_in_base(45, 37) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive >>> is_harshad_number_in_base(45, 1) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive """ if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") if num < 0: return False n = int_to_base(num, base) d = sum_of_digits(num, base) return int(n, base) % int(d, base) == 0 if __name__ == "__main__": import doctest doctest.testmod()
Hexagonal Number The nth hexagonal number hn 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. https:en.wikipedia.orgwikiHexagonalnumber Author : Akshay Dubey https:github.comitsAkshayDubey :param number: nth hexagonal number to calculate :return: the nth hexagonal number Note: A hexagonal number is only defined for positive integers hexagonal4 28 hexagonal11 231 hexagonal22 946 hexagonal0 Traceback most recent call last: ... ValueError: Input must be a positive integer hexagonal1 Traceback most recent call last: ... ValueError: Input must be a positive integer hexagonal11.0 Traceback most recent call last: ... TypeError: Input value of number11.0 must be an integer
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) def hexagonal(number: int) -> int: """ :param number: nth hexagonal number to calculate :return: the nth hexagonal number Note: A hexagonal number is only defined for positive integers >>> hexagonal(4) 28 >>> hexagonal(11) 231 >>> hexagonal(22) 946 >>> hexagonal(0) Traceback (most recent call last): ... ValueError: Input must be a positive integer >>> hexagonal(-1) Traceback (most recent call last): ... ValueError: Input must be a positive integer >>> hexagonal(11.0) Traceback (most recent call last): ... TypeError: Input value of [number=11.0] must be an integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: raise ValueError("Input must be a positive integer") return number * (2 * number - 1) if __name__ == "__main__": import doctest doctest.testmod()
Krishnamurthy Number It is also known as Peterson Number A Krishnamurthy Number is a number whose sum of the factorial of the digits equals to the original number itself. For example: 145 1! 4! 5! So, 145 is a Krishnamurthy Number factorial3 6 factorial0 1 factorial5 120 krishnamurthy145 True krishnamurthy240 False krishnamurthy1 True
def factorial(digit: int) -> int: """ >>> factorial(3) 6 >>> factorial(0) 1 >>> factorial(5) 120 """ return 1 if digit in (0, 1) else (digit * factorial(digit - 1)) def krishnamurthy(number: int) -> bool: """ >>> krishnamurthy(145) True >>> krishnamurthy(240) False >>> krishnamurthy(1) True """ fact_sum = 0 duplicate = number while duplicate > 0: duplicate, digit = divmod(duplicate, 10) fact_sum += factorial(digit) return fact_sum == number if __name__ == "__main__": print("Program to check whether a number is a Krisnamurthy Number or not.") number = int(input("Enter number: ").strip()) print( f"{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number." )
Perfect Number In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For example: 6 divisors1, 2, 3, 6 Excluding 6, the sumdivisors is 1 2 3 6 So, 6 is a Perfect Number Other examples of Perfect Numbers: 28, 486, ... https:en.wikipedia.orgwikiPerfectnumber Check if a number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors excluding itself. Args: number: The number to be checked. Returns: True if the number is a perfect number, False otherwise. Start from 1 because dividing by 0 will raise ZeroDivisionError. A number at most can be divisible by the half of the number except the number itself. For example, 6 is at most can be divisible by 3 except by 6 itself. Examples: perfect27 False perfect28 True perfect29 False perfect6 True perfect12 False perfect496 True perfect8128 True perfect0 False perfect1 False perfect12.34 Traceback most recent call last: ... ValueError: number must be an integer perfectHello Traceback most recent call last: ... ValueError: number must be an integer
def perfect(number: int) -> bool: """ Check if a number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). Args: number: The number to be checked. Returns: True if the number is a perfect number, False otherwise. Start from 1 because dividing by 0 will raise ZeroDivisionError. A number at most can be divisible by the half of the number except the number itself. For example, 6 is at most can be divisible by 3 except by 6 itself. Examples: >>> perfect(27) False >>> perfect(28) True >>> perfect(29) False >>> perfect(6) True >>> perfect(12) False >>> perfect(496) True >>> perfect(8128) True >>> perfect(0) False >>> perfect(-1) False >>> perfect(12.34) Traceback (most recent call last): ... ValueError: number must be an integer >>> perfect("Hello") Traceback (most recent call last): ... ValueError: number must be an integer """ if not isinstance(number, int): raise ValueError("number must be an integer") if number <= 0: return False return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number if __name__ == "__main__": from doctest import testmod testmod() print("Program to check whether a number is a Perfect number or not...") try: number = int(input("Enter a positive integer: ").strip()) except ValueError: msg = "number must be an integer" print(msg) raise ValueError(msg) print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
Returns the numth sidesgonal number. It is assumed that num 0 and sides 3 see for reference https:en.wikipedia.orgwikiPolygonalnumber. polygonalnum0, 3 0 polygonalnum3, 3 6 polygonalnum5, 4 25 polygonalnum2, 5 5 polygonalnum1, 0 Traceback most recent call last: ... ValueError: Invalid input: num must be 0 and sides must be 3. polygonalnum0, 2 Traceback most recent call last: ... ValueError: Invalid input: num must be 0 and sides must be 3.
def polygonal_num(num: int, sides: int) -> int: """ Returns the `num`th `sides`-gonal number. It is assumed that `num` >= 0 and `sides` >= 3 (see for reference https://en.wikipedia.org/wiki/Polygonal_number). >>> polygonal_num(0, 3) 0 >>> polygonal_num(3, 3) 6 >>> polygonal_num(5, 4) 25 >>> polygonal_num(2, 5) 5 >>> polygonal_num(-1, 0) Traceback (most recent call last): ... ValueError: Invalid input: num must be >= 0 and sides must be >= 3. >>> polygonal_num(0, 2) Traceback (most recent call last): ... ValueError: Invalid input: num must be >= 0 and sides must be >= 3. """ if num < 0 or sides < 3: raise ValueError("Invalid input: num must be >= 0 and sides must be >= 3.") return ((sides - 2) * num**2 - (sides - 4) * num) // 2 if __name__ == "__main__": import doctest doctest.testmod()
Pronic Number A number n is said to be a Proic number if there exists an integer m such that n m m 1 Examples of Proic Numbers: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110 ... https:en.wikipedia.orgwikiPronicnumber Author : Akshay Dubey https:github.comitsAkshayDubey doctest: NORMALIZEWHITESPACE This functions takes an integer number as input. returns True if the number is pronic. ispronic1 False ispronic0 True ispronic2 True ispronic5 False ispronic6 True ispronic8 False ispronic30 True ispronic32 False ispronic2147441940 True ispronic9223372033963249500 True ispronic6.0 Traceback most recent call last: ... TypeError: Input value of number6.0 must be an integer
# Author : Akshay Dubey (https://github.com/itsAkshayDubey) def is_pronic(number: int) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes an integer number as input. returns True if the number is pronic. >>> is_pronic(-1) False >>> is_pronic(0) True >>> is_pronic(2) True >>> is_pronic(5) False >>> is_pronic(6) True >>> is_pronic(8) False >>> is_pronic(30) True >>> is_pronic(32) False >>> is_pronic(2147441940) True >>> is_pronic(9223372033963249500) True >>> is_pronic(6.0) Traceback (most recent call last): ... TypeError: Input value of [number=6.0] must be an integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 0 or number % 2 == 1: return False number_sqrt = int(number**0.5) return number == number_sqrt * (number_sqrt + 1) if __name__ == "__main__": import doctest doctest.testmod()
Calculate the nth Proth number Source: https:handwiki.orgwikiProthnumber :param number: nth number to calculate in the sequence :return: the nth number in Proth number Note: indexing starts at 1 i.e. proth1 gives the first Proth number of 3 proth6 25 proth0 Traceback most recent call last: ... ValueError: Input value of number0 must be 0 proth1 Traceback most recent call last: ... ValueError: Input value of number1 must be 0 proth6.0 Traceback most recent call last: ... TypeError: Input value of number6.0 must be an integer 1 for binary starting at 0 i.e. 20, 21, etc. 1 to start the sequence at the 3rd Proth number Hence, we have a 2 in the below statement
import math def proth(number: int) -> int: """ :param number: nth number to calculate in the sequence :return: the nth number in Proth number Note: indexing starts at 1 i.e. proth(1) gives the first Proth number of 3 >>> proth(6) 25 >>> proth(0) Traceback (most recent call last): ... ValueError: Input value of [number=0] must be > 0 >>> proth(-1) Traceback (most recent call last): ... ValueError: Input value of [number=-1] must be > 0 >>> proth(6.0) Traceback (most recent call last): ... TypeError: Input value of [number=6.0] must be an integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be > 0" raise ValueError(msg) elif number == 1: return 3 elif number == 2: return 5 else: """ +1 for binary starting at 0 i.e. 2^0, 2^1, etc. +1 to start the sequence at the 3rd Proth number Hence, we have a +2 in the below statement """ block_index = int(math.log(number // 3, 2)) + 2 proth_list = [3, 5] proth_index = 2 increment = 3 for block in range(1, block_index): for _ in range(increment): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1]) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): value = 0 try: value = proth(number) except ValueError: print(f"ValueError: there is no {number}th Proth number") continue print(f"The {number}th Proth number: {value}")