instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Write proper docstrings for these functions
import numpy as np def solution(limit: int = 1_000_000) -> int: # generating an array from -1 to limit phi = np.arange(-1, limit) for i in range(2, limit + 1): if phi[i] == i - 1: ind = np.arange(2 * i, limit + 1, i) # indexes for selection phi[ind] -= phi[ind] // i return int(np.sum(phi[2 : limit + 1])) if __name__ == "__main__": print(solution())
--- +++ @@ -1,8 +1,39 @@+""" +Problem 72 Counting fractions: https://projecteuler.net/problem=72 + +Description: + +Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, +it is called a reduced proper fraction. +If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we +get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, +3/4, 4/5, 5/6, 6/7, 7/8 +It can be seen that there are 21 elements in this set. +How many elements would be contained in the set of reduced proper fractions for +d ≤ 1,000,000? + +Solution: + +Number of numbers between 1 and n that are coprime to n is given by the Euler's Totient +function, phi(n). So, the answer is simply the sum of phi(n) for 2 <= n <= 1,000,000 +Sum of phi(d), for all d|n = n. This result can be used to find phi(n) using a sieve. + +Time: 1 sec +""" import numpy as np def solution(limit: int = 1_000_000) -> int: + """ + Returns an integer, the solution to the problem + >>> solution(10) + 31 + >>> solution(100) + 3043 + >>> solution(1_000) + 304191 + """ # generating an array from -1 to limit phi = np.arange(-1, limit) @@ -16,4 +47,4 @@ if __name__ == "__main__": - print(solution())+ print(solution())
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_072/sol1.py
Add missing documentation to my Python functions
def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: max_numerator = 0 max_denominator = 1 for current_denominator in range(1, limit + 1): current_numerator = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: max_numerator = current_numerator max_denominator = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1000000))
--- +++ @@ -1,6 +1,36 @@+""" +Ordered fractions +Problem 71 +https://projecteuler.net/problem=71 + +Consider the fraction n/d, where n and d are positive +integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. + +If we list the set of reduced proper fractions for d ≤ 8 +in ascending order of size, we get: + 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, + 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 + +It can be seen that 2/5 is the fraction immediately to the left of 3/7. + +By listing the set of reduced proper fractions for d ≤ 1,000,000 +in ascending order of size, find the numerator of the fraction +immediately to the left of 3/7. +""" def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: + """ + Returns the closest numerator of the fraction immediately to the + left of given fraction (numerator/denominator) from a list of reduced + proper fractions. + >>> solution() + 428570 + >>> solution(3, 7, 8) + 2 + >>> solution(6, 7, 60) + 47 + """ max_numerator = 0 max_denominator = 1 @@ -15,4 +45,4 @@ if __name__ == "__main__": - print(solution(numerator=3, denominator=7, limit=1000000))+ print(solution(numerator=3, denominator=7, limit=1000000))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_071/sol1.py
Auto-generate documentation strings for this file
import os def solution() -> int: script_dir = os.path.dirname(os.path.realpath(__file__)) triangle_path = os.path.join(script_dir, "triangle.txt") with open(triangle_path) as in_file: triangle = [[int(i) for i in line.split()] for line in in_file] while len(triangle) != 1: last_row = triangle.pop() curr_row = triangle[-1] for j in range(len(last_row) - 1): curr_row[j] += max(last_row[j], last_row[j + 1]) return triangle[0][0] if __name__ == "__main__": print(solution())
--- +++ @@ -1,8 +1,27 @@+""" +Problem Statement: +By starting at the top of the triangle below and moving to adjacent numbers on +the row below, the maximum total from top to bottom is 23. +3 +7 4 +2 4 6 +8 5 9 3 +That is, 3 + 7 + 4 + 9 = 23. +Find the maximum total from top to bottom in triangle.txt (right click and +'Save Link/Target As...'), a 15K text file containing a triangle with +one-hundred rows. +""" import os def solution() -> int: + """ + Finds the maximum total in a triangle as described by the problem statement + above. + >>> solution() + 7273 + """ script_dir = os.path.dirname(os.path.realpath(__file__)) triangle_path = os.path.join(script_dir, "triangle.txt") @@ -18,4 +37,4 @@ if __name__ == "__main__": - print(solution())+ print(solution())
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_067/sol2.py
Add docstrings to incomplete code
def solution(limit: int = 1000000) -> int: primes = set(range(3, limit, 2)) primes.add(2) for p in range(3, limit, 2): if p not in primes: continue primes.difference_update(set(range(p * p, limit, p))) phi = [float(n) for n in range(limit + 1)] for p in primes: for n in range(p, limit + 1, p): phi[n] *= 1 - 1 / p return int(sum(phi[2:])) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,30 @@+""" +Project Euler Problem 72: https://projecteuler.net/problem=72 + +Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, +it is called a reduced proper fraction. + +If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, +we get: + +1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, +4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 + +It can be seen that there are 21 elements in this set. + +How many elements would be contained in the set of reduced proper fractions +for d ≤ 1,000,000? +""" def solution(limit: int = 1000000) -> int: + """ + Return the number of reduced proper fractions with denominator less than limit. + >>> solution(8) + 21 + >>> solution(1000) + 304191 + """ primes = set(range(3, limit, 2)) primes.add(2) for p in range(3, limit, 2): @@ -18,4 +42,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_072/sol2.py
Help me document legacy Python code
from math import gcd def solution(max_d: int = 12_000) -> int: fractions_number = 0 for d in range(max_d + 1): n_start = d // 3 + 1 n_step = 1 if d % 2 == 0: n_start += 1 - n_start % 2 n_step = 2 for n in range(n_start, (d + 1) // 2, n_step): if gcd(n, d) == 1: fractions_number += 1 return fractions_number if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,38 @@+""" +Project Euler Problem 73: https://projecteuler.net/problem=73 + +Consider the fraction, n/d, where n and d are positive integers. +If n<d and HCF(n,d)=1, it is called a reduced proper fraction. + +If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, +we get: + +1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, +5/7, 3/4, 4/5, 5/6, 6/7, 7/8 + +It can be seen that there are 3 fractions between 1/3 and 1/2. + +How many fractions lie between 1/3 and 1/2 in the sorted set +of reduced proper fractions for d ≤ 12,000? +""" from math import gcd def solution(max_d: int = 12_000) -> int: + """ + Returns number of fractions lie between 1/3 and 1/2 in the sorted set + of reduced proper fractions for d ≤ max_d + + >>> solution(4) + 0 + + >>> solution(5) + 1 + + >>> solution(8) + 3 + """ fractions_number = 0 for d in range(max_d + 1): @@ -18,4 +48,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_073/sol1.py
Generate docstrings for exported functions
from __future__ import annotations from functools import lru_cache from math import ceil NUM_PRIMES = 100 primes = set(range(3, NUM_PRIMES, 2)) primes.add(2) prime: int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=100) def partition(number_to_partition: int) -> set[int]: if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} ret: set[int] = set() prime: int sub: int for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime): ret.add(sub * prime) return ret def solution(number_unique_partitions: int = 5000) -> int | None: for number_to_partition in range(1, NUM_PRIMES): if len(partition(number_to_partition)) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,17 @@+""" +Project Euler Problem 77: https://projecteuler.net/problem=77 + +It is possible to write ten as the sum of primes in exactly five different ways: + +7 + 3 +5 + 5 +5 + 3 + 2 +3 + 3 + 2 + 2 +2 + 2 + 2 + 2 + 2 + +What is the first value which can be written as the sum of primes in over +five thousand different ways? +""" from __future__ import annotations @@ -18,6 +32,17 @@ @lru_cache(maxsize=100) def partition(number_to_partition: int) -> set[int]: + """ + Return a set of integers corresponding to unique prime partitions of n. + The unique prime partitions can be represented as unique prime decompositions, + e.g. (7+3) <-> 7*3 = 12, (3+3+2+2) = 3*3*2*2 = 36 + >>> partition(10) + {32, 36, 21, 25, 30} + >>> partition(15) + {192, 160, 105, 44, 112, 243, 180, 150, 216, 26, 125, 126} + >>> len(partition(20)) + 26 + """ if number_to_partition < 0: return set() elif number_to_partition == 0: @@ -37,6 +62,16 @@ def solution(number_unique_partitions: int = 5000) -> int | None: + """ + Return the smallest integer that can be written as the sum of primes in over + m unique ways. + >>> solution(4) + 10 + >>> solution(500) + 45 + >>> solution(1000) + 53 + """ for number_to_partition in range(1, NUM_PRIMES): if len(partition(number_to_partition)) > number_unique_partitions: return number_to_partition @@ -44,4 +79,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_077/sol1.py
Add structured docstrings to improve clarity
from math import factorial DIGIT_FACTORIAL: dict[str, int] = {str(digit): factorial(digit) for digit in range(10)} def digit_factorial_sum(number: int) -> int: if not isinstance(number, int): raise TypeError("Parameter number must be int") if number < 0: raise ValueError("Parameter number must be greater than or equal to 0") # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(number)) def solution(chain_length: int = 60, number_limit: int = 1000000) -> int: if not isinstance(chain_length, int) or not isinstance(number_limit, int): raise TypeError("Parameters chain_length and number_limit must be int") if chain_length <= 0 or number_limit <= 0: raise ValueError( "Parameters chain_length and number_limit must be greater than 0" ) # the counter for the chains with the exact desired length chains_counter = 0 # the cached sizes of the previous chains chain_sets_lengths: dict[int, int] = {} for start_chain_element in range(1, number_limit): # The temporary set will contain the elements of the chain chain_set = set() chain_set_length = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. chain_element = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(chain_element) chain_set_length += 1 chain_element = digit_factorial_sum(chain_element) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] chain_sets_lengths[start_chain_element] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution()}")
--- +++ @@ -1,3 +1,38 @@+""" +Project Euler Problem 074: https://projecteuler.net/problem=74 + +The number 145 is well known for the property that the sum of the factorial of its +digits is equal to 145: + +1! + 4! + 5! = 1 + 24 + 120 = 145 + +Perhaps less well known is 169, in that it produces the longest chain of numbers that +link back to 169; it turns out that there are only three such loops that exist: + +169 → 363601 → 1454 → 169 +871 → 45361 → 871 +872 → 45362 → 872 + +It is not difficult to prove that EVERY starting number will eventually get stuck in a +loop. For example, + +69 → 363600 → 1454 → 169 → 363601 (→ 1454) +78 → 45360 → 871 → 45361 (→ 871) +540 → 145 (→ 145) + +Starting with 69 produces a chain of five non-repeating terms, but the longest +non-repeating chain with a starting number below one million is sixty terms. + +How many chains, with a starting number below one million, contain exactly sixty +non-repeating terms? + +Solution approach: +This solution simply consists in a loop that generates the chains of non repeating +items using the cached sizes of the previous chains. +The generation of the chain stops before a repeating item or if the size of the chain +is greater then the desired one. +After generating each chain, the length is checked and the counter increases. +""" from math import factorial @@ -5,6 +40,25 @@ def digit_factorial_sum(number: int) -> int: + """ + Function to perform the sum of the factorial of all the digits in number + + >>> digit_factorial_sum(69.0) + Traceback (most recent call last): + ... + TypeError: Parameter number must be int + + >>> digit_factorial_sum(-1) + Traceback (most recent call last): + ... + ValueError: Parameter number must be greater than or equal to 0 + + >>> digit_factorial_sum(0) + 1 + + >>> digit_factorial_sum(69) + 363600 + """ if not isinstance(number, int): raise TypeError("Parameter number must be int") @@ -16,6 +70,33 @@ def solution(chain_length: int = 60, number_limit: int = 1000000) -> int: + """ + Returns the number of numbers below number_limit that produce chains with exactly + chain_length non repeating elements. + + >>> solution(10.0, 1000) + Traceback (most recent call last): + ... + TypeError: Parameters chain_length and number_limit must be int + + >>> solution(10, 1000.0) + Traceback (most recent call last): + ... + TypeError: Parameters chain_length and number_limit must be int + + >>> solution(0, 1000) + Traceback (most recent call last): + ... + ValueError: Parameters chain_length and number_limit must be greater than 0 + + >>> solution(10, 0) + Traceback (most recent call last): + ... + ValueError: Parameters chain_length and number_limit must be greater than 0 + + >>> solution(10, 1000) + 26 + """ if not isinstance(chain_length, int) or not isinstance(number_limit, int): raise TypeError("Parameters chain_length and number_limit must be int") @@ -63,4 +144,4 @@ import doctest doctest.testmod() - print(f"{solution()}")+ print(f"{solution()}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_074/sol2.py
Add docstrings to improve collaboration
import itertools def solution(number: int = 1000000) -> int: partitions = [1] for i in itertools.count(len(partitions)): item = 0 for j in itertools.count(1): sign = -1 if j % 2 == 0 else +1 index = (j * j * 3 - j) // 2 if index > i: break item += partitions[i - index] * sign item %= number index += j if index > i: break item += partitions[i - index] * sign item %= number if item == 0: return i partitions.append(item) return 0 if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
--- +++ @@ -1,8 +1,35 @@+""" +Problem 78 +Url: https://projecteuler.net/problem=78 +Statement: +Let p(n) represent the number of different ways in which n coins +can be separated into piles. For example, five coins can be separated +into piles in exactly seven different ways, so p(5)=7. + + OOOOO + OOOO O + OOO OO + OOO O O + OO OO O + OO O O O + O O O O O +Find the least value of n for which p(n) is divisible by one million. +""" import itertools def solution(number: int = 1000000) -> int: + """ + >>> solution(1) + 1 + + >>> solution(9) + 14 + + >>> solution() + 55374 + """ partitions = [1] for i in itertools.count(len(partitions)): @@ -32,4 +59,4 @@ doctest.testmod() - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_078/sol1.py
Add verbose docstrings with examples
from collections import defaultdict from math import gcd def solution(limit: int = 1500000) -> int: frequencies: defaultdict = defaultdict(int) euclid_m = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1, euclid_m, 2): if gcd(euclid_m, euclid_n) > 1: continue primitive_perimeter = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(primitive_perimeter, limit + 1, primitive_perimeter): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,9 +1,47 @@+""" +Project Euler Problem 75: https://projecteuler.net/problem=75 + +It turns out that 12 cm is the smallest length of wire that can be bent to form an +integer sided right angle triangle in exactly one way, but there are many more examples. + +12 cm: (3,4,5) +24 cm: (6,8,10) +30 cm: (5,12,13) +36 cm: (9,12,15) +40 cm: (8,15,17) +48 cm: (12,16,20) + +In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided +right angle triangle, and other lengths allow more than one solution to be found; for +example, using 120 cm it is possible to form exactly three different integer sided +right angle triangles. + +120 cm: (30,40,50), (20,48,52), (24,45,51) + +Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can +exactly one integer sided right angle triangle be formed? + +Solution: we generate all pythagorean triples using Euclid's formula and +keep track of the frequencies of the perimeters. + +Reference: https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple +""" from collections import defaultdict from math import gcd def solution(limit: int = 1500000) -> int: + """ + Return the number of values of L <= limit such that a wire of length L can be + formmed into an integer sided right angle triangle in exactly one way. + >>> solution(50) + 6 + >>> solution(1000) + 112 + >>> solution(50000) + 5502 + """ frequencies: defaultdict = defaultdict(int) euclid_m = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: @@ -18,4 +56,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_075/sol1.py
Create docstrings for reusable components
import itertools from pathlib import Path def find_secret_passcode(logins: list[str]) -> int: # Split each login by character e.g. '319' -> ('3', '1', '9') split_logins = [tuple(login) for login in logins] unique_chars = {char for login in split_logins for char in login} for permutation in itertools.permutations(unique_chars): satisfied = True for login in logins: if not ( permutation.index(login[0]) < permutation.index(login[1]) < permutation.index(login[2]) ): satisfied = False break if satisfied: return int("".join(permutation)) raise Exception("Unable to find the secret passcode") def solution(input_file: str = "keylog.txt") -> int: logins = Path(__file__).parent.joinpath(input_file).read_text().splitlines() return find_secret_passcode(logins) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,9 +1,35 @@+""" +Project Euler Problem 79: https://projecteuler.net/problem=79 + +Passcode derivation + +A common security method used for online banking is to ask the user for three +random characters from a passcode. For example, if the passcode was 531278, +they may ask for the 2nd, 3rd, and 5th characters; the expected reply would +be: 317. + +The text file, keylog.txt, contains fifty successful login attempts. + +Given that the three characters are always asked for in order, analyse the file +so as to determine the shortest possible secret passcode of unknown length. +""" import itertools from pathlib import Path def find_secret_passcode(logins: list[str]) -> int: + """ + Returns the shortest possible secret passcode of unknown length. + + >>> find_secret_passcode(["135", "259", "235", "189", "690", "168", "120", + ... "136", "289", "589", "160", "165", "580", "369", "250", "280"]) + 12365890 + + >>> find_secret_passcode(["426", "281", "061", "819" "268", "406", "420", + ... "428", "209", "689", "019", "421", "469", "261", "681", "201"]) + 4206819 + """ # Split each login by character e.g. '319' -> ('3', '1', '9') split_logins = [tuple(login) for login in logins] @@ -28,10 +54,17 @@ def solution(input_file: str = "keylog.txt") -> int: + """ + Returns the shortest possible secret passcode of unknown length + for successful login attempts given by `input_file` text file. + + >>> solution("keylog_test.txt") + 6312980 + """ logins = Path(__file__).parent.joinpath(input_file).read_text().splitlines() return find_secret_passcode(logins) if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_079/sol1.py
Add structured docstrings to improve clarity
from __future__ import annotations from math import ceil, floor, sqrt def solution(target: int = 2000000) -> int: triangle_numbers: list[int] = [0] idx: int for idx in range(1, ceil(sqrt(target * 2) * 1.1)): triangle_numbers.append(triangle_numbers[-1] + idx) # we want this to be as close as possible to target best_product: int = 0 # the area corresponding to the grid that gives the product closest to target area: int = 0 # an estimate of b, using the quadratic formula b_estimate: float # the largest integer less than b_estimate b_floor: int # the largest integer less than b_estimate b_ceil: int # the triangle number corresponding to b_floor triangle_b_first_guess: int # the triangle number corresponding to b_ceil triangle_b_second_guess: int for idx_a, triangle_a in enumerate(triangle_numbers[1:], 1): b_estimate = (-1 + sqrt(1 + 8 * target / triangle_a)) / 2 b_floor = floor(b_estimate) b_ceil = ceil(b_estimate) triangle_b_first_guess = triangle_numbers[b_floor] triangle_b_second_guess = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a) < abs( target - best_product ): best_product = triangle_b_first_guess * triangle_a area = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a) < abs( target - best_product ): best_product = triangle_b_second_guess * triangle_a area = idx_a * b_ceil return area if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,49 @@+""" +Project Euler Problem 85: https://projecteuler.net/problem=85 + +By counting carefully it can be seen that a rectangular grid measuring 3 by 2 +contains eighteen rectangles. + +Although there exists no rectangular grid that contains exactly two million +rectangles, find the area of the grid with the nearest solution. + +Solution: + + For a grid with side-lengths a and b, the number of rectangles contained in the grid + is [a*(a+1)/2] * [b*(b+1)/2)], which happens to be the product of the a-th and b-th + triangle numbers. So to find the solution grid (a,b), we need to find the two + triangle numbers whose product is closest to two million. + + Denote these two triangle numbers Ta and Tb. We want their product Ta*Tb to be + as close as possible to 2m. Assuming that the best solution is fairly close to 2m, + We can assume that both Ta and Tb are roughly bounded by 2m. Since Ta = a(a+1)/2, + we can assume that a (and similarly b) are roughly bounded by sqrt(2 * 2m) = 2000. + Since this is a rough bound, to be on the safe side we add 10%. Therefore we start + by generating all the triangle numbers Ta for 1 <= a <= 2200. This can be done + iteratively since the ith triangle number is the sum of 1,2, ... ,i, and so + T(i) = T(i-1) + i. + + We then search this list of triangle numbers for the two that give a product + closest to our target of two million. Rather than testing every combination of 2 + elements of the list, which would find the result in quadratic time, we can find + the best pair in linear time. + + We iterate through the list of triangle numbers using enumerate() so we have a + and Ta. Since we want Ta * Tb to be as close as possible to 2m, we know that Tb + needs to be roughly 2m / Ta. Using the formula Tb = b*(b+1)/2 as well as the + quadratic formula, we can solve for b: + b is roughly (-1 + sqrt(1 + 8 * 2m / Ta)) / 2. + + Since the closest integers to this estimate will give product closest to 2m, + we only need to consider the integers above and below. It's then a simple matter + to get the triangle numbers corresponding to those integers, calculate the product + Ta * Tb, compare that product to our target 2m, and keep track of the (a,b) pair + that comes the closest. + + +Reference: https://en.wikipedia.org/wiki/Triangular_number + https://en.wikipedia.org/wiki/Quadratic_formula +""" from __future__ import annotations @@ -5,6 +51,16 @@ def solution(target: int = 2000000) -> int: + """ + Find the area of the grid which contains as close to two million rectangles + as possible. + >>> solution(20) + 6 + >>> solution(2000) + 72 + >>> solution(2000000000) + 86595 + """ triangle_numbers: list[int] = [0] idx: int @@ -49,4 +105,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_085/sol1.py
Add docstrings to improve code quality
import os def solution(filename: str = "matrix.txt") -> int: with open(os.path.join(os.path.dirname(__file__), filename)) as in_file: data = in_file.read() grid = [[int(cell) for cell in row.split(",")] for row in data.strip().splitlines()] dp = [[0 for cell in row] for row in grid] n = len(grid[0]) dp = [[0 for i in range(n)] for j in range(n)] dp[0][0] = grid[0][0] for i in range(1, n): dp[0][i] = grid[0][i] + dp[0][i - 1] for i in range(1, n): dp[i][0] = grid[i][0] + dp[i - 1][0] for i in range(1, n): for j in range(1, n): dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]) return dp[-1][-1] if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,28 @@+""" +Problem 81: https://projecteuler.net/problem=81 +In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, +by only moving to the right and down, is indicated in bold red and is equal to 2427. + + [131] 673 234 103 18 + [201] [96] [342] 965 150 + 630 803 [746] [422] 111 + 537 699 497 [121] 956 + 805 732 524 [37] [331] + +Find the minimal path sum from the top left to the bottom right by only moving right +and down in matrix.txt (https://projecteuler.net/project/resources/p081_matrix.txt), +a 31K text file containing an 80 by 80 matrix. +""" import os def solution(filename: str = "matrix.txt") -> int: + """ + Returns the minimal path sum from the top left to the bottom right of the matrix. + >>> solution() + 427337 + """ with open(os.path.join(os.path.dirname(__file__), filename)) as in_file: data = in_file.read() @@ -25,4 +45,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_081/sol1.py
Add documentation for all methods
import os def solution(filename: str = "input.txt") -> int: with open(os.path.join(os.path.dirname(__file__), filename)) as input_file: matrix = [ [int(element) for element in line.split(",")] for line in input_file.readlines() ] rows = len(matrix) cols = len(matrix[0]) minimal_path_sums = [[-1 for _ in range(cols)] for _ in range(rows)] for i in range(rows): minimal_path_sums[i][0] = matrix[i][0] for j in range(1, cols): for i in range(rows): minimal_path_sums[i][j] = minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1, rows): minimal_path_sums[i][j] = min( minimal_path_sums[i][j], minimal_path_sums[i - 1][j] + matrix[i][j] ) for i in range(rows - 2, -1, -1): minimal_path_sums[i][j] = min( minimal_path_sums[i][j], minimal_path_sums[i + 1][j] + matrix[i][j] ) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,35 @@+""" +Project Euler Problem 82: https://projecteuler.net/problem=82 + +The minimal path sum in the 5 by 5 matrix below, by starting in any cell +in the left column and finishing in any cell in the right column, +and only moving up, down, and right, is indicated in red and bold; +the sum is equal to 994. + + 131 673 [234] [103] [18] + [201] [96] [342] 965 150 + 630 803 746 422 111 + 537 699 497 121 956 + 805 732 524 37 331 + +Find the minimal path sum from the left column to the right column in matrix.txt +(https://projecteuler.net/project/resources/p082_matrix.txt) +(right click and "Save Link/Target As..."), +a 31K text file containing an 80 by 80 matrix. +""" import os def solution(filename: str = "input.txt") -> int: + """ + Returns the minimal path sum in the matrix from the file, by starting in any cell + in the left column and finishing in any cell in the right column, + and only moving up, down, and right + + >>> solution("test_matrix.txt") + 994 + """ with open(os.path.join(os.path.dirname(__file__), filename)) as input_file: matrix = [ @@ -35,4 +62,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_082/sol1.py
Document this script properly
def solution(limit: int = 50000000) -> int: ret = set() prime_square_limit = int((limit - 24) ** (1 / 2)) primes = set(range(3, prime_square_limit + 1, 2)) primes.add(2) for p in range(3, prime_square_limit + 1, 2): if p not in primes: continue primes.difference_update(set(range(p * p, prime_square_limit + 1, p))) for prime1 in primes: square = prime1 * prime1 for prime2 in primes: cube = prime2 * prime2 * prime2 if square + cube >= limit - 16: break for prime3 in primes: tetr = prime3 * prime3 * prime3 * prime3 total = square + cube + tetr if total >= limit: break ret.add(total) return len(ret) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,27 @@+""" +Project Euler Problem 87: https://projecteuler.net/problem=87 + +The smallest number expressible as the sum of a prime square, prime cube, and prime +fourth power is 28. In fact, there are exactly four numbers below fifty that can be +expressed in such a way: + +28 = 22 + 23 + 24 +33 = 32 + 23 + 24 +49 = 52 + 23 + 24 +47 = 22 + 33 + 24 + +How many numbers below fifty million can be expressed as the sum of a prime square, +prime cube, and prime fourth power? +""" def solution(limit: int = 50000000) -> int: + """ + Return the number of integers less than limit which can be expressed as the sum + of a prime square, prime cube, and prime fourth power. + >>> solution(50) + 4 + """ ret = set() prime_square_limit = int((limit - 24) ** (1 / 2)) @@ -28,4 +49,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_087/sol1.py
Add docstrings to improve readability
DIGIT_FACTORIALS = { "0": 1, "1": 1, "2": 2, "3": 6, "4": 24, "5": 120, "6": 720, "7": 5040, "8": 40320, "9": 362880, } CACHE_SUM_DIGIT_FACTORIALS = {145: 145} CHAIN_LENGTH_CACHE = { 145: 0, 169: 3, 36301: 3, 1454: 3, 871: 2, 45361: 2, 872: 2, } def sum_digit_factorials(n: int) -> int: if n in CACHE_SUM_DIGIT_FACTORIALS: return CACHE_SUM_DIGIT_FACTORIALS[n] ret = sum(DIGIT_FACTORIALS[let] for let in str(n)) CACHE_SUM_DIGIT_FACTORIALS[n] = ret return ret def chain_length(n: int, previous: set | None = None) -> int: previous = previous or set() if n in CHAIN_LENGTH_CACHE: return CHAIN_LENGTH_CACHE[n] next_number = sum_digit_factorials(n) if next_number in previous: CHAIN_LENGTH_CACHE[n] = 0 return 0 else: previous.add(n) ret = 1 + chain_length(next_number, previous) CHAIN_LENGTH_CACHE[n] = ret return ret def solution(num_terms: int = 60, max_start: int = 1000000) -> int: return sum(1 for i in range(1, max_start) if chain_length(i) == num_terms) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,31 @@+""" +Project Euler Problem 74: https://projecteuler.net/problem=74 + +The number 145 is well known for the property that the sum of the factorial of its +digits is equal to 145: + +1! + 4! + 5! = 1 + 24 + 120 = 145 + +Perhaps less well known is 169, in that it produces the longest chain of numbers that +link back to 169; it turns out that there are only three such loops that exist: + +169 → 363601 → 1454 → 169 +871 → 45361 → 871 +872 → 45362 → 872 + +It is not difficult to prove that EVERY starting number will eventually get stuck in +a loop. For example, + +69 → 363600 → 1454 → 169 → 363601 (→ 1454) +78 → 45360 → 871 → 45361 (→ 871) +540 → 145 (→ 145) + +Starting with 69 produces a chain of five non-repeating terms, but the longest +non-repeating chain with a starting number below one million is sixty terms. + +How many chains, with a starting number below one million, contain exactly sixty +non-repeating terms? +""" DIGIT_FACTORIALS = { "0": 1, @@ -26,6 +54,15 @@ def sum_digit_factorials(n: int) -> int: + """ + Return the sum of the factorial of the digits of n. + >>> sum_digit_factorials(145) + 145 + >>> sum_digit_factorials(45361) + 871 + >>> sum_digit_factorials(540) + 145 + """ if n in CACHE_SUM_DIGIT_FACTORIALS: return CACHE_SUM_DIGIT_FACTORIALS[n] ret = sum(DIGIT_FACTORIALS[let] for let in str(n)) @@ -34,6 +71,16 @@ def chain_length(n: int, previous: set | None = None) -> int: + """ + Calculate the length of the chain of non-repeating terms starting with n. + Previous is a set containing the previous member of the chain. + >>> chain_length(10101) + 11 + >>> chain_length(555) + 20 + >>> chain_length(178924) + 39 + """ previous = previous or set() if n in CHAIN_LENGTH_CACHE: return CHAIN_LENGTH_CACHE[n] @@ -49,8 +96,14 @@ def solution(num_terms: int = 60, max_start: int = 1000000) -> int: + """ + Return the number of chains with a starting number below one million which + contain exactly n non-repeating terms. + >>> solution(10,1000) + 28 + """ return sum(1 for i in range(1, max_start) if chain_length(i) == num_terms) if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_074/sol1.py
Add professional docstrings to my codebase
import os SYMBOLS = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def parse_roman_numerals(numerals: str) -> int: total_value = 0 index = 0 while index < len(numerals) - 1: current_value = SYMBOLS[numerals[index]] next_value = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def generate_roman_numerals(num: int) -> str: numerals = "" m_count = num // 1000 numerals += m_count * "M" num %= 1000 c_count = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 x_count = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int: savings = 0 with open(os.path.dirname(__file__) + roman_numerals_filename) as file1: lines = file1.readlines() for line in lines: original = line.strip() num = parse_roman_numerals(original) shortened = generate_roman_numerals(num) savings += len(original) - len(shortened) return savings if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,32 @@+""" +Project Euler Problem 89: https://projecteuler.net/problem=89 + +For a number written in Roman numerals to be considered valid there are basic rules +which must be followed. Even though the rules allow some numbers to be expressed in +more than one way there is always a "best" way of writing a particular number. + +For example, it would appear that there are at least six ways of writing the number +sixteen: + +IIIIIIIIIIIIIIII +VIIIIIIIIIII +VVIIIIII +XIIIIII +VVVI +XVI + +However, according to the rules only XIIIIII and XVI are valid, and the last example +is considered to be the most efficient, as it uses the least number of numerals. + +The 11K text file, roman.txt (right click and 'Save Link/Target As...'), contains one +thousand numbers written in valid, but not necessarily minimal, Roman numerals; see +About... Roman Numerals for the definitive rules for this problem. + +Find the number of characters saved by writing each of these in their minimal form. + +Note: You can assume that all the Roman numerals in the file contain no more than four +consecutive identical units. +""" import os @@ -5,6 +34,14 @@ def parse_roman_numerals(numerals: str) -> int: + """ + Converts a string of roman numerals to an integer. + e.g. + >>> parse_roman_numerals("LXXXIX") + 89 + >>> parse_roman_numerals("IIII") + 4 + """ total_value = 0 @@ -23,6 +60,14 @@ def generate_roman_numerals(num: int) -> str: + """ + Generates a string of roman numerals for a given integer. + e.g. + >>> generate_roman_numerals(89) + 'LXXXIX' + >>> generate_roman_numerals(4) + 'IV' + """ numerals = "" @@ -71,6 +116,12 @@ def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int: + """ + Calculates and returns the answer to project euler problem 89. + + >>> solution("/numeralcleanup_test.txt") + 16 + """ savings = 0 @@ -87,4 +138,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_089/sol1.py
Write beginner-friendly docstrings
import decimal def solution() -> int: answer = 0 decimal_context = decimal.Context(prec=105) for i in range(2, 100): number = decimal.Decimal(i) sqrt_number = number.sqrt(decimal_context) if len(str(sqrt_number)) > 1: answer += int(str(sqrt_number)[0]) sqrt_number_str = str(sqrt_number)[2:101] answer += sum(int(x) for x in sqrt_number_str) return answer if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
--- +++ @@ -1,8 +1,25 @@+""" +Project Euler Problem 80: https://projecteuler.net/problem=80 +Author: Sandeep Gupta +Problem statement: For the first one hundred natural numbers, find the total of +the digital sums of the first one hundred decimal digits for all the irrational +square roots. +Time: 5 October 2020, 18:30 +""" import decimal def solution() -> int: + """ + To evaluate the sum, Used decimal python module to calculate the decimal + places up to 100, the most important thing would be take calculate + a few extra places for decimal otherwise there will be rounding + error. + + >>> solution() + 40886 + """ answer = 0 decimal_context = decimal.Context(prec=105) for i in range(2, 100): @@ -19,4 +36,4 @@ import doctest doctest.testmod() - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_080/sol1.py
Help me document legacy Python code
def solution(m: int = 100) -> int: memo = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 for n in range(m + 1): for k in range(1, m): memo[n][k] += memo[n][k - 1] if n > k: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] - 1 if __name__ == "__main__": print(solution(int(input("Enter a number: ").strip())))
--- +++ @@ -1,6 +1,43 @@+""" +Counting Summations +Problem 76: https://projecteuler.net/problem=76 + +It is possible to write five as a sum in exactly six different ways: + +4 + 1 +3 + 2 +3 + 1 + 1 +2 + 2 + 1 +2 + 1 + 1 + 1 +1 + 1 + 1 + 1 + 1 + +How many different ways can one hundred be written as a sum of at least two +positive integers? +""" def solution(m: int = 100) -> int: + """ + Returns the number of different ways the number m can be written as a + sum of at least two positive integers. + + >>> solution(100) + 190569291 + >>> solution(50) + 204225 + >>> solution(30) + 5603 + >>> solution(10) + 41 + >>> solution(5) + 6 + >>> solution(3) + 2 + >>> solution(2) + 1 + >>> solution(1) + 0 + """ memo = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 @@ -15,4 +52,4 @@ if __name__ == "__main__": - print(solution(int(input("Enter a number: ").strip())))+ print(solution(int(input("Enter a number: ").strip())))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_076/sol1.py
Add docstrings explaining edge cases
from math import sqrt def solution(limit: int = 1000000) -> int: num_cuboids: int = 0 max_cuboid_size: int = 0 sum_shortest_sides: int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2, 2 * max_cuboid_size + 1): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2).is_integer(): num_cuboids += ( min(max_cuboid_size, sum_shortest_sides // 2) - max(1, sum_shortest_sides - max_cuboid_size) + 1 ) return max_cuboid_size if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,88 @@+""" +Project Euler Problem 86: https://projecteuler.net/problem=86 + +A spider, S, sits in one corner of a cuboid room, measuring 6 by 5 by 3, and a fly, F, +sits in the opposite corner. By travelling on the surfaces of the room the shortest +"straight line" distance from S to F is 10 and the path is shown on the diagram. + +However, there are up to three "shortest" path candidates for any given cuboid and the +shortest route doesn't always have integer length. + +It can be shown that there are exactly 2060 distinct cuboids, ignoring rotations, with +integer dimensions, up to a maximum size of M by M by M, for which the shortest route +has integer length when M = 100. This is the least value of M for which the number of +solutions first exceeds two thousand; the number of solutions when M = 99 is 1975. + +Find the least value of M such that the number of solutions first exceeds one million. + +Solution: + Label the 3 side-lengths of the cuboid a,b,c such that 1 <= a <= b <= c <= M. + By conceptually "opening up" the cuboid and laying out its faces on a plane, + it can be seen that the shortest distance between 2 opposite corners is + sqrt((a+b)^2 + c^2). This distance is an integer if and only if (a+b),c make up + the first 2 sides of a pythagorean triplet. + + The second useful insight is rather than calculate the number of cuboids + with integral shortest distance for each maximum cuboid side-length M, + we can calculate this number iteratively each time we increase M, as follows. + The set of cuboids satisfying this property with maximum side-length M-1 is a + subset of the cuboids satisfying the property with maximum side-length M + (since any cuboids with side lengths <= M-1 are also <= M). To calculate the + number of cuboids in the larger set (corresponding to M) we need only consider + the cuboids which have at least one side of length M. Since we have ordered the + side lengths a <= b <= c, we can assume that c = M. Then we just need to count + the number of pairs a,b satisfying the conditions: + sqrt((a+b)^2 + M^2) is integer + 1 <= a <= b <= M + + To count the number of pairs (a,b) satisfying these conditions, write d = a+b. + Now we have: + 1 <= a <= b <= M => 2 <= d <= 2*M + we can actually make the second equality strict, + since d = 2*M => d^2 + M^2 = 5M^2 + => shortest distance = M * sqrt(5) + => not integral. + a + b = d => b = d - a + and a <= b + => a <= d/2 + also a <= M + => a <= min(M, d//2) + + a + b = d => a = d - b + and b <= M + => a >= d - M + also a >= 1 + => a >= max(1, d - M) + + So a is in range(max(1, d - M), min(M, d // 2) + 1) + + For a given d, the number of cuboids satisfying the required property with c = M + and a + b = d is the length of this range, which is + min(M, d // 2) + 1 - max(1, d - M). + + In the code below, d is sum_shortest_sides + and M is max_cuboid_size. + + +""" from math import sqrt def solution(limit: int = 1000000) -> int: + """ + Return the least value of M such that there are more than one million cuboids + of side lengths 1 <= a,b,c <= M such that the shortest distance between two + opposite vertices of the cuboid is integral. + >>> solution(100) + 24 + >>> solution(1000) + 72 + >>> solution(2000) + 100 + >>> solution(20000) + 288 + """ num_cuboids: int = 0 max_cuboid_size: int = 0 sum_shortest_sides: int @@ -21,4 +101,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_086/sol1.py
Document functions with detailed explanations
def solution(max_perimeter: int = 10**9) -> int: prev_value = 1 value = 2 perimeters_sum = 0 i = 0 perimeter = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value perimeter = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,26 @@+""" +Project Euler Problem 94: https://projecteuler.net/problem=94 + +It is easily proved that no equilateral triangle exists with integral length sides and +integral area. However, the almost equilateral triangle 5-5-6 has an area of 12 square +units. + +We shall define an almost equilateral triangle to be a triangle for which two sides are +equal and the third differs by no more than one unit. + +Find the sum of the perimeters of all almost equilateral triangles with integral side +lengths and area and whose perimeters do not exceed one billion (1,000,000,000). +""" def solution(max_perimeter: int = 10**9) -> int: + """ + Returns the sum of the perimeters of all almost equilateral triangles with integral + side lengths and area and whose perimeters do not exceed max_perimeter + + >>> solution(20) + 16 + """ prev_value = 1 value = 2 @@ -21,4 +41,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_094/sol1.py
Create documentation for each function signature
from math import isqrt def generate_primes(max_num: int) -> list[int]: are_primes = [True] * (max_num + 1) are_primes[0] = are_primes[1] = False for i in range(2, isqrt(max_num) + 1): if are_primes[i]: for j in range(i * i, max_num + 1, i): are_primes[j] = False return [prime for prime, is_prime in enumerate(are_primes) if is_prime] def multiply( chain: list[int], primes: list[int], min_prime_idx: int, prev_num: int, max_num: int, prev_sum: int, primes_degrees: dict[int, int], ) -> None: min_prime = primes[min_prime_idx] num = prev_num * min_prime min_prime_degree = primes_degrees.get(min_prime, 0) min_prime_degree += 1 primes_degrees[min_prime] = min_prime_degree new_sum = prev_sum * min_prime + (prev_sum + prev_num) * (min_prime - 1) // ( min_prime**min_prime_degree - 1 ) chain[num] = new_sum for prime_idx in range(min_prime_idx, len(primes)): if primes[prime_idx] * num > max_num: break multiply( chain=chain, primes=primes, min_prime_idx=prime_idx, prev_num=num, max_num=max_num, prev_sum=new_sum, primes_degrees=primes_degrees.copy(), ) def find_longest_chain(chain: list[int], max_num: int) -> int: max_len = 0 min_elem = 0 for start in range(2, len(chain)): visited = {start} elem = chain[start] length = 1 while elem > 1 and elem <= max_num and elem not in visited: visited.add(elem) elem = chain[elem] length += 1 if elem == start and length > max_len: max_len = length min_elem = start return min_elem def solution(max_num: int = 1000000) -> int: primes = generate_primes(max_num) chain = [0] * (max_num + 1) for prime_idx, prime in enumerate(primes): if prime**2 > max_num: break multiply( chain=chain, primes=primes, min_prime_idx=prime_idx, prev_num=1, max_num=max_num, prev_sum=0, primes_degrees={}, ) return find_longest_chain(chain=chain, max_num=max_num) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,43 @@+""" +Project Euler Problem 95: https://projecteuler.net/problem=95 + +Amicable Chains + +The proper divisors of a number are all the divisors excluding the number itself. +For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. +As the sum of these divisors is equal to 28, we call it a perfect number. + +Interestingly the sum of the proper divisors of 220 is 284 and +the sum of the proper divisors of 284 is 220, forming a chain of two numbers. +For this reason, 220 and 284 are called an amicable pair. + +Perhaps less well known are longer chains. +For example, starting with 12496, we form a chain of five numbers: + 12496 -> 14288 -> 15472 -> 14536 -> 14264 (-> 12496 -> ...) + +Since this chain returns to its starting point, it is called an amicable chain. + +Find the smallest member of the longest amicable chain with +no element exceeding one million. + +Solution is doing the following: +- Get relevant prime numbers +- Iterate over product combination of prime numbers to generate all non-prime + numbers up to max number, by keeping track of prime factors +- Calculate the sum of factors for each number +- Iterate over found some factors to find longest chain +""" from math import isqrt def generate_primes(max_num: int) -> list[int]: + """ + Calculates the list of primes up to and including `max_num`. + + >>> generate_primes(6) + [2, 3, 5] + """ are_primes = [True] * (max_num + 1) are_primes[0] = are_primes[1] = False for i in range(2, isqrt(max_num) + 1): @@ -22,6 +57,25 @@ prev_sum: int, primes_degrees: dict[int, int], ) -> None: + """ + Run over all prime combinations to generate non-prime numbers. + + >>> chain = [0] * 3 + >>> primes_degrees = {} + >>> multiply( + ... chain=chain, + ... primes=[2], + ... min_prime_idx=0, + ... prev_num=1, + ... max_num=2, + ... prev_sum=0, + ... primes_degrees=primes_degrees, + ... ) + >>> chain + [0, 0, 1] + >>> primes_degrees + {2: 1} + """ min_prime = primes[min_prime_idx] num = prev_num * min_prime @@ -51,6 +105,12 @@ def find_longest_chain(chain: list[int], max_num: int) -> int: + """ + Finds the smallest element of longest chain + + >>> find_longest_chain(chain=[0, 0, 0, 0, 0, 0, 6], max_num=6) + 6 + """ max_len = 0 min_elem = 0 @@ -72,6 +132,14 @@ def solution(max_num: int = 1000000) -> int: + """ + Runs the calculation for numbers <= `max_num`. + + >>> solution(10) + 6 + >>> solution(200000) + 12496 + """ primes = generate_primes(max_num) chain = [0] * (max_num + 1) @@ -93,4 +161,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_095/sol1.py
Include argument descriptions in docstrings
def solution(n: int = 10) -> str: if not isinstance(n, int) or n < 0: raise ValueError("Invalid input") modulus = 10**n number = 28433 * (pow(2, 7830457, modulus)) + 1 return str(number % modulus) if __name__ == "__main__": from doctest import testmod testmod() print(f"{solution(10) = }")
--- +++ @@ -1,15 +1,46 @@- - -def solution(n: int = 10) -> str: - if not isinstance(n, int) or n < 0: - raise ValueError("Invalid input") - modulus = 10**n - number = 28433 * (pow(2, 7830457, modulus)) + 1 - return str(number % modulus) - - -if __name__ == "__main__": - from doctest import testmod - - testmod() - print(f"{solution(10) = }")+""" +The first known prime found to exceed one million digits was discovered in 1999, +and is a Mersenne prime of the form 2**6972593 - 1; it contains exactly 2,098,960 +digits. Subsequently other Mersenne primes, of the form 2**p - 1, have been found +which contain more digits. +However, in 2004 there was found a massive non-Mersenne prime which contains +2,357,207 digits: (28433 * (2 ** 7830457 + 1)). + +Find the last ten digits of this prime number. +""" + + +def solution(n: int = 10) -> str: + """ + Returns the last n digits of NUMBER. + >>> solution() + '8739992577' + >>> solution(8) + '39992577' + >>> solution(1) + '7' + >>> solution(-1) + Traceback (most recent call last): + ... + ValueError: Invalid input + >>> solution(8.3) + Traceback (most recent call last): + ... + ValueError: Invalid input + >>> solution("a") + Traceback (most recent call last): + ... + ValueError: Invalid input + """ + if not isinstance(n, int) or n < 0: + raise ValueError("Invalid input") + modulus = 10**n + number = 28433 * (pow(2, 7830457, modulus)) + 1 + return str(number % modulus) + + +if __name__ == "__main__": + from doctest import testmod + + testmod() + print(f"{solution(10) = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_097/sol1.py
Generate docstrings for exported functions
DIGITS_SQUARED = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(100000)] def next_number(number: int) -> int: sum_of_digits_squared = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution CHAINS: list[bool | None] = [None] * 10000000 CHAINS[0] = True CHAINS[57] = False def chain(number: int) -> bool: if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore[return-value] number_chain = chain(next_number(number)) CHAINS[number - 1] = number_chain while number < 10000000: CHAINS[number - 1] = number_chain number *= 10 return number_chain def solution(number: int = 10000000) -> int: for i in range(1, number): if CHAINS[i] is None: chain(i + 1) return CHAINS[:number].count(False) if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
--- +++ @@ -1,8 +1,32 @@+""" +Project Euler Problem 092: https://projecteuler.net/problem=92 +Square digit chains +A number chain is created by continuously adding the square of the digits in +a number to form a new number until it has been seen before. +For example, +44 → 32 → 13 → 10 → 1 → 1 +85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 +Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. +What is most amazing is that EVERY starting number will eventually arrive at 1 or 89. +How many starting numbers below ten million will arrive at 89? +""" DIGITS_SQUARED = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(100000)] def next_number(number: int) -> int: + """ + Returns the next number of the chain by adding the square of each digit + to form a new number. + For example, if number = 12, next_number() will return 1^2 + 2^2 = 5. + Therefore, 5 is the next number of the chain. + >>> next_number(44) + 32 + >>> next_number(10) + 1 + >>> next_number(32) + 13 + """ sum_of_digits_squared = 0 while number: @@ -28,6 +52,20 @@ def chain(number: int) -> bool: + """ + The function generates the chain of numbers until the next number is 1 or 89. + For example, if starting number is 44, then the function generates the + following chain of numbers: + 44 → 32 → 13 → 10 → 1 → 1. + Once the next number generated is 1 or 89, the function returns whether + or not the next number generated by next_number() is 1. + >>> chain(10) + True + >>> chain(58) + False + >>> chain(1) + True + """ if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore[return-value] @@ -43,6 +81,16 @@ def solution(number: int = 10000000) -> int: + """ + The function returns the number of integers that end up being 89 in each chain. + The function accepts a range number and the function checks all the values + under value number. + + >>> solution(100) + 80 + >>> solution(10000000) + 8581146 + """ for i in range(1, number): if CHAINS[i] is None: chain(i + 1) @@ -54,4 +102,4 @@ import doctest doctest.testmod() - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_092/sol1.py
Write docstrings for backend logic
from itertools import combinations, product def is_right(x1: int, y1: int, x2: int, y2: int) -> bool: if x1 == y1 == 0 or x2 == y2 == 0: return False a_square = x1 * x1 + y1 * y1 b_square = x2 * x2 + y2 * y2 c_square = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) return ( a_square + b_square == c_square or a_square + c_square == b_square or b_square + c_square == a_square ) def solution(limit: int = 50) -> int: return sum( 1 for pt1, pt2 in combinations(product(range(limit + 1), repeat=2), 2) if is_right(*pt1, *pt2) ) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,30 @@+""" +Project Euler Problem 91: https://projecteuler.net/problem=91 + +The points P (x1, y1) and Q (x2, y2) are plotted at integer coordinates and +are joined to the origin, O(0,0), to form ΔOPQ. + +There are exactly fourteen triangles containing a right angle that can be formed +when each coordinate lies between 0 and 2 inclusive; that is, +0 ≤ x1, y1, x2, y2 ≤ 2. + +Given that 0 ≤ x1, y1, x2, y2 ≤ 50, how many right triangles can be formed? +""" from itertools import combinations, product def is_right(x1: int, y1: int, x2: int, y2: int) -> bool: + """ + Check if the triangle described by P(x1,y1), Q(x2,y2) and O(0,0) is right-angled. + Note: this doesn't check if P and Q are equal, but that's handled by the use of + itertools.combinations in the solution function. + + >>> is_right(0, 1, 2, 0) + True + >>> is_right(1, 0, 2, 2) + False + """ if x1 == y1 == 0 or x2 == y2 == 0: return False a_square = x1 * x1 + y1 * y1 @@ -16,6 +38,15 @@ def solution(limit: int = 50) -> int: + """ + Return the number of right triangles OPQ that can be formed by two points P, Q + which have both x- and y- coordinates between 0 and limit inclusive. + + >>> solution(2) + 14 + >>> solution(10) + 448 + """ return sum( 1 for pt1, pt2 in combinations(product(range(limit + 1), repeat=2), 2) @@ -24,4 +55,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_091/sol1.py
Create documentation strings for testing functions
import sys sys.set_int_max_str_digits(0) def check(number: int) -> bool: check_last = [0] * 11 check_front = [0] * 11 # mark last 9 numbers for _ in range(9): check_last[int(number % 10)] = 1 number = number // 10 # flag f = True # check last 9 numbers for pandigitality for x in range(9): if not check_last[x + 1]: f = False if not f: return f # mark first 9 numbers number = int(str(number)[:9]) for _ in range(9): check_front[int(number % 10)] = 1 number = number // 10 # check first 9 numbers for pandigitality for x in range(9): if not check_front[x + 1]: f = False return f def check1(number: int) -> bool: check_last = [0] * 11 # mark last 9 numbers for _ in range(9): check_last[int(number % 10)] = 1 number = number // 10 # flag f = True # check last 9 numbers for pandigitality for x in range(9): if not check_last[x + 1]: f = False return f def solution() -> int: a = 1 b = 1 c = 2 # temporary Fibonacci numbers a1 = 1 b1 = 1 c1 = 2 # temporary Fibonacci numbers mod 1e9 # mod m=1e9, done for fast optimisation tocheck = [0] * 1000000 m = 1000000000 for x in range(1000000): c1 = (a1 + b1) % m a1 = b1 % m b1 = c1 % m if check1(b1): tocheck[x + 3] = 1 for x in range(1000000): c = a + b a = b b = c # perform check only if in tocheck if tocheck[x + 3] and check(b): return x + 3 # first 2 already done return -1 if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,17 @@+""" +Project Euler Problem 104 : https://projecteuler.net/problem=104 + +The Fibonacci sequence is defined by the recurrence relation: + +Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1. +It turns out that F541, which contains 113 digits, is the first Fibonacci number +for which the last nine digits are 1-9 pandigital (contain all the digits 1 to 9, +but not necessarily in order). And F2749, which contains 575 digits, is the first +Fibonacci number for which the first nine digits are 1-9 pandigital. + +Given that Fk is the first Fibonacci number for which the first nine digits AND +the last nine digits are 1-9 pandigital, find k. +""" import sys @@ -5,6 +19,20 @@ def check(number: int) -> bool: + """ + Takes a number and checks if it is pandigital both from start and end + + + >>> check(123456789987654321) + True + + >>> check(120000987654321) + False + + >>> check(1234567895765677987654321) + True + + """ check_last = [0] * 11 check_front = [0] * 11 @@ -40,6 +68,19 @@ def check1(number: int) -> bool: + """ + Takes a number and checks if it is pandigital from END + + >>> check1(123456789987654321) + True + + >>> check1(120000987654321) + True + + >>> check1(12345678957656779870004321) + False + + """ check_last = [0] * 11 @@ -59,6 +100,11 @@ def solution() -> int: + """ + Outputs the answer is the least Fibonacci number pandigital from both sides. + >>> solution() + 329468 + """ a = 1 b = 1 @@ -92,4 +138,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_104/sol1.py
Write Python docstrings for this snippet
def sylvester(number: int) -> int: assert isinstance(number, int), f"The input value of [n={number}] is not an integer" if number == 1: return 2 elif number < 1: msg = f"The input value of [n={number}] has to be > 0" raise ValueError(msg) else: num = sylvester(number - 1) lower = num - 1 upper = num return lower * upper + 1 if __name__ == "__main__": print(f"The 8th number in Sylvester's sequence: {sylvester(8)}")
--- +++ @@ -1,6 +1,31 @@+""" + +Calculates the nth number in Sylvester's sequence + +Source: + https://en.wikipedia.org/wiki/Sylvester%27s_sequence + +""" def sylvester(number: int) -> int: + """ + :param number: nth number to calculate in the sequence + :return: the nth number in Sylvester's sequence + + >>> sylvester(8) + 113423713055421844361000443 + + >>> sylvester(-1) + Traceback (most recent call last): + ... + ValueError: The input value of [n=-1] has to be > 0 + + >>> sylvester(8.0) + Traceback (most recent call last): + ... + AssertionError: The input value of [n=8.0] is not an integer + """ assert isinstance(number, int), f"The input value of [n={number}] is not an integer" if number == 1: @@ -16,4 +41,4 @@ if __name__ == "__main__": - print(f"The 8th number in Sylvester's sequence: {sylvester(8)}")+ print(f"The 8th number in Sylvester's sequence: {sylvester(8)}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/sylvester_sequence.py
Document this code for team use
from __future__ import annotations from collections.abc import Callable Matrix = list[list[float | int]] def solve(matrix: Matrix, vector: Matrix) -> Matrix: size: int = len(matrix) augmented: Matrix = [[0 for _ in range(size + 1)] for _ in range(size)] row: int row2: int col: int col2: int pivot_row: int ratio: float for row in range(size): for col in range(size): augmented[row][col] = matrix[row][col] augmented[row][size] = vector[row][0] row = 0 col = 0 while row < size and col < size: # pivoting pivot_row = max((abs(augmented[row2][col]), row2) for row2 in range(col, size))[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: augmented[row], augmented[pivot_row] = augmented[pivot_row], augmented[row] for row2 in range(row + 1, size): ratio = augmented[row2][col] / augmented[row][col] augmented[row2][col] = 0 for col2 in range(col + 1, size + 1): augmented[row2][col2] -= augmented[row][col2] * ratio row += 1 col += 1 # back substitution for col in range(1, size): for row in range(col): ratio = augmented[row][col] / augmented[col][col] for col2 in range(col, size + 1): augmented[row][col2] -= augmented[col][col2] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row], 10)] for row in range(size) ] def interpolate(y_list: list[int]) -> Callable[[int], int]: size: int = len(y_list) matrix: Matrix = [[0 for _ in range(size)] for _ in range(size)] vector: Matrix = [[0] for _ in range(size)] coeffs: Matrix x_val: int y_val: int col: int for x_val, y_val in enumerate(y_list): for col in range(size): matrix[x_val][col] = (x_val + 1) ** (size - col - 1) vector[x_val][0] = y_val coeffs = solve(matrix, vector) def interpolated_func(var: int) -> int: return sum( round(coeffs[x_val][0]) * (var ** (size - x_val - 1)) for x_val in range(size) ) return interpolated_func def question_function(variable: int) -> int: return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def solution(func: Callable[[int], int] = question_function, order: int = 10) -> int: data_points: list[int] = [func(x_val) for x_val in range(1, order + 1)] polynomials: list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff]) for max_coeff in range(1, order + 1) ] ret: int = 0 poly: Callable[[int], int] x_val: int for poly in polynomials: x_val = 1 while func(x_val) == poly(x_val): x_val += 1 ret += poly(x_val) return ret if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,46 @@+""" +If we are presented with the first k terms of a sequence it is impossible to say with +certainty the value of the next term, as there are infinitely many polynomial functions +that can model the sequence. + +As an example, let us consider the sequence of cube +numbers. This is defined by the generating function, +u(n) = n3: 1, 8, 27, 64, 125, 216, ... + +Suppose we were only given the first two terms of this sequence. Working on the +principle that "simple is best" we should assume a linear relationship and predict the +next term to be 15 (common difference 7). Even if we were presented with the first three +terms, by the same principle of simplicity, a quadratic relationship should be +assumed. + +We shall define OP(k, n) to be the nth term of the optimum polynomial +generating function for the first k terms of a sequence. It should be clear that +OP(k, n) will accurately generate the terms of the sequence for n ≤ k, and potentially +the first incorrect term (FIT) will be OP(k, k+1); in which case we shall call it a +bad OP (BOP). + +As a basis, if we were only given the first term of sequence, it would be most +sensible to assume constancy; that is, for n ≥ 2, OP(1, n) = u(1). + +Hence we obtain the +following OPs for the cubic sequence: + +OP(1, n) = 1 1, 1, 1, 1, ... +OP(2, n) = 7n-6 1, 8, 15, ... +OP(3, n) = 6n^2-11n+6 1, 8, 27, 58, ... +OP(4, n) = n^3 1, 8, 27, 64, 125, ... + +Clearly no BOPs exist for k ≥ 4. + +By considering the sum of FITs generated by the BOPs (indicated in red above), we +obtain 1 + 15 + 58 = 74. + +Consider the following tenth degree polynomial generating function: + +1 - n + n^2 - n^3 + n^4 - n^5 + n^6 - n^7 + n^8 - n^9 + n^10 + +Find the sum of FITs for the BOPs. +""" from __future__ import annotations @@ -7,6 +50,16 @@ def solve(matrix: Matrix, vector: Matrix) -> Matrix: + """ + Solve the linear system of equations Ax = b (A = "matrix", b = "vector") + for x using Gaussian elimination and back substitution. We assume that A + is an invertible square matrix and that b is a column vector of the + same height. + >>> solve([[1, 0], [0, 1]], [[1],[2]]) + [[1.0], [2.0]] + >>> solve([[2, 1, -1],[-3, -1, 2],[-2, 1, 2]],[[8], [-11],[-3]]) + [[2.0], [3.0], [-1.0]] + """ size: int = len(matrix) augmented: Matrix = [[0 for _ in range(size + 1)] for _ in range(size)] row: int @@ -58,6 +111,21 @@ def interpolate(y_list: list[int]) -> Callable[[int], int]: + """ + Given a list of data points (1,y0),(2,y1), ..., return a function that + interpolates the data points. We find the coefficients of the interpolating + polynomial by solving a system of linear equations corresponding to + x = 1, 2, 3... + + >>> interpolate([1])(3) + 1 + >>> interpolate([1, 8])(3) + 15 + >>> interpolate([1, 8, 27])(4) + 58 + >>> interpolate([1, 8, 27, 64])(6) + 216 + """ size: int = len(y_list) matrix: Matrix = [[0 for _ in range(size)] for _ in range(size)] @@ -75,6 +143,16 @@ coeffs = solve(matrix, vector) def interpolated_func(var: int) -> int: + """ + >>> interpolate([1])(3) + 1 + >>> interpolate([1, 8])(3) + 15 + >>> interpolate([1, 8, 27])(4) + 58 + >>> interpolate([1, 8, 27, 64])(6) + 216 + """ return sum( round(coeffs[x_val][0]) * (var ** (size - x_val - 1)) for x_val in range(size) @@ -84,6 +162,17 @@ def question_function(variable: int) -> int: + """ + The generating function u as specified in the question. + >>> question_function(0) + 1 + >>> question_function(1) + 1 + >>> question_function(5) + 8138021 + >>> question_function(10) + 9090909091 + """ return ( 1 - variable @@ -100,6 +189,13 @@ def solution(func: Callable[[int], int] = question_function, order: int = 10) -> int: + """ + Find the sum of the FITs of the BOPS. For each interpolating polynomial of order + 1, 2, ... , 10, find the first x such that the value of the polynomial at x does + not equal u(x). + >>> solution(lambda n: n ** 3, 3) + 74 + """ data_points: list[int] = [func(x_val) for x_val in range(1, order + 1)] polynomials: list[Callable[[int], int]] = [ @@ -121,4 +217,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_101/sol1.py
Help me comply with documentation standards
from __future__ import annotations def p_series(nth_term: float | str, power: float | str) -> list[str]: 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))
--- +++ @@ -1,8 +1,35 @@+""" +This is a pure Python implementation of the P-Series algorithm +https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series +For doctests run following command: +python -m doctest -v p_series.py +or +python3 -m doctest -v p_series.py +For manual testing run: +python3 p_series.py +""" 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) @@ -21,4 +48,4 @@ 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))+ print(p_series(nth_term, power))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/series/p_series.py
Create docstrings for reusable components
import numpy as np def squareplus(vector: np.ndarray, beta: float) -> np.ndarray: return (vector + np.sqrt(vector**2 + beta)) / 2 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,12 +1,38 @@+""" +Squareplus Activation Function + +Use Case: Squareplus designed to enhance positive values and suppress negative values. +For more detailed information, you can refer to the following link: +https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Squareplus +""" import numpy as np def squareplus(vector: np.ndarray, beta: float) -> np.ndarray: + """ + Implements the SquarePlus activation function. + + Parameters: + vector (np.ndarray): The input array for the SquarePlus activation. + beta (float): size of the curved region + + Returns: + np.ndarray: The input array after applying the SquarePlus activation. + + Formula: f(x) = ( x + sqrt(x^2 + b) ) / 2 + + Examples: + >>> squareplus(np.array([2.3, 0.6, -2, -3.8]), beta=2) + array([2.5 , 1.06811457, 0.22474487, 0.12731349]) + + >>> squareplus(np.array([-9.2, -0.3, 0.45, -4.56]), beta=3) + array([0.0808119 , 0.72891979, 1.11977651, 0.15893419]) + """ return (vector + np.sqrt(vector**2 + beta)) / 2 if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/activation_functions/squareplus.py
Add docstrings to my Python code
import sys N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def solution(n: str = N) -> int: largest_product = -sys.maxsize - 1 for i in range(len(n) - 12): product = 1 for j in range(13): product *= int(n[i + j]) largest_product = max(largest_product, product) return largest_product if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,35 @@+""" +Project Euler Problem 8: https://projecteuler.net/problem=8 + +Largest product in a series + +The four adjacent digits in the 1000-digit number that have the greatest +product are 9 x 9 x 8 x 9 = 5832. + + 73167176531330624919225119674426574742355349194934 + 96983520312774506326239578318016984801869478851843 + 85861560789112949495459501737958331952853208805511 + 12540698747158523863050715693290963295227443043557 + 66896648950445244523161731856403098711121722383113 + 62229893423380308135336276614282806444486645238749 + 30358907296290491560440772390713810515859307960866 + 70172427121883998797908792274921901699720888093776 + 65727333001053367881220235421809751254540594752243 + 52584907711670556013604839586446706324415722155397 + 53697817977846174064955149290862569321978468622482 + 83972241375657056057490261407972968652414535100474 + 82166370484403199890008895243450658541227588666881 + 16427171479924442928230863465674813919123162824586 + 17866458359124566529476545682848912883142607690042 + 24219022671055626321111109370544217506941658960408 + 07198403850962455444362981230987879927244284909188 + 84580156166097919133875499200524063689912560717606 + 05886116467109405077541002256983155200055935729725 + 71636269561882670428252483600823257530420752963450 + +Find the thirteen adjacent digits in the 1000-digit number that have the +greatest product. What is the value of this product? +""" import sys @@ -26,6 +58,17 @@ def solution(n: str = N) -> int: + """ + Find the thirteen adjacent digits in the 1000-digit number n that have + the greatest product and returns it. + + >>> solution("13978431290823798458352374") + 609638400 + >>> solution("13978431295823798458352374") + 2612736000 + >>> solution("1397843129582379841238352374") + 209018880 + """ largest_product = -sys.maxsize - 1 for i in range(len(n) - 12): @@ -37,4 +80,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_008/sol1.py
Document my Python code with docstrings
def get_squares(n: int) -> list[int]: return [number * number for number in range(n)] def solution(n: int = 1000) -> int: squares = get_squares(n) squares_set = set(squares) for a in range(1, n // 3): for b in range(a + 1, (n - a) // 2 + 1): if ( squares[a] + squares[b] in squares_set and squares[n - a - b] == squares[a] + squares[b] ): return a * b * (n - a - b) return -1 if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,10 +1,47 @@+""" +Project Euler Problem 9: https://projecteuler.net/problem=9 + +Special Pythagorean triplet + +A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, + + a^2 + b^2 = c^2. + +For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. + +There exists exactly one Pythagorean triplet for which a + b + c = 1000. +Find the product abc. + +References: + - https://en.wikipedia.org/wiki/Pythagorean_triple +""" def get_squares(n: int) -> list[int]: + """ + >>> get_squares(0) + [] + >>> get_squares(1) + [0] + >>> get_squares(2) + [0, 1] + >>> get_squares(3) + [0, 1, 4] + >>> get_squares(4) + [0, 1, 4, 9] + """ return [number * number for number in range(n)] def solution(n: int = 1000) -> int: + """ + Precomputing squares and checking if a^2 + b^2 is the square by set look-up. + + >>> solution(12) + 60 + >>> solution(36) + 1620 + """ squares = get_squares(n) squares_set = set(squares) @@ -20,4 +57,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_009/sol4.py
Add docstrings for better understanding
def solution(min_total: int = 10**12) -> int: prev_numerator = 1 prev_denominator = 0 numerator = 1 denominator = 1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,32 @@+""" +Project Euler Problem 100: https://projecteuler.net/problem=100 + +If a box contains twenty-one coloured discs, composed of fifteen blue discs and +six red discs, and two discs were taken at random, it can be seen that +the probability of taking two blue discs, P(BB) = (15/21) x (14/20) = 1/2. + +The next such arrangement, for which there is exactly 50% chance of taking two blue +discs at random, is a box containing eighty-five blue discs and thirty-five red discs. + +By finding the first arrangement to contain over 10^12 = 1,000,000,000,000 discs +in total, determine the number of blue discs that the box would contain. +""" def solution(min_total: int = 10**12) -> int: + """ + Returns the number of blue discs for the first arrangement to contain + over min_total discs in total + + >>> solution(2) + 3 + + >>> solution(4) + 15 + + >>> solution(21) + 85 + """ prev_numerator = 1 prev_denominator = 0 @@ -19,4 +45,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_100/sol1.py
Add docstrings for internal functions
from functools import reduce N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def solution(n: str = N) -> int: return max( # mypy cannot properly interpret reduce int(reduce(lambda x, y: str(int(x) * int(y)), n[i : i + 13])) for i in range(len(n) - 12) ) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,35 @@+""" +Project Euler Problem 8: https://projecteuler.net/problem=8 + +Largest product in a series + +The four adjacent digits in the 1000-digit number that have the greatest +product are 9 x 9 x 8 x 9 = 5832. + + 73167176531330624919225119674426574742355349194934 + 96983520312774506326239578318016984801869478851843 + 85861560789112949495459501737958331952853208805511 + 12540698747158523863050715693290963295227443043557 + 66896648950445244523161731856403098711121722383113 + 62229893423380308135336276614282806444486645238749 + 30358907296290491560440772390713810515859307960866 + 70172427121883998797908792274921901699720888093776 + 65727333001053367881220235421809751254540594752243 + 52584907711670556013604839586446706324415722155397 + 53697817977846174064955149290862569321978468622482 + 83972241375657056057490261407972968652414535100474 + 82166370484403199890008895243450658541227588666881 + 16427171479924442928230863465674813919123162824586 + 17866458359124566529476545682848912883142607690042 + 24219022671055626321111109370544217506941658960408 + 07198403850962455444362981230987879927244284909188 + 84580156166097919133875499200524063689912560717606 + 05886116467109405077541002256983155200055935729725 + 71636269561882670428252483600823257530420752963450 + +Find the thirteen adjacent digits in the 1000-digit number that have the +greatest product. What is the value of this product? +""" from functools import reduce @@ -26,6 +58,17 @@ def solution(n: str = N) -> int: + """ + Find the thirteen adjacent digits in the 1000-digit number n that have + the greatest product and returns it. + + >>> solution("13978431290823798458352374") + 609638400 + >>> solution("13978431295823798458352374") + 2612736000 + >>> solution("1397843129582379841238352374") + 209018880 + """ return max( # mypy cannot properly interpret reduce @@ -35,4 +78,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_008/sol2.py
Generate docstrings for exported functions
def solution(n: int = 100) -> int: sum_of_squares = n * (n + 1) * (2 * n + 1) / 6 square_of_sum = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,36 @@+""" +Project Euler Problem 6: https://projecteuler.net/problem=6 + +Sum square difference + +The sum of the squares of the first ten natural numbers is, + 1^2 + 2^2 + ... + 10^2 = 385 + +The square of the sum of the first ten natural numbers is, + (1 + 2 + ... + 10)^2 = 55^2 = 3025 + +Hence the difference between the sum of the squares of the first ten +natural numbers and the square of the sum is 3025 - 385 = 2640. + +Find the difference between the sum of the squares of the first one +hundred natural numbers and the square of the sum. +""" def solution(n: int = 100) -> int: + """ + Returns the difference between the sum of the squares of the first n + natural numbers and the square of the sum. + + >>> solution(10) + 2640 + >>> solution(15) + 13160 + >>> solution(20) + 41230 + >>> solution(50) + 1582700 + """ sum_of_squares = n * (n + 1) * (2 * n + 1) / 6 square_of_sum = (n * (n + 1) / 2) ** 2 @@ -8,4 +38,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_006/sol4.py
Add docstrings to improve code quality
from __future__ import annotations from pathlib import Path def vector_product(point1: tuple[int, int], point2: tuple[int, int]) -> int: return point1[0] * point2[1] - point1[1] * point2[0] def contains_origin(x1: int, y1: int, x2: int, y2: int, x3: int, y3: int) -> bool: point_a: tuple[int, int] = (x1, y1) point_a_to_b: tuple[int, int] = (x2 - x1, y2 - y1) point_a_to_c: tuple[int, int] = (x3 - x1, y3 - y1) a: float = -vector_product(point_a, point_a_to_b) / vector_product( point_a_to_c, point_a_to_b ) b: float = +vector_product(point_a, point_a_to_c) / vector_product( point_a_to_c, point_a_to_b ) return a > 0 and b > 0 and a + b < 1 def solution(filename: str = "p102_triangles.txt") -> int: data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") triangles: list[list[int]] = [] for line in data.strip().split("\n"): triangles.append([int(number) for number in line.split(",")]) ret: int = 0 triangle: list[int] for triangle in triangles: ret += contains_origin(*triangle) return ret if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,23 @@+""" +Three distinct points are plotted at random on a Cartesian plane, +for which -1000 ≤ x, y ≤ 1000, such that a triangle is formed. + +Consider the following two triangles: + +A(-340,495), B(-153,-910), C(835,-947) + +X(-175,41), Y(-421,-714), Z(574,-645) + +It can be verified that triangle ABC contains the origin, whereas +triangle XYZ does not. + +Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text +file containing the coordinates of one thousand "random" triangles, find +the number of triangles for which the interior contains the origin. + +NOTE: The first two examples in the file represent the triangles in the +example given above. +""" from __future__ import annotations @@ -5,10 +25,25 @@ def vector_product(point1: tuple[int, int], point2: tuple[int, int]) -> int: + """ + Return the 2-d vector product of two vectors. + >>> vector_product((1, 2), (-5, 0)) + 10 + >>> vector_product((3, 1), (6, 10)) + 24 + """ return point1[0] * point2[1] - point1[1] * point2[0] def contains_origin(x1: int, y1: int, x2: int, y2: int, x3: int, y3: int) -> bool: + """ + Check if the triangle given by the points A(x1, y1), B(x2, y2), C(x3, y3) + contains the origin. + >>> contains_origin(-340, 495, -153, -910, 835, -947) + True + >>> contains_origin(-175, 41, -421, -714, 574, -645) + False + """ point_a: tuple[int, int] = (x1, y1) point_a_to_b: tuple[int, int] = (x2 - x1, y2 - y1) point_a_to_c: tuple[int, int] = (x3 - x1, y3 - y1) @@ -23,6 +58,11 @@ def solution(filename: str = "p102_triangles.txt") -> int: + """ + Find the number of triangles whose interior contains the origin. + >>> solution("test_triangles.txt") + 1 + """ data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") triangles: list[list[int]] = [] @@ -39,4 +79,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_102/sol1.py
Add well-formatted docstrings
def solution(length: int = 50) -> int: different_colour_ways_number = [[0] * 3 for _ in range(length + 1)] for row_length in range(length + 1): for tile_length in range(2, 5): for tile_start in range(row_length - tile_length + 1): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length]) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,49 @@+""" +Project Euler Problem 116: https://projecteuler.net/problem=116 + +A row of five grey square tiles is to have a number of its tiles +replaced with coloured oblong tiles chosen +from red (length two), green (length three), or blue (length four). + +If red tiles are chosen there are exactly seven ways this can be done. + + |red,red|grey|grey|grey| |grey|red,red|grey|grey| + + |grey|grey|red,red|grey| |grey|grey|grey|red,red| + + |red,red|red,red|grey| |red,red|grey|red,red| + + |grey|red,red|red,red| + +If green tiles are chosen there are three ways. + + |green,green,green|grey|grey| |grey|green,green,green|grey| + + |grey|grey|green,green,green| + +And if blue tiles are chosen there are two ways. + + |blue,blue,blue,blue|grey| |grey|blue,blue,blue,blue| + +Assuming that colours cannot be mixed there are 7 + 3 + 2 = 12 ways +of replacing the grey tiles in a row measuring five units in length. + +How many different ways can the grey tiles in a row measuring fifty units in length +be replaced if colours cannot be mixed and at least one coloured tile must be used? + +NOTE: This is related to Problem 117 (https://projecteuler.net/problem=117). +""" def solution(length: int = 50) -> int: + """ + Returns the number of different ways can the grey tiles in a row + of the given length be replaced if colours cannot be mixed + and at least one coloured tile must be used + + >>> solution(5) + 12 + """ different_colour_ways_number = [[0] * 3 for _ in range(length + 1)] @@ -18,4 +61,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_116/sol1.py
Document this module using docstrings
from math import ceil def solution(n: int = 1001) -> int: total = 1 for i in range(1, ceil(n / 2.0)): odd = 2 * i + 1 even = 2 * i total = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: n = int(sys.argv[1]) print(solution(n)) except ValueError: print("Invalid entry - please enter a number")
--- +++ @@ -1,8 +1,40 @@+""" +Problem 28 +Url: https://projecteuler.net/problem=28 +Statement: +Starting with the number 1 and moving to the right in a clockwise direction a 5 +by 5 spiral is formed as follows: + + 21 22 23 24 25 + 20 7 8 9 10 + 19 6 1 2 11 + 18 5 4 3 12 + 17 16 15 14 13 + +It can be verified that the sum of the numbers on the diagonals is 101. + +What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed +in the same way? +""" from math import ceil def solution(n: int = 1001) -> int: + """Returns the sum of the numbers on the diagonals in a n by n spiral + formed in the same way. + + >>> solution(1001) + 669171001 + >>> solution(500) + 82959497 + >>> solution(100) + 651897 + >>> solution(50) + 79697 + >>> solution(10) + 537 + """ total = 1 for i in range(1, ceil(n / 2.0)): @@ -23,4 +55,4 @@ n = int(sys.argv[1]) print(solution(n)) except ValueError: - print("Invalid entry - please enter a number")+ print("Invalid entry - please enter a number")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_028/sol1.py
Add inline docstrings for readability
import numpy as np def softplus(vector: np.ndarray) -> np.ndarray: return np.log(1 + np.exp(vector)) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,12 +1,37 @@+""" +Softplus Activation Function + +Use Case: The Softplus function is a smooth approximation of the ReLU function. +For more detailed information, you can refer to the following link: +https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Softplus +""" import numpy as np def softplus(vector: np.ndarray) -> np.ndarray: + """ + Implements the Softplus activation function. + + Parameters: + vector (np.ndarray): The input array for the Softplus activation. + + Returns: + np.ndarray: The input array after applying the Softplus activation. + + Formula: f(x) = ln(1 + e^x) + + Examples: + >>> softplus(np.array([2.3, 0.6, -2, -3.8])) + array([2.39554546, 1.03748795, 0.12692801, 0.02212422]) + + >>> softplus(np.array([-9.2, -0.3, 0.45, -4.56])) + array([1.01034298e-04, 5.54355244e-01, 9.43248946e-01, 1.04077103e-02]) + """ return np.log(1 + np.exp(vector)) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/neural_network/activation_functions/softplus.py
Can you add docstrings to this Python file?
def solution(n: int = 100) -> int: collect_powers = set() current_pow = 0 n = n + 1 # maximum limit for a in range(2, n): for b in range(2, n): current_pow = a**b # calculates the current power collect_powers.add(current_pow) # adds the result to the set return len(collect_powers) if __name__ == "__main__": print("Number of terms ", solution(int(str(input()).strip())))
--- +++ @@ -1,6 +1,38 @@+""" +Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: + +2^2=4, 2^3=8, 2^4=16, 2^5=32 +3^2=9, 3^3=27, 3^4=81, 3^5=243 +4^2=16, 4^3=64, 4^4=256, 4^5=1024 +5^2=25, 5^3=125, 5^4=625, 5^5=3125 + +If they are then placed in numerical order, with any repeats removed, we get +the following sequence of 15 distinct terms: + +4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 + +How many distinct terms are in the sequence generated by ab +for 2 <= a <= 100 and 2 <= b <= 100? +""" def solution(n: int = 100) -> int: + """Returns the number of distinct terms in the sequence generated by a^b + for 2 <= a <= 100 and 2 <= b <= 100. + + >>> solution(100) + 9183 + >>> solution(50) + 2184 + >>> solution(20) + 324 + >>> solution(5) + 15 + >>> solution(2) + 1 + >>> solution(1) + 0 + """ collect_powers = set() current_pow = 0 @@ -15,4 +47,4 @@ if __name__ == "__main__": - print("Number of terms ", solution(int(str(input()).strip())))+ print("Number of terms ", solution(int(str(input()).strip())))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_029/sol1.py
Add docstrings to my Python code
from __future__ import annotations def geometric_series( nth_term: float, start_term_a: float, common_ratio_r: float, ) -> list[float]: 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))
--- +++ @@ -1,3 +1,13 @@+""" +This is a pure Python implementation of the Geometric Series algorithm +https://en.wikipedia.org/wiki/Geometric_series +Run the doctests with the following command: +python3 -m doctest -v geometric_series.py +or +python -m doctest -v geometric_series.py +For manual testing run: +python3 geometric_series.py +""" from __future__ import annotations @@ -7,6 +17,34 @@ 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] = [] @@ -33,4 +71,4 @@ 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))+ print(geometric_series(nth_term, start_term_a, common_ratio_r))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/maths/series/geometric_series.py
Add concise docstrings to each method
import os # Precomputes a list of the 100 first triangular numbers TRIANGULAR_NUMBERS = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def solution(): script_dir = os.path.dirname(os.path.realpath(__file__)) words_file_path = os.path.join(script_dir, "words.txt") words = "" with open(words_file_path) as f: words = f.readline() words = [word.strip('"') for word in words.strip("\r\n").split(",")] words = [ word for word in [sum(ord(x) - 64 for x in word) for word in words] if word in TRIANGULAR_NUMBERS ] return len(words) if __name__ == "__main__": print(solution())
--- +++ @@ -1,3 +1,18 @@+""" +The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so +the first ten triangle numbers are: + +1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... + +By converting each letter in a word to a number corresponding to its +alphabetical position and adding these values we form a word value. For example, +the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a +triangle number then we shall call the word a triangle word. + +Using words.txt (right click and 'Save Link/Target As...'), a 16K text file +containing nearly two-thousand common English words, how many are triangle +words? +""" import os @@ -6,6 +21,12 @@ def solution(): + """ + Finds the amount of triangular words in the words file. + + >>> solution() + 162 + """ script_dir = os.path.dirname(os.path.realpath(__file__)) words_file_path = os.path.join(script_dir, "words.txt") @@ -23,4 +44,4 @@ if __name__ == "__main__": - print(solution())+ print(solution())
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_042/solution42.py
Create documentation strings for testing functions
from __future__ import annotations import os from collections.abc import Mapping EdgeT = tuple[int, int] class Graph: def __init__(self, vertices: set[int], edges: Mapping[EdgeT, int]) -> None: self.vertices: set[int] = vertices self.edges: dict[EdgeT, int] = { (min(edge), max(edge)): weight for edge, weight in edges.items() } def add_edge(self, edge: EdgeT, weight: int) -> None: self.vertices.add(edge[0]) self.vertices.add(edge[1]) self.edges[(min(edge), max(edge))] = weight def prims_algorithm(self) -> Graph: subgraph: Graph = Graph({min(self.vertices)}, {}) min_edge: EdgeT min_weight: int edge: EdgeT weight: int while len(subgraph.vertices) < len(self.vertices): min_weight = max(self.edges.values()) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ ( edge[1] in subgraph.vertices ) and weight < min_weight: min_edge = edge min_weight = weight subgraph.add_edge(min_edge, min_weight) return subgraph def solution(filename: str = "p107_network.txt") -> int: script_dir: str = os.path.abspath(os.path.dirname(__file__)) network_file: str = os.path.join(script_dir, filename) edges: dict[EdgeT, int] = {} data: list[str] edge1: int edge2: int with open(network_file) as f: data = f.read().strip().split("\n") adjaceny_matrix = [line.split(",") for line in data] for edge1 in range(1, len(adjaceny_matrix)): for edge2 in range(edge1): if adjaceny_matrix[edge1][edge2] != "-": edges[(edge2, edge1)] = int(adjaceny_matrix[edge1][edge2]) graph: Graph = Graph(set(range(len(adjaceny_matrix))), edges) subgraph: Graph = graph.prims_algorithm() initial_total: int = sum(graph.edges.values()) optimal_total: int = sum(subgraph.edges.values()) return initial_total - optimal_total if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,32 @@+""" +The following undirected network consists of seven vertices and twelve edges +with a total weight of 243. + +The same network can be represented by the matrix below. + + A B C D E F G +A - 16 12 21 - - - +B 16 - - 17 20 - - +C 12 - - 28 - 31 - +D 21 17 28 - 18 19 23 +E - 20 - 18 - - 11 +F - - 31 19 - - 27 +G - - - 23 11 27 - + +However, it is possible to optimise the network by removing some edges and still +ensure that all points on the network remain connected. The network which achieves +the maximum saving is shown below. It has a weight of 93, representing a saving of +243 - 93 = 150 from the original network. + +Using network.txt (right click and 'Save Link/Target As...'), a 6K text file +containing a network with forty vertices, and given in matrix form, find the maximum +saving which can be achieved by removing redundant edges whilst ensuring that the +network remains connected. + +Solution: + We use Prim's algorithm to find a Minimum Spanning Tree. + Reference: https://en.wikipedia.org/wiki/Prim%27s_algorithm +""" from __future__ import annotations @@ -8,6 +37,9 @@ class Graph: + """ + A class representing an undirected weighted graph. + """ def __init__(self, vertices: set[int], edges: Mapping[EdgeT, int]) -> None: self.vertices: set[int] = vertices @@ -16,11 +48,30 @@ } def add_edge(self, edge: EdgeT, weight: int) -> None: + """ + Add a new edge to the graph. + >>> graph = Graph({1, 2}, {(2, 1): 4}) + >>> graph.add_edge((3, 1), 5) + >>> sorted(graph.vertices) + [1, 2, 3] + >>> sorted([(v,k) for k,v in graph.edges.items()]) + [(4, (1, 2)), (5, (1, 3))] + """ self.vertices.add(edge[0]) self.vertices.add(edge[1]) self.edges[(min(edge), max(edge))] = weight def prims_algorithm(self) -> Graph: + """ + Run Prim's algorithm to find the minimum spanning tree. + Reference: https://en.wikipedia.org/wiki/Prim%27s_algorithm + >>> graph = Graph({1,2,3,4},{(1,2):5, (1,3):10, (1,4):20, (2,4):30, (3,4):1}) + >>> mst = graph.prims_algorithm() + >>> sorted(mst.vertices) + [1, 2, 3, 4] + >>> sorted(mst.edges) + [(1, 2), (1, 3), (3, 4)] + """ subgraph: Graph = Graph({min(self.vertices)}, {}) min_edge: EdgeT min_weight: int @@ -42,6 +93,12 @@ def solution(filename: str = "p107_network.txt") -> int: + """ + Find the maximum saving which can be achieved by removing redundant edges + whilst ensuring that the network remains connected. + >>> solution("test_network.txt") + 150 + """ script_dir: str = os.path.abspath(os.path.dirname(__file__)) network_file: str = os.path.join(script_dir, filename) edges: dict[EdgeT, int] = {} @@ -70,4 +127,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_107/sol1.py
Create docstrings for API functions
def check_bouncy(n: int) -> bool: if not isinstance(n, int): raise ValueError("check_bouncy() accepts only integer arguments") str_n = str(n) sorted_str_n = "".join(sorted(str_n)) return str_n not in {sorted_str_n, sorted_str_n[::-1]} def solution(percent: float = 99) -> int: if not 0 < percent < 100: raise ValueError("solution() only accepts values from 0 to 100") bouncy_num = 0 num = 1 while True: if check_bouncy(num): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(f"{solution(99)}")
--- +++ @@ -1,29 +1,91 @@- - -def check_bouncy(n: int) -> bool: - if not isinstance(n, int): - raise ValueError("check_bouncy() accepts only integer arguments") - str_n = str(n) - sorted_str_n = "".join(sorted(str_n)) - return str_n not in {sorted_str_n, sorted_str_n[::-1]} - - -def solution(percent: float = 99) -> int: - if not 0 < percent < 100: - raise ValueError("solution() only accepts values from 0 to 100") - bouncy_num = 0 - num = 1 - - while True: - if check_bouncy(num): - bouncy_num += 1 - if (bouncy_num / num) * 100 >= percent: - return num - num += 1 - - -if __name__ == "__main__": - from doctest import testmod - - testmod() - print(f"{solution(99)}")+""" +Problem 112: https://projecteuler.net/problem=112 + +Working from left-to-right if no digit is exceeded by the digit to its left it is +called an increasing number; for example, 134468. +Similarly if no digit is exceeded by the digit to its right it is called a decreasing +number; for example, 66420. +We shall call a positive integer that is neither increasing nor decreasing a "bouncy" +number, for example, 155349. +Clearly there cannot be any bouncy numbers below one-hundred, but just over half of +the numbers below one-thousand (525) are bouncy. In fact, the least number for which +the proportion of bouncy numbers first reaches 50% is 538. +Surprisingly, bouncy numbers become more and more common and by the time we reach +21780 the proportion of bouncy numbers is equal to 90%. + +Find the least number for which the proportion of bouncy numbers is exactly 99%. +""" + + +def check_bouncy(n: int) -> bool: + """ + Returns True if number is bouncy, False otherwise + >>> check_bouncy(6789) + False + >>> check_bouncy(-12345) + False + >>> check_bouncy(0) + False + >>> check_bouncy(6.74) + Traceback (most recent call last): + ... + ValueError: check_bouncy() accepts only integer arguments + >>> check_bouncy(132475) + True + >>> check_bouncy(34) + False + >>> check_bouncy(341) + True + >>> check_bouncy(47) + False + >>> check_bouncy(-12.54) + Traceback (most recent call last): + ... + ValueError: check_bouncy() accepts only integer arguments + >>> check_bouncy(-6548) + True + """ + if not isinstance(n, int): + raise ValueError("check_bouncy() accepts only integer arguments") + str_n = str(n) + sorted_str_n = "".join(sorted(str_n)) + return str_n not in {sorted_str_n, sorted_str_n[::-1]} + + +def solution(percent: float = 99) -> int: + """ + Returns the least number for which the proportion of bouncy numbers is + exactly 'percent' + >>> solution(50) + 538 + >>> solution(90) + 21780 + >>> solution(80) + 4770 + >>> solution(105) + Traceback (most recent call last): + ... + ValueError: solution() only accepts values from 0 to 100 + >>> solution(100.011) + Traceback (most recent call last): + ... + ValueError: solution() only accepts values from 0 to 100 + """ + if not 0 < percent < 100: + raise ValueError("solution() only accepts values from 0 to 100") + bouncy_num = 0 + num = 1 + + while True: + if check_bouncy(num): + bouncy_num += 1 + if (bouncy_num / num) * 100 >= percent: + return num + num += 1 + + +if __name__ == "__main__": + from doctest import testmod + + testmod() + print(f"{solution(99)}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_112/sol1.py
Auto-generate documentation strings for this file
from itertools import combinations_with_replacement def solution(limit: int = 100) -> int: singles: list[int] = [*list(range(1, 21)), 25] doubles: list[int] = [2 * x for x in range(1, 21)] + [50] triples: list[int] = [3 * x for x in range(1, 21)] all_values: list[int] = singles + doubles + triples + [0] num_checkouts: int = 0 double: int throw1: int throw2: int checkout_total: int for double in doubles: for throw1, throw2 in combinations_with_replacement(all_values, 2): checkout_total = double + throw1 + throw2 if checkout_total < limit: num_checkouts += 1 return num_checkouts if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,70 @@+""" +In the game of darts a player throws three darts at a target board which is +split into twenty equal sized sections numbered one to twenty. + +The score of a dart is determined by the number of the region that the dart +lands in. A dart landing outside the red/green outer ring scores zero. The black +and cream regions inside this ring represent single scores. However, the red/green +outer ring and middle ring score double and treble scores respectively. + +At the centre of the board are two concentric circles called the bull region, or +bulls-eye. The outer bull is worth 25 points and the inner bull is a double, +worth 50 points. + +There are many variations of rules but in the most popular game the players will +begin with a score 301 or 501 and the first player to reduce their running total +to zero is a winner. However, it is normal to play a "doubles out" system, which +means that the player must land a double (including the double bulls-eye at the +centre of the board) on their final dart to win; any other dart that would reduce +their running total to one or lower means the score for that set of three darts +is "bust". + +When a player is able to finish on their current score it is called a "checkout" +and the highest checkout is 170: T20 T20 D25 (two treble 20s and double bull). + +There are exactly eleven distinct ways to checkout on a score of 6: + +D3 +D1 D2 +S2 D2 +D2 D1 +S4 D1 +S1 S1 D2 +S1 T1 D1 +S1 S3 D1 +D1 D1 D1 +D1 S2 D1 +S2 S2 D1 + +Note that D1 D2 is considered different to D2 D1 as they finish on different +doubles. However, the combination S1 T1 D1 is considered the same as T1 S1 D1. + +In addition we shall not include misses in considering combinations; for example, +D3 is the same as 0 D3 and 0 0 D3. + +Incredibly there are 42336 distinct ways of checking out in total. + +How many distinct ways can a player checkout with a score less than 100? + +Solution: + We first construct a list of the possible dart values, separated by type. + We then iterate through the doubles, followed by the possible 2 following throws. + If the total of these three darts is less than the given limit, we increment + the counter. +""" from itertools import combinations_with_replacement def solution(limit: int = 100) -> int: + """ + Count the number of distinct ways a player can checkout with a score + less than limit. + >>> solution(171) + 42336 + >>> solution(50) + 12577 + """ singles: list[int] = [*list(range(1, 21)), 25] doubles: list[int] = [2 * x for x in range(1, 21)] + [50] triples: list[int] = [3 * x for x in range(1, 21)] @@ -24,4 +86,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_109/sol1.py
Add verbose docstrings with examples
def solution(length: int = 50) -> int: ways_number = [1] * (length + 1) for row_length in range(3, length + 1): for block_length in range(3, row_length + 1): for block_start in range(row_length - block_length): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,44 @@+""" +Project Euler Problem 114: https://projecteuler.net/problem=114 + +A row measuring seven units in length has red blocks with a minimum length +of three units placed on it, such that any two red blocks +(which are allowed to be different lengths) are separated by at least one grey square. +There are exactly seventeen ways of doing this. + + |g|g|g|g|g|g|g| |r,r,r|g|g|g|g| + + |g|r,r,r|g|g|g| |g|g|r,r,r|g|g| + + |g|g|g|r,r,r|g| |g|g|g|g|r,r,r| + + |r,r,r|g|r,r,r| |r,r,r,r|g|g|g| + + |g|r,r,r,r|g|g| |g|g|r,r,r,r|g| + + |g|g|g|r,r,r,r| |r,r,r,r,r|g|g| + + |g|r,r,r,r,r|g| |g|g|r,r,r,r,r| + + |r,r,r,r,r,r|g| |g|r,r,r,r,r,r| + + |r,r,r,r,r,r,r| + +How many ways can a row measuring fifty units in length be filled? + +NOTE: Although the example above does not lend itself to the possibility, +in general it is permitted to mix block sizes. For example, +on a row measuring eight units in length you could use red (3), grey (1), and red (4). +""" def solution(length: int = 50) -> int: + """ + Returns the number of ways a row of the given length can be filled + + >>> solution(7) + 17 + """ ways_number = [1] * (length + 1) @@ -17,4 +55,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_114/sol1.py
Generate docstrings for this script
def choose(n: int, r: int) -> int: ret = 1.0 for i in range(1, r + 1): ret *= (n + 1 - i) / i return round(ret) def non_bouncy_exact(n: int) -> int: return choose(8 + n, n) + choose(9 + n, n) - 10 def non_bouncy_upto(n: int) -> int: return sum(non_bouncy_exact(i) for i in range(1, n + 1)) def solution(num_digits: int = 100) -> int: return non_bouncy_upto(num_digits) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,33 @@+""" +Project Euler Problem 113: https://projecteuler.net/problem=113 + +Working from left-to-right if no digit is exceeded by the digit to its left it is +called an increasing number; for example, 134468. + +Similarly if no digit is exceeded by the digit to its right it is called a decreasing +number; for example, 66420. + +We shall call a positive integer that is neither increasing nor decreasing a +"bouncy" number; for example, 155349. + +As n increases, the proportion of bouncy numbers below n increases such that there +are only 12951 numbers below one-million that are not bouncy and only 277032 +non-bouncy numbers below 10^10. + +How many numbers below a googol (10^100) are not bouncy? +""" def choose(n: int, r: int) -> int: + """ + Calculate the binomial coefficient c(n,r) using the multiplicative formula. + >>> choose(4,2) + 6 + >>> choose(5,3) + 10 + >>> choose(20,6) + 38760 + """ ret = 1.0 for i in range(1, r + 1): ret *= (n + 1 - i) / i @@ -8,16 +35,41 @@ def non_bouncy_exact(n: int) -> int: + """ + Calculate the number of non-bouncy numbers with at most n digits. + >>> non_bouncy_exact(1) + 9 + >>> non_bouncy_exact(6) + 7998 + >>> non_bouncy_exact(10) + 136126 + """ return choose(8 + n, n) + choose(9 + n, n) - 10 def non_bouncy_upto(n: int) -> int: + """ + Calculate the number of non-bouncy numbers with at most n digits. + >>> non_bouncy_upto(1) + 9 + >>> non_bouncy_upto(6) + 12951 + >>> non_bouncy_upto(10) + 277032 + """ return sum(non_bouncy_exact(i) for i in range(1, n + 1)) def solution(num_digits: int = 100) -> int: + """ + Calculate the number of non-bouncy numbers less than a googol. + >>> solution(6) + 12951 + >>> solution(10) + 277032 + """ return non_bouncy_upto(num_digits) if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_113/sol1.py
Add docstrings to meet PEP guidelines
def solution(n: int = 1000) -> int: return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 1)) if __name__ == "__main__": print(solution())
--- +++ @@ -1,8 +1,32 @@+""" +Problem 120 Square remainders: https://projecteuler.net/problem=120 + +Description: + +Let r be the remainder when (a-1)^n + (a+1)^n is divided by a^2. +For example, if a = 7 and n = 3, then r = 42: 6^3 + 8^3 = 728 ≡ 42 mod 49. +And as n varies, so too will r, but for a = 7 it turns out that r_max = 42. +For 3 ≤ a ≤ 1000, find ∑ r_max. + +Solution: + +On expanding the terms, we get 2 if n is even and 2an if n is odd. +For maximizing the value, 2an < a*a => n <= (a - 1)/2 (integer division) +""" def solution(n: int = 1000) -> int: + """ + Returns ∑ r_max for 3 <= a <= n as explained above + >>> solution(10) + 300 + >>> solution(100) + 330750 + >>> solution(1000) + 333082500 + """ return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 1)) if __name__ == "__main__": - print(solution())+ print(solution())
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_120/sol1.py
Create docstrings for each class method
import math def digit_sum(n: int) -> int: return sum(int(digit) for digit in str(n)) def solution(n: int = 30) -> int: digit_to_powers = [] for digit in range(2, 100): for power in range(2, 100): number = int(math.pow(digit, power)) if digit == digit_sum(number): digit_to_powers.append(number) digit_to_powers.sort() return digit_to_powers[n - 1] if __name__ == "__main__": print(solution())
--- +++ @@ -1,12 +1,41 @@+""" +Problem 119: https://projecteuler.net/problem=119 + +Name: Digit power sum + +The number 512 is interesting because it is equal to the sum of its digits +raised to some power: 5 + 1 + 2 = 8, and 8^3 = 512. Another example of a number +with this property is 614656 = 28^4. We shall define an to be the nth term of +this sequence and insist that a number must contain at least two digits to have a sum. +You are given that a2 = 512 and a10 = 614656. Find a30 +""" import math def digit_sum(n: int) -> int: + """ + Returns the sum of the digits of the number. + >>> digit_sum(123) + 6 + >>> digit_sum(456) + 15 + >>> digit_sum(78910) + 25 + """ return sum(int(digit) for digit in str(n)) def solution(n: int = 30) -> int: + """ + Returns the value of 30th digit power sum. + >>> solution(2) + 512 + >>> solution(5) + 5832 + >>> solution(10) + 614656 + """ digit_to_powers = [] for digit in range(2, 100): for power in range(2, 100): @@ -19,4 +48,4 @@ if __name__ == "__main__": - print(solution())+ print(solution())
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_119/sol1.py
Write docstrings for data processing functions
def solution(length: int = 50) -> int: ways_number = [1] * (length + 1) for row_length in range(length + 1): for tile_length in range(2, 5): for tile_start in range(row_length - tile_length + 1): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,41 @@+""" +Project Euler Problem 117: https://projecteuler.net/problem=117 + +Using a combination of grey square tiles and oblong tiles chosen from: +red tiles (measuring two units), green tiles (measuring three units), +and blue tiles (measuring four units), +it is possible to tile a row measuring five units in length +in exactly fifteen different ways. + + |grey|grey|grey|grey|grey| |red,red|grey|grey|grey| + + |grey|red,red|grey|grey| |grey|grey|red,red|grey| + + |grey|grey|grey|red,red| |red,red|red,red|grey| + + |red,red|grey|red,red| |grey|red,red|red,red| + + |green,green,green|grey|grey| |grey|green,green,green|grey| + + |grey|grey|green,green,green| |red,red|green,green,green| + + |green,green,green|red,red| |blue,blue,blue,blue|grey| + + |grey|blue,blue,blue,blue| + +How many ways can a row measuring fifty units in length be tiled? + +NOTE: This is related to Problem 116 (https://projecteuler.net/problem=116). +""" def solution(length: int = 50) -> int: + """ + Returns the number of ways can a row of the given length be tiled + + >>> solution(5) + 15 + """ ways_number = [1] * (length + 1) @@ -15,4 +50,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_117/sol1.py
Add structured docstrings to improve clarity
from itertools import count def solution(min_block_length: int = 50) -> int: fill_count_functions = [1] * min_block_length for n in count(min_block_length): fill_count_functions.append(1) for block_length in range(min_block_length, n + 1): for block_start in range(n - block_length): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_000_000: break return n if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,43 @@+""" +Project Euler Problem 115: https://projecteuler.net/problem=115 + +NOTE: This is a more difficult version of Problem 114 +(https://projecteuler.net/problem=114). + +A row measuring n units in length has red blocks +with a minimum length of m units placed on it, such that any two red blocks +(which are allowed to be different lengths) are separated by at least one black square. + +Let the fill-count function, F(m, n), +represent the number of ways that a row can be filled. + +For example, F(3, 29) = 673135 and F(3, 30) = 1089155. + +That is, for m = 3, it can be seen that n = 30 is the smallest value +for which the fill-count function first exceeds one million. + +In the same way, for m = 10, it can be verified that +F(10, 56) = 880711 and F(10, 57) = 1148904, so n = 57 is the least value +for which the fill-count function first exceeds one million. + +For m = 50, find the least value of n +for which the fill-count function first exceeds one million. +""" from itertools import count def solution(min_block_length: int = 50) -> int: + """ + Returns for given minimum block length the least value of n + for which the fill-count function first exceeds one million + + >>> solution(3) + 30 + + >>> solution(10) + 57 + """ fill_count_functions = [1] * min_block_length @@ -24,4 +59,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_115/sol1.py
Add docstrings to improve collaboration
LIMIT = 10**8 def is_palindrome(n: int) -> bool: if n % 10 == 0: return False s = str(n) return s == s[::-1] def solution() -> int: answer = set() first_square = 1 sum_squares = 5 while sum_squares < LIMIT: last_square = first_square + 1 while sum_squares < LIMIT: if is_palindrome(sum_squares): answer.add(sum_squares) last_square += 1 sum_squares += last_square**2 first_square += 1 sum_squares = first_square**2 + (first_square + 1) ** 2 return sum(answer) if __name__ == "__main__": print(solution())
--- +++ @@ -1,8 +1,31 @@+""" +Problem 125: https://projecteuler.net/problem=125 + +The palindromic number 595 is interesting because it can be written as the sum +of consecutive squares: 6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2. + +There are exactly eleven palindromes below one-thousand that can be written as +consecutive square sums, and the sum of these palindromes is 4164. Note that +1 = 0^2 + 1^2 has not been included as this problem is concerned with the +squares of positive integers. + +Find the sum of all the numbers less than 10^8 that are both palindromic and can +be written as the sum of consecutive squares. +""" LIMIT = 10**8 def is_palindrome(n: int) -> bool: + """ + Check if an integer is palindromic. + >>> is_palindrome(12521) + True + >>> is_palindrome(12522) + False + >>> is_palindrome(12210) + False + """ if n % 10 == 0: return False s = str(n) @@ -10,6 +33,10 @@ def solution() -> int: + """ + Returns the sum of all numbers less than 1e8 that are both palindromic and + can be written as the sum of consecutive squares. + """ answer = set() first_square = 1 sum_squares = 5 @@ -27,4 +54,4 @@ if __name__ == "__main__": - print(solution())+ print(solution())
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_125/sol1.py
Provide docstrings following PEP 257
def solve(nums: list[int], goal: int, depth: int) -> bool: if len(nums) > depth: return False for el in nums: if el + nums[-1] == goal: return True nums.append(el + nums[-1]) if solve(nums=nums, goal=goal, depth=depth): return True del nums[-1] return False def solution(n: int = 200) -> int: total = 0 for i in range(2, n + 1): max_length = 0 while True: nums = [1] max_length += 1 if solve(nums=nums, goal=i, depth=max_length): break total += max_length return total if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,52 @@+""" +Project Euler Problem 122: https://projecteuler.net/problem=122 + +Efficient Exponentiation + +The most naive way of computing n^15 requires fourteen multiplications: + + n x n x ... x n = n^15. + +But using a "binary" method you can compute it in six multiplications: + + n x n = n^2 + n^2 x n^2 = n^4 + n^4 x n^4 = n^8 + n^8 x n^4 = n^12 + n^12 x n^2 = n^14 + n^14 x n = n^15 + +However it is yet possible to compute it in only five multiplications: + + n x n = n^2 + n^2 x n = n^3 + n^3 x n^3 = n^6 + n^6 x n^6 = n^12 + n^12 x n^3 = n^15 + +We shall define m(k) to be the minimum number of multiplications to compute n^k; +for example m(15) = 5. + +Find sum_{k = 1}^200 m(k). + +It uses the fact that for rather small n, applicable for this problem, the solution +for each number can be formed by increasing the largest element. + +References: +- https://en.wikipedia.org/wiki/Addition_chain +""" def solve(nums: list[int], goal: int, depth: int) -> bool: + """ + Checks if nums can have a sum equal to goal, given that length of nums does + not exceed depth. + + >>> solve([1], 2, 2) + True + >>> solve([1], 2, 0) + False + """ if len(nums) > depth: return False for el in nums: @@ -14,6 +60,19 @@ def solution(n: int = 200) -> int: + """ + Calculates sum of smallest number of multiplactions for each number up to + and including n. + + >>> solution(1) + 0 + >>> solution(2) + 1 + >>> solution(14) + 45 + >>> solution(15) + 50 + """ total = 0 for i in range(2, n + 1): max_length = 0 @@ -27,4 +86,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_122/sol1.py
Generate missing documentation strings
from itertools import product def solution(num_turns: int = 15) -> int: total_prob: float = 0.0 prob: float num_blue: int num_red: int ind: int col: int series: tuple[int, ...] for series in product(range(2), repeat=num_turns): num_blue = series.count(1) num_red = num_turns - num_blue if num_red >= num_blue: continue prob = 1.0 for ind, col in enumerate(series, 2): if col == 0: prob *= (ind - 1) / ind else: prob *= 1 / ind total_prob += prob return int(1 / total_prob) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,40 @@+""" +A bag contains one red disc and one blue disc. In a game of chance a player takes a +disc at random and its colour is noted. After each turn the disc is returned to the +bag, an extra red disc is added, and another disc is taken at random. + +The player pays £1 to play and wins if they have taken more blue discs than red +discs at the end of the game. + +If the game is played for four turns, the probability of a player winning is exactly +11/120, and so the maximum prize fund the banker should allocate for winning in this +game would be £10 before they would expect to incur a loss. Note that any payout will +be a whole number of pounds and also includes the original £1 paid to play the game, +so in the example given the player actually wins £9. + +Find the maximum prize fund that should be allocated to a single game in which +fifteen turns are played. + + +Solution: + For each 15-disc sequence of red and blue for which there are more red than blue, + we calculate the probability of that sequence and add it to the total probability + of the player winning. The inverse of this probability gives an upper bound for + the prize if the banker wants to avoid an expected loss. +""" from itertools import product def solution(num_turns: int = 15) -> int: + """ + Find the maximum prize fund that should be allocated to a single game in which + fifteen turns are played. + >>> solution(4) + 10 + >>> solution(10) + 225 + """ total_prob: float = 0.0 prob: float num_blue: int @@ -29,4 +61,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_121/sol1.py
Document this code for team use
from math import isclose, sqrt def next_point( point_x: float, point_y: float, incoming_gradient: float ) -> tuple[float, float, float]: # normal_gradient = gradient of line through which the beam is reflected # outgoing_gradient = gradient of reflected line normal_gradient = point_y / 4 / point_x s2 = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) c2 = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) outgoing_gradient = (s2 - c2 * incoming_gradient) / (c2 + s2 * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 quadratic_term = outgoing_gradient**2 + 4 linear_term = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) constant_term = (point_y - outgoing_gradient * point_x) ** 2 - 100 x_minus = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) x_plus = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) # two solutions, one of which is our input point next_x = x_minus if isclose(x_plus, point_x) else x_plus next_y = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def solution(first_x_coord: float = 1.4, first_y_coord: float = -9.6) -> int: num_reflections: int = 0 point_x: float = first_x_coord point_y: float = first_y_coord gradient: float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): point_x, point_y, gradient = next_point(point_x, point_y, gradient) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,33 @@+""" +In laser physics, a "white cell" is a mirror system that acts as a delay line for the +laser beam. The beam enters the cell, bounces around on the mirrors, and eventually +works its way back out. + +The specific white cell we will be considering is an ellipse with the equation +4x^2 + y^2 = 100 + +The section corresponding to -0.01 ≤ x ≤ +0.01 at the top is missing, allowing the +light to enter and exit through the hole. + +The light beam in this problem starts at the point (0.0,10.1) just outside the white +cell, and the beam first impacts the mirror at (1.4,-9.6). + +Each time the laser beam hits the surface of the ellipse, it follows the usual law of +reflection "angle of incidence equals angle of reflection." That is, both the incident +and reflected beams make the same angle with the normal line at the point of incidence. + +In the figure on the left, the red line shows the first two points of contact between +the laser beam and the wall of the white cell; the blue line shows the line tangent to +the ellipse at the point of incidence of the first bounce. + +The slope m of the tangent line at any point (x,y) of the given ellipse is: m = -4x/y + +The normal line is perpendicular to this tangent line at the point of incidence. + +The animation on the right shows the first 10 reflections of the beam. + +How many times does the beam hit the internal surface of the white cell before exiting? +""" from math import isclose, sqrt @@ -5,6 +35,15 @@ def next_point( point_x: float, point_y: float, incoming_gradient: float ) -> tuple[float, float, float]: + """ + Given that a laser beam hits the interior of the white cell at point + (point_x, point_y) with gradient incoming_gradient, return a tuple (x,y,m1) + where the next point of contact with the interior is (x,y) with gradient m1. + >>> next_point(5.0, 0.0, 0.0) + (-5.0, 0.0, 0.0) + >>> next_point(5.0, 0.0, -2.0) + (0.0, -10.0, 2.0) + """ # normal_gradient = gradient of line through which the beam is reflected # outgoing_gradient = gradient of reflected line normal_gradient = point_y / 4 / point_x @@ -37,6 +76,14 @@ def solution(first_x_coord: float = 1.4, first_y_coord: float = -9.6) -> int: + """ + Return the number of times that the beam hits the interior wall of the + cell before exiting. + >>> solution(0.00001,-10) + 1 + >>> solution(5, 0) + 287 + """ num_reflections: int = 0 point_x: float = first_x_coord point_y: float = first_y_coord @@ -50,4 +97,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_144/sol1.py
Add inline docstrings for readability
from __future__ import annotations from collections.abc import Generator def sieve() -> Generator[int]: factor_map: dict[int, int] = {} prime = 2 while True: factor = factor_map.pop(prime, None) if factor: x = factor + prime while x in factor_map: x += factor factor_map[x] = factor else: factor_map[prime * prime] = prime yield prime prime += 1 def solution(limit: float = 1e10) -> int: primes = sieve() n = 1 while True: prime = next(primes) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(primes) n += 2 if __name__ == "__main__": print(solution())
--- +++ @@ -1,3 +1,42 @@+""" +Problem 123: https://projecteuler.net/problem=123 + +Name: Prime square remainders + +Let pn be the nth prime: 2, 3, 5, 7, 11, ..., and +let r be the remainder when (pn-1)^n + (pn+1)^n is divided by pn^2. + +For example, when n = 3, p3 = 5, and 43 + 63 = 280 ≡ 5 mod 25. +The least value of n for which the remainder first exceeds 10^9 is 7037. + +Find the least value of n for which the remainder first exceeds 10^10. + + +Solution: + +n=1: (p-1) + (p+1) = 2p +n=2: (p-1)^2 + (p+1)^2 + = p^2 + 1 - 2p + p^2 + 1 + 2p (Using (p+b)^2 = (p^2 + b^2 + 2pb), + (p-b)^2 = (p^2 + b^2 - 2pb) and b = 1) + = 2p^2 + 2 +n=3: (p-1)^3 + (p+1)^3 (Similarly using (p+b)^3 & (p-b)^3 formula and so on) + = 2p^3 + 6p +n=4: 2p^4 + 12p^2 + 2 +n=5: 2p^5 + 20p^3 + 10p + +As you could see, when the expression is divided by p^2. +Except for the last term, the rest will result in the remainder 0. + +n=1: 2p +n=2: 2 +n=3: 6p +n=4: 2 +n=5: 10p + +So it could be simplified as, + r = 2pn when n is odd + r = 2 when n is even. +""" from __future__ import annotations @@ -5,6 +44,24 @@ def sieve() -> Generator[int]: + """ + Returns a prime number generator using sieve method. + >>> type(sieve()) + <class 'generator'> + >>> primes = sieve() + >>> next(primes) + 2 + >>> next(primes) + 3 + >>> next(primes) + 5 + >>> next(primes) + 7 + >>> next(primes) + 11 + >>> next(primes) + 13 + """ factor_map: dict[int, int] = {} prime = 2 while True: @@ -21,6 +78,13 @@ def solution(limit: float = 1e10) -> int: + """ + Returns the least value of n for which the remainder first exceeds 10^10. + >>> solution(1e8) + 2371 + >>> solution(1e9) + 7037 + """ primes = sieve() n = 1 @@ -34,4 +98,4 @@ if __name__ == "__main__": - print(solution())+ print(solution())
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_123/sol1.py
Write proper docstrings for these functions
from math import isqrt def is_prime(number: int) -> bool: return all(number % divisor != 0 for divisor in range(2, isqrt(number) + 1)) def solution(max_prime: int = 10**6) -> int: primes_count = 0 cube_index = 1 prime_candidate = 7 while prime_candidate < max_prime: primes_count += is_prime(prime_candidate) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,13 +1,41 @@+""" +Project Euler Problem 131: https://projecteuler.net/problem=131 + +There are some prime values, p, for which there exists a positive integer, n, +such that the expression n^3 + n^2p is a perfect cube. + +For example, when p = 19, 8^3 + 8^2 x 19 = 12^3. + +What is perhaps most surprising is that for each prime with this property +the value of n is unique, and there are only four such primes below one-hundred. + +How many primes below one million have this remarkable property? +""" from math import isqrt def is_prime(number: int) -> bool: + """ + Determines whether number is prime + + >>> is_prime(3) + True + + >>> is_prime(4) + False + """ return all(number % divisor != 0 for divisor in range(2, isqrt(number) + 1)) def solution(max_prime: int = 10**6) -> int: + """ + Returns number of primes below max_prime with the property + + >>> solution(100) + 4 + """ primes_count = 0 cube_index = 1 @@ -22,4 +50,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_131/sol1.py
Add docstrings to incomplete code
def solution(limit: int = 1000000) -> int: limit = limit + 1 frequency = [0] * limit for first_term in range(1, limit): for n in range(first_term, limit, first_term): common_difference = first_term + n / first_term if common_difference % 4: # d must be divisible by 4 continue else: common_difference /= 4 if ( first_term > common_difference and first_term < 4 * common_difference ): # since x, y, z are positive integers frequency[n] += 1 # so z > 0, a > d and 4d < a count = sum(1 for x in frequency[1:limit] if x == 10) return count if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,36 @@+""" +Project Euler Problem 135: https://projecteuler.net/problem=135 + +Given the positive integers, x, y, and z, are consecutive terms of an arithmetic +progression, the least value of the positive integer, n, for which the equation, +x2 - y2 - z2 = n, has exactly two solutions is n = 27: + +342 - 272 - 202 = 122 - 92 - 62 = 27 + +It turns out that n = 1155 is the least value which has exactly ten solutions. + +How many values of n less than one million have exactly ten distinct solutions? + + +Taking x, y, z of the form a + d, a, a - d respectively, the given equation reduces to +a * (4d - a) = n. +Calculating no of solutions for every n till 1 million by fixing a, and n must be a +multiple of a. Total no of steps = n * (1/1 + 1/2 + 1/3 + 1/4 + ... + 1/n), so roughly +O(nlogn) time complexity. +""" def solution(limit: int = 1000000) -> int: + """ + returns the values of n less than or equal to the limit + have exactly ten distinct solutions. + >>> solution(100) + 0 + >>> solution(10000) + 45 + >>> solution(50050) + 292 + """ limit = limit + 1 frequency = [0] * limit for first_term in range(1, limit): @@ -22,4 +52,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_135/sol1.py
Generate documentation strings for clarity
def solution(n_limit: int = 50 * 10**6) -> int: n_sol = [0] * n_limit for delta in range(1, (n_limit + 1) // 4 + 1): for y in range(4 * delta - 1, delta, -1): n = y * (4 * delta - y) if n >= n_limit: break n_sol[n] += 1 ans = 0 for i in range(n_limit): if n_sol[i] == 1: ans += 1 return ans if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,47 @@+""" +Project Euler Problem 136: https://projecteuler.net/problem=136 + +Singleton Difference + +The positive integers, x, y, and z, are consecutive terms of an arithmetic progression. +Given that n is a positive integer, the equation, x^2 - y^2 - z^2 = n, +has exactly one solution when n = 20: + 13^2 - 10^2 - 7^2 = 20. + +In fact there are twenty-five values of n below one hundred for which +the equation has a unique solution. + +How many values of n less than fifty million have exactly one solution? + +By change of variables + +x = y + delta +z = y - delta + +The expression can be rewritten: + +x^2 - y^2 - z^2 = y * (4 * delta - y) = n + +The algorithm loops over delta and y, which is restricted in upper and lower limits, +to count how many solutions each n has. +In the end it is counted how many n's have one solution. +""" def solution(n_limit: int = 50 * 10**6) -> int: + """ + Define n count list and loop over delta, y to get the counts, then check + which n has count == 1. + + >>> solution(3) + 0 + >>> solution(10) + 3 + >>> solution(100) + 25 + >>> solution(110) + 27 + """ n_sol = [0] * n_limit for delta in range(1, (n_limit + 1) // 4 + 1): @@ -19,4 +60,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_136/sol1.py
Replace inline comments with docstrings
EVEN_DIGITS = [0, 2, 4, 6, 8] ODD_DIGITS = [1, 3, 5, 7, 9] def slow_reversible_numbers( remaining_length: int, remainder: int, digits: list[int], length: int ) -> int: if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return 0 for i in range(length // 2 - 1, -1, -1): remainder += digits[i] + digits[length - i - 1] if remainder % 2 == 0: return 0 remainder //= 10 return 1 if remaining_length == 1: if remainder % 2 == 0: return 0 result = 0 for digit in range(10): digits[length // 2] = digit result += slow_reversible_numbers( 0, (remainder + 2 * digit) // 10, digits, length ) return result result = 0 for digit1 in range(10): digits[(length + remaining_length) // 2 - 1] = digit1 if (remainder + digit1) % 2 == 0: other_parity_digits = ODD_DIGITS else: other_parity_digits = EVEN_DIGITS for digit2 in other_parity_digits: digits[(length - remaining_length) // 2] = digit2 result += slow_reversible_numbers( remaining_length - 2, (remainder + digit1 + digit2) // 10, digits, length, ) return result def slow_solution(max_power: int = 9) -> int: result = 0 for length in range(1, max_power + 1): result += slow_reversible_numbers(length, 0, [0] * length, length) return result def reversible_numbers( remaining_length: int, remainder: int, digits: list[int], length: int ) -> int: # There exist no reversible 1, 5, 9, 13 (ie. 4k+1) digit numbers if (length - 1) % 4 == 0: return 0 return slow_reversible_numbers(remaining_length, remainder, digits, length) def solution(max_power: int = 9) -> int: result = 0 for length in range(1, max_power + 1): result += reversible_numbers(length, 0, [0] * length, length) return result def benchmark() -> None: # Running performance benchmarks... # slow_solution : 292.9300301000003 # solution : 54.90970860000016 from timeit import timeit print("Running performance benchmarks...") print(f"slow_solution : {timeit('slow_solution()', globals=globals(), number=10)}") print(f"solution : {timeit('solution()', globals=globals(), number=10)}") if __name__ == "__main__": print(f"Solution : {solution()}") benchmark() # for i in range(1, 15): # print(f"{i}. {reversible_numbers(i, 0, [0]*i, i)}")
--- +++ @@ -1,3 +1,18 @@+""" +Project Euler problem 145: https://projecteuler.net/problem=145 +Author: Vineet Rao, Maxim Smolskiy +Problem statement: + +Some positive integers n have the property that the sum [ n + reverse(n) ] +consists entirely of odd (decimal) digits. +For instance, 36 + 63 = 99 and 409 + 904 = 1313. +We will call such numbers reversible; so 36, 63, 409, and 904 are reversible. +Leading zeroes are not allowed in either n or reverse(n). + +There are 120 reversible numbers below one-thousand. + +How many reversible numbers are there below one-billion (10^9)? +""" EVEN_DIGITS = [0, 2, 4, 6, 8] ODD_DIGITS = [1, 3, 5, 7, 9] @@ -6,6 +21,16 @@ def slow_reversible_numbers( remaining_length: int, remainder: int, digits: list[int], length: int ) -> int: + """ + Count the number of reversible numbers of given length. + Iterate over possible digits considering parity of current sum remainder. + >>> slow_reversible_numbers(1, 0, [0], 1) + 0 + >>> slow_reversible_numbers(2, 0, [0] * 2, 2) + 20 + >>> slow_reversible_numbers(3, 0, [0] * 3, 3) + 100 + """ if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return 0 @@ -53,6 +78,15 @@ def slow_solution(max_power: int = 9) -> int: + """ + To evaluate the solution, use solution() + >>> slow_solution(3) + 120 + >>> slow_solution(6) + 18720 + >>> slow_solution(7) + 68720 + """ result = 0 for length in range(1, max_power + 1): result += slow_reversible_numbers(length, 0, [0] * length, length) @@ -62,6 +96,16 @@ def reversible_numbers( remaining_length: int, remainder: int, digits: list[int], length: int ) -> int: + """ + Count the number of reversible numbers of given length. + Iterate over possible digits considering parity of current sum remainder. + >>> reversible_numbers(1, 0, [0], 1) + 0 + >>> reversible_numbers(2, 0, [0] * 2, 2) + 20 + >>> reversible_numbers(3, 0, [0] * 3, 3) + 100 + """ # There exist no reversible 1, 5, 9, 13 (ie. 4k+1) digit numbers if (length - 1) % 4 == 0: return 0 @@ -70,6 +114,15 @@ def solution(max_power: int = 9) -> int: + """ + To evaluate the solution, use solution() + >>> solution(3) + 120 + >>> solution(6) + 18720 + >>> solution(7) + 68720 + """ result = 0 for length in range(1, max_power + 1): result += reversible_numbers(length, 0, [0] * length, length) @@ -77,6 +130,9 @@ def benchmark() -> None: + """ + Benchmarks + """ # Running performance benchmarks... # slow_solution : 292.9300301000003 # solution : 54.90970860000016 @@ -94,4 +150,4 @@ benchmark() # for i in range(1, 15): - # print(f"{i}. {reversible_numbers(i, 0, [0]*i, i)}")+ # print(f"{i}. {reversible_numbers(i, 0, [0]*i, i)}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_145/sol1.py
Generate docstrings with parameter types
from math import ceil, sqrt def solution(limit: int = 1000000) -> int: answer = 0 for outer_width in range(3, (limit // 4) + 2): if outer_width**2 > limit: hole_width_lower_bound = max(ceil(sqrt(outer_width**2 - limit)), 1) else: hole_width_lower_bound = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,26 @@+""" +Project Euler Problem 173: https://projecteuler.net/problem=173 + +We shall define a square lamina to be a square outline with a square "hole" so that +the shape possesses vertical and horizontal symmetry. For example, using exactly +thirty-two square tiles we can form two different square laminae: + +With one-hundred tiles, and not necessarily using all of the tiles at one time, it is +possible to form forty-one different square laminae. + +Using up to one million tiles how many different square laminae can be formed? +""" from math import ceil, sqrt def solution(limit: int = 1000000) -> int: + """ + Return the number of different square laminae that can be formed using up to + one million tiles. + >>> solution(100) + 41 + """ answer = 0 for outer_width in range(3, (limit // 4) + 2): @@ -19,4 +37,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_173/sol1.py
Document classes and their methods
def solve( digit: int, prev1: int, prev2: int, sum_max: int, first: bool, cache: dict[str, int] ) -> int: if digit == 0: return 1 cache_str = f"{digit},{prev1},{prev2}" if cache_str in cache: return cache[cache_str] comb = 0 for curr in range(sum_max - prev1 - prev2 + 1): if first and curr == 0: continue comb += solve( digit=digit - 1, prev1=curr, prev2=prev1, sum_max=sum_max, first=False, cache=cache, ) cache[cache_str] = comb return comb def solution(n_digits: int = 20) -> int: cache: dict[str, int] = {} return solve(digit=n_digits, prev1=0, prev2=0, sum_max=9, first=True, cache=cache) if __name__ == "__main__": print(f"{solution(10) = }")
--- +++ @@ -1,8 +1,28 @@+""" +Project Euler Problem 164: https://projecteuler.net/problem=164 + +Three Consecutive Digital Sum Limit + +How many 20 digit numbers n (without any leading zero) exist such that no three +consecutive digits of n have a sum greater than 9? + +Brute-force recursive solution with caching of intermediate results. +""" def solve( digit: int, prev1: int, prev2: int, sum_max: int, first: bool, cache: dict[str, int] ) -> int: + """ + Solve for remaining 'digit' digits, with previous 'prev1' digit, and + previous-previous 'prev2' digit, total sum of 'sum_max'. + Pass around 'cache' to store/reuse intermediate results. + + >>> solve(digit=1, prev1=0, prev2=0, sum_max=9, first=True, cache={}) + 9 + >>> solve(digit=1, prev1=0, prev2=0, sum_max=9, first=False, cache={}) + 10 + """ if digit == 0: return 1 @@ -29,9 +49,17 @@ def solution(n_digits: int = 20) -> int: + """ + Solves the problem for n_digits number of digits. + + >>> solution(2) + 45 + >>> solution(10) + 21838806 + """ cache: dict[str, int] = {} return solve(digit=n_digits, prev1=0, prev2=0, sum_max=9, first=True, cache=cache) if __name__ == "__main__": - print(f"{solution(10) = }")+ print(f"{solution(10) = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_164/sol1.py
Generate documentation strings for clarity
def least_divisible_repunit(divisor: int) -> int: if divisor % 5 == 0 or divisor % 2 == 0: return 0 repunit = 1 repunit_index = 1 while repunit: repunit = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def solution(limit: int = 1000000) -> int: divisor = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(divisor) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,29 @@+""" +Project Euler Problem 129: https://projecteuler.net/problem=129 + +A number consisting entirely of ones is called a repunit. We shall define R(k) to be +a repunit of length k; for example, R(6) = 111111. + +Given that n is a positive integer and GCD(n, 10) = 1, it can be shown that there +always exists a value, k, for which R(k) is divisible by n, and let A(n) be the least +such value of k; for example, A(7) = 6 and A(41) = 5. + +The least value of n for which A(n) first exceeds ten is 17. + +Find the least value of n for which A(n) first exceeds one-million. +""" def least_divisible_repunit(divisor: int) -> int: + """ + Return the least value k such that the Repunit of length k is divisible by divisor. + >>> least_divisible_repunit(7) + 6 + >>> least_divisible_repunit(41) + 5 + >>> least_divisible_repunit(1234567) + 34020 + """ if divisor % 5 == 0 or divisor % 2 == 0: return 0 repunit = 1 @@ -12,6 +35,16 @@ def solution(limit: int = 1000000) -> int: + """ + Return the least value of n for which least_divisible_repunit(n) + first exceeds limit. + >>> solution(10) + 17 + >>> solution(100) + 109 + >>> solution(1000) + 1017 + """ divisor = limit - 1 if divisor % 2 == 0: divisor += 1 @@ -21,4 +54,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_129/sol1.py
Include argument descriptions in docstrings
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def is_sq(number: int) -> bool: sq: int = int(number**0.5) return number == sq * sq def add_three( x_num: int, x_den: int, y_num: int, y_den: int, z_num: int, z_den: int ) -> tuple[int, int]: top: int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den bottom: int = x_den * y_den * z_den hcf: int = gcd(top, bottom) top //= hcf bottom //= hcf return top, bottom def solution(order: int = 35) -> int: unique_s: set = set() hcf: int total: Fraction = Fraction(0) fraction_sum: tuple[int, int] for x_num in range(1, order + 1): for x_den in range(x_num + 1, order + 1): for y_num in range(1, order + 1): for y_den in range(y_num + 1, order + 1): # n=1 z_num = x_num * y_den + x_den * y_num z_den = x_den * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) z_den = x_den * x_den * y_den * y_den if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=-1 z_num = x_num * y_num z_den = x_den * y_num + x_num * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = x_num * x_num * y_num * y_num z_den = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) for num, den in unique_s: total += Fraction(num, den) return total.denominator + total.numerator if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,49 @@+""" +Project Euler Problem 234: https://projecteuler.net/problem=234 + +For any integer n, consider the three functions + +f1,n(x,y,z) = x^(n+1) + y^(n+1) - z^(n+1) +f2,n(x,y,z) = (xy + yz + zx)*(x^(n-1) + y^(n-1) - z^(n-1)) +f3,n(x,y,z) = xyz*(xn-2 + yn-2 - zn-2) + +and their combination + +fn(x,y,z) = f1,n(x,y,z) + f2,n(x,y,z) - f3,n(x,y,z) + +We call (x,y,z) a golden triple of order k if x, y, and z are all rational numbers +of the form a / b with 0 < a < b ≤ k and there is (at least) one integer n, +so that fn(x,y,z) = 0. + +Let s(x,y,z) = x + y + z. +Let t = u / v be the sum of all distinct s(x,y,z) for all golden triples +(x,y,z) of order 35. +All the s(x,y,z) and t must be in reduced form. + +Find u + v. + + +Solution: + +By expanding the brackets it is easy to show that +fn(x, y, z) = (x + y + z) * (x^n + y^n - z^n). + +Since x,y,z are positive, the requirement fn(x, y, z) = 0 is fulfilled if and +only if x^n + y^n = z^n. + +By Fermat's Last Theorem, this means that the absolute value of n can not +exceed 2, i.e. n is in {-2, -1, 0, 1, 2}. We can eliminate n = 0 since then the +equation would reduce to 1 + 1 = 1, for which there are no solutions. + +So all we have to do is iterate through the possible numerators and denominators +of x and y, calculate the corresponding z, and check if the corresponding numerator and +denominator are integer and satisfy 0 < z_num < z_den <= 0. We use a set "uniquq_s" +to make sure there are no duplicates, and the fractions.Fraction class to make sure +we get the right numerator and denominator. + +Reference: +https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem +""" from __future__ import annotations @@ -6,6 +52,16 @@ def is_sq(number: int) -> bool: + """ + Check if number is a perfect square. + + >>> is_sq(1) + True + >>> is_sq(1000001) + False + >>> is_sq(1000000) + True + """ sq: int = int(number**0.5) return number == sq * sq @@ -13,6 +69,14 @@ def add_three( x_num: int, x_den: int, y_num: int, y_den: int, z_num: int, z_den: int ) -> tuple[int, int]: + """ + Given the numerators and denominators of three fractions, return the + numerator and denominator of their sum in lowest form. + >>> add_three(1, 3, 1, 3, 1, 3) + (1, 1) + >>> add_three(2, 5, 4, 11, 12, 3) + (262, 55) + """ top: int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den bottom: int = x_den * y_den * z_den hcf: int = gcd(top, bottom) @@ -22,6 +86,17 @@ def solution(order: int = 35) -> int: + """ + Find the sum of the numerator and denominator of the sum of all s(x,y,z) for + golden triples (x,y,z) of the given order. + + >>> solution(5) + 296 + >>> solution(10) + 12519 + >>> solution(20) + 19408891927 + """ unique_s: set = set() hcf: int total: Fraction = Fraction(0) @@ -96,4 +171,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_180/sol1.py
Provide clean and structured docstrings
from collections import defaultdict from math import ceil, sqrt def solution(t_limit: int = 1000000, n_limit: int = 10) -> int: count: defaultdict = defaultdict(int) for outer_width in range(3, (t_limit // 4) + 2): if outer_width * outer_width > t_limit: hole_width_lower_bound = max( ceil(sqrt(outer_width * outer_width - t_limit)), 1 ) else: hole_width_lower_bound = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(hole_width_lower_bound, outer_width - 1, 2): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= n_limit) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,9 +1,37 @@+""" +Project Euler Problem 174: https://projecteuler.net/problem=174 + +We shall define a square lamina to be a square outline with a square "hole" so that +the shape possesses vertical and horizontal symmetry. + +Given eight tiles it is possible to form a lamina in only one way: 3x3 square with a +1x1 hole in the middle. However, using thirty-two tiles it is possible to form two +distinct laminae. + +If t represents the number of tiles used, we shall say that t = 8 is type L(1) and +t = 32 is type L(2). + +Let N(n) be the number of t ≤ 1000000 such that t is type L(n); for example, +N(15) = 832. + +What is sum N(n) for 1 ≤ n ≤ 10? +""" from collections import defaultdict from math import ceil, sqrt def solution(t_limit: int = 1000000, n_limit: int = 10) -> int: + """ + Return the sum of N(n) for 1 <= n <= n_limit. + + >>> solution(1000,5) + 222 + >>> solution(1000,10) + 249 + >>> solution(10000,10) + 2383 + """ count: defaultdict = defaultdict(int) for outer_width in range(3, (t_limit // 4) + 2): @@ -23,4 +51,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_174/sol1.py
Add detailed docstrings explaining each function
import math BALLS_PER_COLOUR = 10 NUM_COLOURS = 7 NUM_BALLS = BALLS_PER_COLOUR * NUM_COLOURS def solution(num_picks: int = 20) -> str: total = math.comb(NUM_BALLS, num_picks) missing_colour = math.comb(NUM_BALLS - BALLS_PER_COLOUR, num_picks) result = NUM_COLOURS * (1 - missing_colour / total) return f"{result:.9f}" if __name__ == "__main__": print(solution(20))
--- +++ @@ -1,3 +1,28 @@+""" +Project Euler Problem 493: https://projecteuler.net/problem=493 + +70 coloured balls are placed in an urn, 10 for each of the seven rainbow colours. +What is the expected number of distinct colours in 20 randomly picked balls? +Give your answer with nine digits after the decimal point (a.bcdefghij). + +----- + +This combinatorial problem can be solved by decomposing the problem into the +following steps: +1. Calculate the total number of possible picking combinations +[combinations := binom_coeff(70, 20)] +2. Calculate the number of combinations with one colour missing +[missing := binom_coeff(60, 20)] +3. Calculate the probability of one colour missing +[missing_prob := missing / combinations] +4. Calculate the probability of no colour missing +[no_missing_prob := 1 - missing_prob] +5. Calculate the expected number of distinct colours +[expected = 7 * no_missing_prob] + +References: +- https://en.wikipedia.org/wiki/Binomial_coefficient +""" import math @@ -7,6 +32,15 @@ def solution(num_picks: int = 20) -> str: + """ + Calculates the expected number of distinct colours + + >>> solution(10) + '5.669644129' + + >>> solution(30) + '6.985042712' + """ total = math.comb(NUM_BALLS, num_picks) missing_colour = math.comb(NUM_BALLS - BALLS_PER_COLOUR, num_picks) @@ -16,4 +50,4 @@ if __name__ == "__main__": - print(solution(20))+ print(solution(20))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_493/sol1.py
Create docstrings for reusable components
def solution(n: int = 15) -> int: total = 0 for m in range(2, n + 1): x1 = 2 / (m + 1) p = 1.0 for i in range(1, m + 1): xi = i * x1 p *= xi**i total += int(p) return total if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,38 @@+""" +Project Euler Problem 190: https://projecteuler.net/problem=190 + +Maximising a Weighted Product + +Let S_m = (x_1, x_2, ..., x_m) be the m-tuple of positive real numbers with +x_1 + x_2 + ... + x_m = m for which P_m = x_1 * x_2^2 * ... * x_m^m is maximised. + +For example, it can be verified that |_ P_10 _| = 4112 +(|_ _| is the integer part function). + +Find Sum_{m=2}^15 = |_ P_m _|. + +Solution: +- Fix x_1 = m - x_2 - ... - x_m. +- Calculate partial derivatives of P_m wrt the x_2, ..., x_m. This gives that + x_2 = 2 * x_1, x_3 = 3 * x_1, ..., x_m = m * x_1. +- Calculate partial second order derivatives of P_m wrt the x_2, ..., x_m. + By plugging in the values from the previous step, can verify that solution is maximum. +""" def solution(n: int = 15) -> int: + """ + Calculate sum of |_ P_m _| for m from 2 to n. + + >>> solution(2) + 1 + >>> solution(3) + 2 + >>> solution(4) + 4 + >>> solution(5) + 10 + """ total = 0 for m in range(2, n + 1): x1 = 2 / (m + 1) @@ -13,4 +45,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_190/sol1.py
Generate helpful docstrings for debugging
from math import isqrt def slow_calculate_prime_numbers(max_number: int) -> list[int]: # List containing a bool value for every number below max_number/2 is_prime = [True] * max_number for i in range(2, isqrt(max_number - 1) + 1): if is_prime[i]: # Mark all multiple of i as not prime for j in range(i**2, max_number, i): is_prime[j] = False return [i for i in range(2, max_number) if is_prime[i]] def calculate_prime_numbers(max_number: int) -> list[int]: if max_number <= 2: return [] # List containing a bool value for every odd number below max_number/2 is_prime = [True] * (max_number // 2) for i in range(3, isqrt(max_number - 1) + 1, 2): if is_prime[i // 2]: # Mark all multiple of i as not prime using list slicing is_prime[i**2 // 2 :: i] = [False] * ( # Same as: (max_number - (i**2)) // (2 * i) + 1 # but faster than len(is_prime[i**2 // 2 :: i]) len(range(i**2 // 2, max_number // 2, i)) ) return [2] + [2 * i + 1 for i in range(1, max_number // 2) if is_prime[i]] def slow_solution(max_number: int = 10**8) -> int: prime_numbers = slow_calculate_prime_numbers(max_number // 2) semiprimes_count = 0 left = 0 right = len(prime_numbers) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count def while_solution(max_number: int = 10**8) -> int: prime_numbers = calculate_prime_numbers(max_number // 2) semiprimes_count = 0 left = 0 right = len(prime_numbers) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count def solution(max_number: int = 10**8) -> int: prime_numbers = calculate_prime_numbers(max_number // 2) semiprimes_count = 0 right = len(prime_numbers) - 1 for left in range(len(prime_numbers)): if left > right: break for r in range(right, left - 2, -1): if prime_numbers[left] * prime_numbers[r] < max_number: break right = r semiprimes_count += right - left + 1 return semiprimes_count def benchmark() -> None: # Running performance benchmarks... # slow_solution : 108.50874730000032 # while_sol : 28.09581200000048 # solution : 25.063097400000515 from timeit import timeit print("Running performance benchmarks...") print(f"slow_solution : {timeit('slow_solution()', globals=globals(), number=10)}") print(f"while_sol : {timeit('while_solution()', globals=globals(), number=10)}") print(f"solution : {timeit('solution()', globals=globals(), number=10)}") if __name__ == "__main__": print(f"Solution: {solution()}") benchmark()
--- +++ @@ -1,8 +1,30 @@+""" +Project Euler Problem 187: https://projecteuler.net/problem=187 + +A composite is a number containing at least two prime factors. +For example, 15 = 3 x 5; 9 = 3 x 3; 12 = 2 x 2 x 3. + +There are ten composites below thirty containing precisely two, +not necessarily distinct, prime factors: 4, 6, 9, 10, 14, 15, 21, 22, 25, 26. + +How many composite integers, n < 10^8, have precisely two, +not necessarily distinct, prime factors? +""" from math import isqrt def slow_calculate_prime_numbers(max_number: int) -> list[int]: + """ + Returns prime numbers below max_number. + See: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes + + >>> slow_calculate_prime_numbers(10) + [2, 3, 5, 7] + + >>> slow_calculate_prime_numbers(2) + [] + """ # List containing a bool value for every number below max_number/2 is_prime = [True] * max_number @@ -17,6 +39,16 @@ def calculate_prime_numbers(max_number: int) -> list[int]: + """ + Returns prime numbers below max_number. + See: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes + + >>> calculate_prime_numbers(10) + [2, 3, 5, 7] + + >>> calculate_prime_numbers(2) + [] + """ if max_number <= 2: return [] @@ -37,6 +69,13 @@ def slow_solution(max_number: int = 10**8) -> int: + """ + Returns the number of composite integers below max_number have precisely two, + not necessarily distinct, prime factors. + + >>> slow_solution(30) + 10 + """ prime_numbers = slow_calculate_prime_numbers(max_number // 2) @@ -53,6 +92,13 @@ def while_solution(max_number: int = 10**8) -> int: + """ + Returns the number of composite integers below max_number have precisely two, + not necessarily distinct, prime factors. + + >>> while_solution(30) + 10 + """ prime_numbers = calculate_prime_numbers(max_number // 2) @@ -69,6 +115,13 @@ def solution(max_number: int = 10**8) -> int: + """ + Returns the number of composite integers below max_number have precisely two, + not necessarily distinct, prime factors. + + >>> solution(30) + 10 + """ prime_numbers = calculate_prime_numbers(max_number // 2) @@ -87,6 +140,9 @@ def benchmark() -> None: + """ + Benchmarks + """ # Running performance benchmarks... # slow_solution : 108.50874730000032 # while_sol : 28.09581200000048 @@ -103,4 +159,4 @@ if __name__ == "__main__": print(f"Solution: {solution()}") - benchmark()+ benchmark()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_187/sol1.py
Add docstrings to my Python code
cache: dict[tuple[int, int, int], int] = {} def _calculate(days: int, absent: int, late: int) -> int: # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on key = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one state_late = _calculate(days - 1, absent, late + 1) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 state_absent = _calculate(days - 1, absent + 1, 0) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter state_ontime = _calculate(days - 1, absent, 0) prizestrings = state_late + state_absent + state_ontime cache[key] = prizestrings return prizestrings def solution(days: int = 30) -> int: return _calculate(days, absent=0, late=0) if __name__ == "__main__": print(solution())
--- +++ @@ -1,8 +1,50 @@+""" +Prize Strings +Problem 191 + +A particular school offers cash rewards to children with good attendance and +punctuality. If they are absent for three consecutive days or late on more +than one occasion then they forfeit their prize. + +During an n-day period a trinary string is formed for each child consisting +of L's (late), O's (on time), and A's (absent). + +Although there are eighty-one trinary strings for a 4-day period that can be +formed, exactly forty-three strings would lead to a prize: + +OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA +OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO +AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL +AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA +LAOO LAOA LAAO + +How many "prize" strings exist over a 30-day period? + +References: + - The original Project Euler project page: + https://projecteuler.net/problem=191 +""" cache: dict[tuple[int, int, int], int] = {} def _calculate(days: int, absent: int, late: int) -> int: + """ + A small helper function for the recursion, mainly to have + a clean interface for the solution() function below. + + It should get called with the number of days (corresponding + to the desired length of the 'prize strings'), and the + initial values for the number of consecutive absent days and + number of total late days. + + >>> _calculate(days=4, absent=0, late=0) + 43 + >>> _calculate(days=30, absent=2, late=0) + 0 + >>> _calculate(days=30, absent=1, late=0) + 98950096 + """ # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible @@ -45,9 +87,18 @@ def solution(days: int = 30) -> int: + """ + Returns the number of possible prize strings for a particular number + of days, using a simple recursive function with caching to speed it up. + + >>> solution() + 1918080160 + >>> solution(4) + 43 + """ return _calculate(days, absent=0, late=0) if __name__ == "__main__": - print(solution())+ print(solution())
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_191/sol1.py
Add docstrings to improve readability
# small helper function for modular exponentiation (fast exponentiation algorithm) def _modexpt(base: int, exponent: int, modulo_value: int) -> int: if exponent == 1: return base if exponent % 2 == 0: x = _modexpt(base, exponent // 2, modulo_value) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(base, exponent - 1, modulo_value)) % modulo_value def solution(base: int = 1777, height: int = 1855, digits: int = 8) -> int: # calculate base↑↑height by right-assiciative repeated modular # exponentiation result = base for _ in range(1, height): result = _modexpt(base, result, 10**digits) return result if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,7 +1,37 @@+""" +Project Euler Problem 188: https://projecteuler.net/problem=188 + +The hyperexponentiation of a number + +The hyperexponentiation or tetration of a number a by a positive integer b, +denoted by a↑↑b or b^a, is recursively defined by: + +a↑↑1 = a, +a↑↑(k+1) = a(a↑↑k). + +Thus we have e.g. 3↑↑2 = 3^3 = 27, hence 3↑↑3 = 3^27 = 7625597484987 and +3↑↑4 is roughly 103.6383346400240996*10^12. + +Find the last 8 digits of 1777↑↑1855. + +References: + - https://en.wikipedia.org/wiki/Tetration +""" # small helper function for modular exponentiation (fast exponentiation algorithm) def _modexpt(base: int, exponent: int, modulo_value: int) -> int: + """ + Returns the modular exponentiation, that is the value + of `base ** exponent % modulo_value`, without calculating + the actual number. + >>> _modexpt(2, 4, 10) + 6 + >>> _modexpt(2, 1024, 100) + 16 + >>> _modexpt(13, 65535, 7) + 6 + """ if exponent == 1: return base @@ -13,6 +43,17 @@ def solution(base: int = 1777, height: int = 1855, digits: int = 8) -> int: + """ + Returns the last 8 digits of the hyperexponentiation of base by + height, i.e. the number base↑↑height: + + >>> solution(base=3, height=2) + 27 + >>> solution(base=3, height=3) + 97484987 + >>> solution(base=123, height=456, digits=4) + 2547 + """ # calculate base↑↑height by right-assiciative repeated modular # exponentiation @@ -24,4 +65,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_188/sol1.py
Replace inline comments with docstrings
import math def check_partition_perfect(positive_integer: int) -> bool: exponent = math.log2(math.sqrt(4 * positive_integer + 1) / 2 + 1 / 2) return exponent == int(exponent) def solution(max_proportion: float = 1 / 12345) -> int: total_partitions = 0 perfect_partitions = 0 integer = 3 while True: partition_candidate = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(partition_candidate): partition_candidate = int(partition_candidate) total_partitions += 1 if check_partition_perfect(partition_candidate): perfect_partitions += 1 if ( perfect_partitions > 0 and perfect_partitions / total_partitions < max_proportion ): return int(partition_candidate) integer += 1 if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,59 @@+""" + +Project Euler Problem 207: https://projecteuler.net/problem=207 + +Problem Statement: +For some positive integers k, there exists an integer partition of the form +4**t = 2**t + k, where 4**t, 2**t, and k are all positive integers and t is a real +number. The first two such partitions are 4**1 = 2**1 + 2 and +4**1.5849625... = 2**1.5849625... + 6. +Partitions where t is also an integer are called perfect. +For any m ≥ 1 let P(m) be the proportion of such partitions that are perfect with +k ≤ m. +Thus P(6) = 1/2. +In the following table are listed some values of P(m) + + P(5) = 1/1 + P(10) = 1/2 + P(15) = 2/3 + P(20) = 1/2 + P(25) = 1/2 + P(30) = 2/5 + ... + P(180) = 1/4 + P(185) = 3/13 + +Find the smallest m for which P(m) < 1/12345 + +Solution: +Equation 4**t = 2**t + k solved for t gives: + t = log2(sqrt(4*k+1)/2 + 1/2) +For t to be real valued, sqrt(4*k+1) must be an integer which is implemented in +function check_t_real(k). For a perfect partition t must be an integer. +To speed up significantly the search for partitions, instead of incrementing k by one +per iteration, the next valid k is found by k = (i**2 - 1) / 4 with an integer i and +k has to be a positive integer. If this is the case a partition is found. The partition +is perfect if t os an integer. The integer i is increased with increment 1 until the +proportion perfect partitions / total partitions drops under the given value. + +""" import math def check_partition_perfect(positive_integer: int) -> bool: + """ + + Check if t = f(positive_integer) = log2(sqrt(4*positive_integer+1)/2 + 1/2) is a + real number. + + >>> check_partition_perfect(2) + True + + >>> check_partition_perfect(6) + False + + """ exponent = math.log2(math.sqrt(4 * positive_integer + 1) / 2 + 1 / 2) @@ -10,6 +61,20 @@ def solution(max_proportion: float = 1 / 12345) -> int: + """ + Find m for which the proportion of perfect partitions to total partitions is lower + than max_proportion + + >>> solution(1) > 5 + True + + >>> solution(1/2) > 10 + True + + >>> solution(3 / 13) > 185 + True + + """ total_partitions = 0 perfect_partitions = 0 @@ -32,4 +97,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_207/sol1.py
Add inline docstrings for readability
def is_square_form(num: int) -> bool: digit = 9 while num > 0: if num % 10 != digit: return False num //= 100 digit -= 1 return True def solution() -> int: num = 138902663 while not is_square_form(num * num): if num % 10 == 3: num -= 6 # (3 - 6) % 10 = 7 else: num -= 4 # (7 - 4) % 10 = 3 return num * 10 if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,49 @@+""" +Project Euler Problem 206: https://projecteuler.net/problem=206 + +Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0, +where each “_” is a single digit. + +----- + +Instead of computing every single permutation of that number and going +through a 10^9 search space, we can narrow it down considerably. + +If the square ends in a 0, then the square root must also end in a 0. Thus, +the last missing digit must be 0 and the square root is a multiple of 10. +We can narrow the search space down to the first 8 digits and multiply the +result of that by 10 at the end. + +Now the last digit is a 9, which can only happen if the square root ends +in a 3 or 7. From this point, we can try one of two different methods to find +the answer: + +1. Start at the lowest possible base number whose square would be in the +format, and count up. The base we would start at is 101010103, whose square is +the closest number to 10203040506070809. Alternate counting up by 4 and 6 so +the last digit of the base is always a 3 or 7. + +2. Start at the highest possible base number whose square would be in the +format, and count down. That base would be 138902663, whose square is the +closest number to 1929394959697989. Alternate counting down by 6 and 4 so the +last digit of the base is always a 3 or 7. + +The solution does option 2 because the answer happens to be much closer to the +starting point. +""" def is_square_form(num: int) -> bool: + """ + Determines if num is in the form 1_2_3_4_5_6_7_8_9 + + >>> is_square_form(1) + False + >>> is_square_form(112233445566778899) + True + >>> is_square_form(123456789012345678) + False + """ digit = 9 while num > 0: @@ -13,6 +56,9 @@ def solution() -> int: + """ + Returns the first integer whose square is of the form 1_2_3_4_5_6_7_8_9_0 + """ num = 138902663 while not is_square_form(num * num): @@ -25,4 +71,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_206/sol1.py
Generate docstrings for script automation
import math def prime_sieve(n: int) -> list: is_prime = [True] * n is_prime[0] = False is_prime[1] = False is_prime[2] = True for i in range(3, int(n**0.5 + 1), 2): index = i * 2 while index < n: is_prime[index] = False index = index + i primes = [2] for i in range(3, n, 2): if is_prime[i]: primes.append(i) return primes def solution(limit: int = 999_966_663_333) -> int: primes_upper_bound = math.floor(math.sqrt(limit)) + 100 primes = prime_sieve(primes_upper_bound) matches_sum = 0 prime_index = 0 last_prime = primes[prime_index] while (last_prime**2) <= limit: next_prime = primes[prime_index + 1] lower_bound = last_prime**2 upper_bound = next_prime**2 # Get numbers divisible by lps(current) current = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) current = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps current = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair last_prime = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
--- +++ @@ -1,8 +1,35 @@+""" +https://projecteuler.net/problem=234 + +For an integer n ≥ 4, we define the lower prime square root of n, denoted by +lps(n), as the largest prime ≤ √n and the upper prime square root of n, ups(n), +as the smallest prime ≥ √n. + +So, for example, lps(4) = 2 = ups(4), lps(1000) = 31, ups(1000) = 37. Let us +call an integer n ≥ 4 semidivisible, if one of lps(n) and ups(n) divides n, +but not both. + +The sum of the semidivisible numbers not exceeding 15 is 30, the numbers are 8, +10 and 12. 15 is not semidivisible because it is a multiple of both lps(15) = 3 +and ups(15) = 5. As a further example, the sum of the 92 semidivisible numbers +up to 1000 is 34825. + +What is the sum of all semidivisible numbers not exceeding 999966663333 ? +""" import math def prime_sieve(n: int) -> list: + """ + Sieve of Erotosthenes + Function to return all the prime numbers up to a certain number + https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes + >>> prime_sieve(3) + [2] + >>> prime_sieve(50) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] + """ is_prime = [True] * n is_prime[0] = False is_prime[1] = False @@ -24,6 +51,17 @@ def solution(limit: int = 999_966_663_333) -> int: + """ + Computes the solution to the problem up to the specified limit + >>> solution(1000) + 34825 + + >>> solution(10_000) + 1134942 + + >>> solution(100_000) + 36393008 + """ primes_upper_bound = math.floor(math.sqrt(limit)) + 100 primes = prime_sieve(primes_upper_bound) @@ -78,4 +116,4 @@ if __name__ == "__main__": - print(solution())+ print(solution())
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_234/sol1.py
Add detailed documentation for each class
from __future__ import annotations def get_pascal_triangle_unique_coefficients(depth: int) -> set[int]: coefficients = {1} previous_coefficients = [1] for _ in range(2, depth + 1): coefficients_begins_one = [*previous_coefficients, 0] coefficients_ends_one = [0, *previous_coefficients] previous_coefficients = [] for x, y in zip(coefficients_begins_one, coefficients_ends_one): coefficients.add(x + y) previous_coefficients.append(x + y) return coefficients def get_squarefrees(unique_coefficients: set[int]) -> set[int]: non_squarefrees = set() for number in unique_coefficients: divisor = 2 copy_number = number while divisor**2 <= copy_number: multiplicity = 0 while copy_number % divisor == 0: copy_number //= divisor multiplicity += 1 if multiplicity >= 2: non_squarefrees.add(number) break divisor += 1 return unique_coefficients.difference(non_squarefrees) def solution(n: int = 51) -> int: unique_coefficients = get_pascal_triangle_unique_coefficients(n) squarefrees = get_squarefrees(unique_coefficients) return sum(squarefrees) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,53 @@+""" +Project Euler Problem 203: https://projecteuler.net/problem=203 + +The binomial coefficients (n k) can be arranged in triangular form, Pascal's +triangle, like this: + 1 + 1 1 + 1 2 1 + 1 3 3 1 + 1 4 6 4 1 + 1 5 10 10 5 1 + 1 6 15 20 15 6 1 +1 7 21 35 35 21 7 1 + ......... + +It can be seen that the first eight rows of Pascal's triangle contain twelve +distinct numbers: 1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 21 and 35. + +A positive integer n is called squarefree if no square of a prime divides n. +Of the twelve distinct numbers in the first eight rows of Pascal's triangle, +all except 4 and 20 are squarefree. The sum of the distinct squarefree numbers +in the first eight rows is 105. + +Find the sum of the distinct squarefree numbers in the first 51 rows of +Pascal's triangle. + +References: +- https://en.wikipedia.org/wiki/Pascal%27s_triangle +""" from __future__ import annotations def get_pascal_triangle_unique_coefficients(depth: int) -> set[int]: + """ + Returns the unique coefficients of a Pascal's triangle of depth "depth". + + The coefficients of this triangle are symmetric. A further improvement to this + method could be to calculate the coefficients once per level. Nonetheless, + the current implementation is fast enough for the original problem. + + >>> get_pascal_triangle_unique_coefficients(1) + {1} + >>> get_pascal_triangle_unique_coefficients(2) + {1} + >>> get_pascal_triangle_unique_coefficients(3) + {1, 2} + >>> get_pascal_triangle_unique_coefficients(8) + {1, 2, 3, 4, 5, 6, 7, 35, 10, 15, 20, 21} + """ coefficients = {1} previous_coefficients = [1] for _ in range(2, depth + 1): @@ -16,6 +61,24 @@ def get_squarefrees(unique_coefficients: set[int]) -> set[int]: + """ + Calculates the squarefree numbers inside unique_coefficients. + + Based on the definition of a non-squarefree number, then any non-squarefree + n can be decomposed as n = p*p*r, where p is positive prime number and r + is a positive integer. + + Under the previous formula, any coefficient that is lower than p*p is + squarefree as r cannot be negative. On the contrary, if any r exists such + that n = p*p*r, then the number is non-squarefree. + + >>> get_squarefrees({1}) + {1} + >>> get_squarefrees({1, 2}) + {1, 2} + >>> get_squarefrees({1, 2, 3, 4, 5, 6, 7, 35, 10, 15, 20, 21}) + {1, 2, 3, 5, 6, 7, 35, 10, 15, 21} + """ non_squarefrees = set() for number in unique_coefficients: @@ -35,10 +98,20 @@ def solution(n: int = 51) -> int: + """ + Returns the sum of squarefrees for a given Pascal's Triangle of depth n. + + >>> solution(1) + 1 + >>> solution(8) + 105 + >>> solution(9) + 175 + """ unique_coefficients = get_pascal_triangle_unique_coefficients(n) squarefrees = get_squarefrees(unique_coefficients) return sum(squarefrees) if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_203/sol1.py
Add docstrings to improve collaboration
from itertools import product def total_frequency_distribution(sides_number: int, dice_number: int) -> list[int]: max_face_number = sides_number max_total = max_face_number * dice_number totals_frequencies = [0] * (max_total + 1) min_face_number = 1 faces_numbers = range(min_face_number, max_face_number + 1) for dice_numbers in product(faces_numbers, repeat=dice_number): total = sum(dice_numbers) totals_frequencies[total] += 1 return totals_frequencies def solution() -> float: peter_totals_frequencies = total_frequency_distribution( sides_number=4, dice_number=9 ) colin_totals_frequencies = total_frequency_distribution( sides_number=6, dice_number=6 ) peter_wins_count = 0 min_peter_total = 9 max_peter_total = 4 * 9 min_colin_total = 6 for peter_total in range(min_peter_total, max_peter_total + 1): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) total_games_number = (4**9) * (6**6) peter_win_probability = peter_wins_count / total_games_number rounded_peter_win_probability = round(peter_win_probability, ndigits=7) return rounded_peter_win_probability if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,29 @@+""" +Project Euler Problem 205: https://projecteuler.net/problem=205 + +Peter has nine four-sided (pyramidal) dice, each with faces numbered 1, 2, 3, 4. +Colin has six six-sided (cubic) dice, each with faces numbered 1, 2, 3, 4, 5, 6. + +Peter and Colin roll their dice and compare totals: the highest total wins. +The result is a draw if the totals are equal. + +What is the probability that Pyramidal Peter beats Cubic Colin? +Give your answer rounded to seven decimal places in the form 0.abcdefg +""" from itertools import product def total_frequency_distribution(sides_number: int, dice_number: int) -> list[int]: + """ + Returns frequency distribution of total + + >>> total_frequency_distribution(sides_number=6, dice_number=1) + [0, 1, 1, 1, 1, 1, 1] + + >>> total_frequency_distribution(sides_number=4, dice_number=2) + [0, 0, 1, 2, 3, 4, 3, 2, 1] + """ max_face_number = sides_number max_total = max_face_number * dice_number @@ -18,6 +39,13 @@ def solution() -> float: + """ + Returns probability that Pyramidal Peter beats Cubic Colin + rounded to seven decimal places in the form 0.abcdefg + + >>> solution() + 0.5731441 + """ peter_totals_frequencies = total_frequency_distribution( sides_number=4, dice_number=9 @@ -44,4 +72,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_205/sol1.py
Generate docstrings for script automation
import numpy as np from numpy.typing import NDArray MATRIX_1 = [ "7 53 183 439 863", "497 383 563 79 973", "287 63 343 169 583", "627 343 773 959 943", "767 473 103 699 303", ] MATRIX_2 = [ "7 53 183 439 863 497 383 563 79 973 287 63 343 169 583", "627 343 773 959 943 767 473 103 699 303 957 703 583 639 913", "447 283 463 29 23 487 463 993 119 883 327 493 423 159 743", "217 623 3 399 853 407 103 983 89 463 290 516 212 462 350", "960 376 682 962 300 780 486 502 912 800 250 346 172 812 350", "870 456 192 162 593 473 915 45 989 873 823 965 425 329 803", "973 965 905 919 133 673 665 235 509 613 673 815 165 992 326", "322 148 972 962 286 255 941 541 265 323 925 281 601 95 973", "445 721 11 525 473 65 511 164 138 672 18 428 154 448 848", "414 456 310 312 798 104 566 520 302 248 694 976 430 392 198", "184 829 373 181 631 101 969 613 840 740 778 458 284 760 390", "821 461 843 513 17 901 711 993 293 157 274 94 192 156 574", "34 124 4 878 450 476 712 914 838 669 875 299 823 329 699", "815 559 813 459 522 788 168 586 966 232 308 833 251 631 107", "813 883 451 509 615 77 281 613 459 205 380 274 302 35 805", ] def solve(arr: NDArray, row: int, cols: set[int], cache: dict[str, int]) -> int: cache_id = f"{row}, {sorted(cols)}" if cache_id in cache: return cache[cache_id] if row == len(arr): return 0 max_sum = 0 for col in cols: new_cols = cols - {col} max_sum = max( max_sum, int(arr[row, col]) + solve(arr=arr, row=row + 1, cols=new_cols, cache=cache), ) cache[cache_id] = max_sum return max_sum def solution(matrix_str: list[str] = MATRIX_2) -> int: n = len(matrix_str) arr = np.empty(shape=(n, n), dtype=int) for row, matrix_row_str in enumerate(matrix_str): matrix_row_list_str = matrix_row_str.split() for col, elem_str in enumerate(matrix_row_list_str): arr[row, col] = int(elem_str) cache: dict[str, int] = {} return solve(arr=arr, row=0, cols=set(range(n)), cache=cache) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,38 @@+""" +Project Euler Problem 345: https://projecteuler.net/problem=345 + +Matrix Sum + +We define the Matrix Sum of a matrix as the maximum possible sum of +matrix elements such that none of the selected elements share the same row or column. + +For example, the Matrix Sum of the matrix below equals +3315 ( = 863 + 383 + 343 + 959 + 767): + 7 53 183 439 863 + 497 383 563 79 973 + 287 63 343 169 583 + 627 343 773 959 943 + 767 473 103 699 303 + +Find the Matrix Sum of: + 7 53 183 439 863 497 383 563 79 973 287 63 343 169 583 + 627 343 773 959 943 767 473 103 699 303 957 703 583 639 913 + 447 283 463 29 23 487 463 993 119 883 327 493 423 159 743 + 217 623 3 399 853 407 103 983 89 463 290 516 212 462 350 + 960 376 682 962 300 780 486 502 912 800 250 346 172 812 350 + 870 456 192 162 593 473 915 45 989 873 823 965 425 329 803 + 973 965 905 919 133 673 665 235 509 613 673 815 165 992 326 + 322 148 972 962 286 255 941 541 265 323 925 281 601 95 973 + 445 721 11 525 473 65 511 164 138 672 18 428 154 448 848 + 414 456 310 312 798 104 566 520 302 248 694 976 430 392 198 + 184 829 373 181 631 101 969 613 840 740 778 458 284 760 390 + 821 461 843 513 17 901 711 993 293 157 274 94 192 156 574 + 34 124 4 878 450 476 712 914 838 669 875 299 823 329 699 + 815 559 813 459 522 788 168 586 966 232 308 833 251 631 107 + 813 883 451 509 615 77 281 613 459 205 380 274 302 35 805 + +Brute force solution, with caching intermediate steps to speed up the calculation. +""" import numpy as np from numpy.typing import NDArray @@ -30,6 +65,13 @@ def solve(arr: NDArray, row: int, cols: set[int], cache: dict[str, int]) -> int: + """ + Finds the max sum for array `arr` starting with row index `row`, and with columns + included in `cols`. `cache` is used for caching intermediate results. + + >>> solve(arr=np.array([[1, 2], [3, 4]]), row=0, cols={0, 1}, cache={}) + 5 + """ cache_id = f"{row}, {sorted(cols)}" if cache_id in cache: @@ -51,6 +93,14 @@ def solution(matrix_str: list[str] = MATRIX_2) -> int: + """ + Takes list of strings `matrix_str` to parse the matrix and calculates the max sum. + + >>> solution(["1 2", "3 4"]) + 5 + >>> solution(MATRIX_1) + 3315 + """ n = len(matrix_str) arr = np.empty(shape=(n, n), dtype=int) @@ -64,4 +114,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_345/sol1.py
Help me add docstrings to my project
def solution(exponent: int = 30) -> int: # To find how many total games were lost for a given exponent x, # we need to find the Fibonacci number F(x+2). fibonacci_index = exponent + 2 phi = (1 + 5**0.5) / 2 fibonacci = (phi**fibonacci_index - (phi - 1) ** fibonacci_index) / 5**0.5 return int(fibonacci) if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,6 +1,50 @@+""" +Project Euler Problem 301: https://projecteuler.net/problem=301 + +Problem Statement: +Nim is a game played with heaps of stones, where two players take +it in turn to remove any number of stones from any heap until no stones remain. + +We'll consider the three-heap normal-play version of +Nim, which works as follows: +- At the start of the game there are three heaps of stones. +- On each player's turn, the player may remove any positive + number of stones from any single heap. +- The first player unable to move (because no stones remain) loses. + +If (n1, n2, n3) indicates a Nim position consisting of heaps of size +n1, n2, and n3, then there is a simple function, which you may look up +or attempt to deduce for yourself, X(n1, n2, n3) that returns: +- zero if, with perfect strategy, the player about to + move will eventually lose; or +- non-zero if, with perfect strategy, the player about + to move will eventually win. + +For example X(1,2,3) = 0 because, no matter what the current player does, +the opponent can respond with a move that leaves two heaps of equal size, +at which point every move by the current player can be mirrored by the +opponent until no stones remain; so the current player loses. To illustrate: +- current player moves to (1,2,1) +- opponent moves to (1,0,1) +- current player moves to (0,0,1) +- opponent moves to (0,0,0), and so wins. + +For how many positive integers n <= 2^30 does X(n,2n,3n) = 0? +""" def solution(exponent: int = 30) -> int: + """ + For any given exponent x >= 0, 1 <= n <= 2^x. + This function returns how many Nim games are lost given that + each Nim game has three heaps of the form (n, 2*n, 3*n). + >>> solution(0) + 1 + >>> solution(2) + 3 + >>> solution(10) + 144 + """ # To find how many total games were lost for a given exponent x, # we need to find the Fibonacci number F(x+2). fibonacci_index = exponent + 2 @@ -11,4 +55,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_301/sol1.py
Generate helpful docstrings for debugging
import math def log_difference(number: int) -> float: log_number = math.log(2, 10) * number difference = round((log_number - int(log_number)), 15) return difference def solution(number: int = 678910) -> int: power_iterator = 90 position = 0 lower_limit = math.log(1.23, 10) upper_limit = math.log(1.24, 10) previous_power = 0 while position < number: difference = log_difference(power_iterator) if difference >= upper_limit: power_iterator += 93 elif difference < lower_limit: power_iterator += 196 else: previous_power = power_iterator power_iterator += 196 position += 1 return previous_power if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
--- +++ @@ -1,8 +1,41 @@+""" +Project Euler Problem 686: https://projecteuler.net/problem=686 + +2^7 = 128 is the first power of two whose leading digits are "12". +The next power of two whose leading digits are "12" is 2^80. + +Define p(L,n) to be the nth-smallest value of j such that +the base 10 representation of 2^j begins with the digits of L. + +So p(12, 1) = 7 and p(12, 2) = 80. + +You are given that p(123, 45) = 12710. + +Find p(123, 678910). +""" import math def log_difference(number: int) -> float: + """ + This function returns the decimal value of a number multiplied with log(2) + Since the problem is on powers of two, finding the powers of two with + large exponents is time consuming. Hence we use log to reduce compute time. + + We can find out that the first power of 2 with starting digits 123 is 90. + Computing 2^90 is time consuming. + Hence we find log(2^90) = 90*log(2) = 27.092699609758302 + But we require only the decimal part to determine whether the power starts with 123. + So we just return the decimal part of the log product. + Therefore we return 0.092699609758302 + + >>> log_difference(90) + 0.092699609758302 + >>> log_difference(379) + 0.090368356648852 + + """ log_number = math.log(2, 10) * number difference = round((log_number - int(log_number)), 15) @@ -11,6 +44,89 @@ def solution(number: int = 678910) -> int: + """ + This function calculates the power of two which is nth (n = number) + smallest value of power of 2 + such that the starting digits of the 2^power is 123. + + For example the powers of 2 for which starting digits is 123 are: + 90, 379, 575, 864, 1060, 1545, 1741, 2030, 2226, 2515 and so on. + 90 is the first power of 2 whose starting digits are 123, + 379 is second power of 2 whose starting digits are 123, + and so on. + + So if number = 10, then solution returns 2515 as we observe from above series. + + We will define a lowerbound and upperbound. + lowerbound = log(1.23), upperbound = log(1.24) + because we need to find the powers that yield 123 as starting digits. + + log(1.23) = 0.08990511143939792, log(1,24) = 0.09342168516223506. + We use 1.23 and not 12.3 or 123, because log(1.23) yields only decimal value + which is less than 1. + log(12.3) will be same decimal value but 1 added to it + which is log(12.3) = 1.093421685162235. + We observe that decimal value remains same no matter 1.23 or 12.3 + Since we use the function log_difference(), + which returns the value that is only decimal part, using 1.23 is logical. + + If we see, 90*log(2) = 27.092699609758302, + decimal part = 0.092699609758302, which is inside the range of lowerbound + and upperbound. + + If we compute the difference between all the powers which lead to 123 + starting digits is as follows: + + 379 - 90 = 289 + 575 - 379 = 196 + 864 - 575 = 289 + 1060 - 864 = 196 + + We see a pattern here. The difference is either 196 or 289 = 196 + 93. + + Hence to optimize the algorithm we will increment by 196 or 93 depending upon the + log_difference() value. + + Let's take for example 90. + Since 90 is the first power leading to staring digits as 123, + we will increment iterator by 196. + Because the difference between any two powers leading to 123 + as staring digits is greater than or equal to 196. + After incrementing by 196 we get 286. + + log_difference(286) = 0.09457875989861 which is greater than upperbound. + The next power is 379, and we need to add 93 to get there. + The iterator will now become 379, + which is the next power leading to 123 as starting digits. + + Let's take 1060. We increment by 196, we get 1256. + log_difference(1256) = 0.09367455396034, + Which is greater than upperbound hence we increment by 93. Now iterator is 1349. + log_difference(1349) = 0.08946415071057 which is less than lowerbound. + The next power is 1545 and we need to add 196 to get 1545. + + Conditions are as follows: + + 1) If we find a power whose log_difference() is in the range of + lower and upperbound, we will increment by 196. + which implies that the power is a number which will lead to 123 as starting digits. + 2) If we find a power, whose log_difference() is greater than or equal upperbound, + we will increment by 93. + 3) if log_difference() < lowerbound, we increment by 196. + + Reference to the above logic: + https://math.stackexchange.com/questions/4093970/powers-of-2-starting-with-123-does-a-pattern-exist + + >>> solution(1000) + 284168 + + >>> solution(56000) + 15924915 + + >>> solution(678910) + 193060223 + + """ power_iterator = 90 position = 0 @@ -41,4 +157,4 @@ doctest.testmod() - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_686/sol1.py
Write beginner-friendly docstrings
def median_of_five(arr: list) -> int: arr = sorted(arr) return arr[len(arr) // 2] def median_of_medians(arr: list) -> int: if len(arr) <= 5: return median_of_five(arr) medians = [] i = 0 while i < len(arr): if (i + 4) <= len(arr): medians.append(median_of_five(arr[i:].copy())) else: medians.append(median_of_five(arr[i : i + 5].copy())) i += 5 return median_of_medians(medians) def quick_select(arr: list, target: int) -> int: # Invalid Input if target > len(arr): return -1 # x is the estimated pivot by median of medians algorithm x = median_of_medians(arr) left = [] right = [] check = False for i in range(len(arr)): if arr[i] < x: left.append(arr[i]) elif arr[i] > x: right.append(arr[i]) elif arr[i] == x and not check: check = True else: right.append(arr[i]) rank_x = len(left) + 1 if rank_x == target: answer = x elif rank_x > target: answer = quick_select(left, target) elif rank_x < target: answer = quick_select(right, target - rank_x) return answer print(median_of_five([5, 4, 3, 2]))
--- +++ @@ -1,11 +1,49 @@+""" +A Python implementation of the Median of Medians algorithm +to select pivots for quick_select, which is efficient for +calculating the value that would appear in the index of a +list if it would be sorted, even if it is not already +sorted. Search in time complexity O(n) at any rank +deterministically +https://en.wikipedia.org/wiki/Median_of_medians +""" def median_of_five(arr: list) -> int: + """ + Return the median of the input list + :param arr: Array to find median of + :return: median of arr + + >>> median_of_five([2, 4, 5, 7, 899]) + 5 + >>> median_of_five([5, 7, 899, 54, 32]) + 32 + >>> median_of_five([5, 4, 3, 2]) + 4 + >>> median_of_five([3, 5, 7, 10, 2]) + 5 + """ arr = sorted(arr) return arr[len(arr) // 2] def median_of_medians(arr: list) -> int: + """ + Return a pivot to partition data on by calculating + Median of medians of input data + :param arr: The data to be checked (a list) + :return: median of medians of input array + + >>> median_of_medians([2, 4, 5, 7, 899, 54, 32]) + 54 + >>> median_of_medians([5, 7, 899, 54, 32]) + 32 + >>> median_of_medians([5, 4, 3, 2]) + 4 + >>> median_of_medians([3, 5, 7, 10, 2, 12]) + 12 + """ if len(arr) <= 5: return median_of_five(arr) @@ -21,6 +59,22 @@ def quick_select(arr: list, target: int) -> int: + """ + Two way partition the data into smaller and greater lists, + in relationship to the pivot + :param arr: The data to be searched (a list) + :param target: The rank to be searched + :return: element at rank target + + >>> quick_select([2, 4, 5, 7, 899, 54, 32], 5) + 32 + >>> quick_select([2, 4, 5, 7, 899, 54, 32], 1) + 2 + >>> quick_select([5, 4, 3, 2], 2) + 3 + >>> quick_select([3, 5, 7, 10, 2, 12], 3) + 5 + """ # Invalid Input if target > len(arr): @@ -50,4 +104,4 @@ return answer -print(median_of_five([5, 4, 3, 2]))+print(median_of_five([5, 4, 3, 2]))
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/median_of_medians.py
Add docstrings for utility scripts
from __future__ import annotations import queue class TreeNode: def __init__(self, data): self.data = data self.right = None self.left = None def build_tree() -> TreeNode: print("\n********Press N to stop entering at any point of time********\n") check = input("Enter the value of the root node: ").strip().lower() q: queue.Queue = queue.Queue() tree_node = TreeNode(int(check)) q.put(tree_node) while not q.empty(): node_found = q.get() msg = f"Enter the left node of {node_found.data}: " check = input(msg).strip().lower() or "n" if check == "n": return tree_node left_node = TreeNode(int(check)) node_found.left = left_node q.put(left_node) msg = f"Enter the right node of {node_found.data}: " check = input(msg).strip().lower() or "n" if check == "n": return tree_node right_node = TreeNode(int(check)) node_found.right = right_node q.put(right_node) raise ValueError("Something went wrong") def pre_order(node: TreeNode) -> None: if not isinstance(node, TreeNode) or not node: return print(node.data, end=",") pre_order(node.left) pre_order(node.right) def in_order(node: TreeNode) -> None: if not isinstance(node, TreeNode) or not node: return in_order(node.left) print(node.data, end=",") in_order(node.right) def post_order(node: TreeNode) -> None: if not isinstance(node, TreeNode) or not node: return post_order(node.left) post_order(node.right) print(node.data, end=",") def level_order(node: TreeNode) -> None: if not isinstance(node, TreeNode) or not node: return q: queue.Queue = queue.Queue() q.put(node) while not q.empty(): node_dequeued = q.get() print(node_dequeued.data, end=",") if node_dequeued.left: q.put(node_dequeued.left) if node_dequeued.right: q.put(node_dequeued.right) def level_order_actual(node: TreeNode) -> None: if not isinstance(node, TreeNode) or not node: return q: queue.Queue = queue.Queue() q.put(node) while not q.empty(): list_ = [] while not q.empty(): node_dequeued = q.get() print(node_dequeued.data, end=",") if node_dequeued.left: list_.append(node_dequeued.left) if node_dequeued.right: list_.append(node_dequeued.right) print() for inner_node in list_: q.put(inner_node) # iteration version def pre_order_iter(node: TreeNode) -> None: if not isinstance(node, TreeNode) or not node: return stack: list[TreeNode] = [] n = node while n or stack: while n: # start from root node, find its left child print(n.data, end=",") stack.append(n) n = n.left # end of while means current node doesn't have left child n = stack.pop() # start to traverse its right child n = n.right def in_order_iter(node: TreeNode) -> None: if not isinstance(node, TreeNode) or not node: return stack: list[TreeNode] = [] n = node while n or stack: while n: stack.append(n) n = n.left n = stack.pop() print(n.data, end=",") n = n.right def post_order_iter(node: TreeNode) -> None: if not isinstance(node, TreeNode) or not node: return stack1, stack2 = [], [] n = node stack1.append(n) while stack1: # to find the reversed order of post order, store it in stack2 n = stack1.pop() if n.left: stack1.append(n.left) if n.right: stack1.append(n.right) stack2.append(n) while stack2: # pop up from stack2 will be the post order print(stack2.pop().data, end=",") def prompt(s: str = "", width=50, char="*") -> str: if not s: return "\n" + width * char left, extra = divmod(width - len(s) - 2, 2) return f"{left * char} {s} {(left + extra) * char}" if __name__ == "__main__": import doctest doctest.testmod() print(prompt("Binary Tree Traversals")) node: TreeNode = build_tree() print(prompt("Pre Order Traversal")) pre_order(node) print(prompt() + "\n") print(prompt("In Order Traversal")) in_order(node) print(prompt() + "\n") print(prompt("Post Order Traversal")) post_order(node) print(prompt() + "\n") print(prompt("Level Order Traversal")) level_order(node) print(prompt() + "\n") print(prompt("Actual Level Order Traversal")) level_order_actual(node) print("*" * 50 + "\n") print(prompt("Pre Order Traversal - Iteration Version")) pre_order_iter(node) print(prompt() + "\n") print(prompt("In Order Traversal - Iteration Version")) in_order_iter(node) print(prompt() + "\n") print(prompt("Post Order Traversal - Iteration Version")) post_order_iter(node) print(prompt())
--- +++ @@ -1,3 +1,6 @@+""" +This is pure Python implementation of tree traversal algorithms +""" from __future__ import annotations @@ -37,6 +40,20 @@ def pre_order(node: TreeNode) -> None: + """ + >>> root = TreeNode(1) + >>> tree_node2 = TreeNode(2) + >>> tree_node3 = TreeNode(3) + >>> tree_node4 = TreeNode(4) + >>> tree_node5 = TreeNode(5) + >>> tree_node6 = TreeNode(6) + >>> tree_node7 = TreeNode(7) + >>> root.left, root.right = tree_node2, tree_node3 + >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 + >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 + >>> pre_order(root) + 1,2,4,5,3,6,7, + """ if not isinstance(node, TreeNode) or not node: return print(node.data, end=",") @@ -45,6 +62,20 @@ def in_order(node: TreeNode) -> None: + """ + >>> root = TreeNode(1) + >>> tree_node2 = TreeNode(2) + >>> tree_node3 = TreeNode(3) + >>> tree_node4 = TreeNode(4) + >>> tree_node5 = TreeNode(5) + >>> tree_node6 = TreeNode(6) + >>> tree_node7 = TreeNode(7) + >>> root.left, root.right = tree_node2, tree_node3 + >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 + >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 + >>> in_order(root) + 4,2,5,1,6,3,7, + """ if not isinstance(node, TreeNode) or not node: return in_order(node.left) @@ -53,6 +84,20 @@ def post_order(node: TreeNode) -> None: + """ + >>> root = TreeNode(1) + >>> tree_node2 = TreeNode(2) + >>> tree_node3 = TreeNode(3) + >>> tree_node4 = TreeNode(4) + >>> tree_node5 = TreeNode(5) + >>> tree_node6 = TreeNode(6) + >>> tree_node7 = TreeNode(7) + >>> root.left, root.right = tree_node2, tree_node3 + >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 + >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 + >>> post_order(root) + 4,5,2,6,7,3,1, + """ if not isinstance(node, TreeNode) or not node: return post_order(node.left) @@ -61,6 +106,20 @@ def level_order(node: TreeNode) -> None: + """ + >>> root = TreeNode(1) + >>> tree_node2 = TreeNode(2) + >>> tree_node3 = TreeNode(3) + >>> tree_node4 = TreeNode(4) + >>> tree_node5 = TreeNode(5) + >>> tree_node6 = TreeNode(6) + >>> tree_node7 = TreeNode(7) + >>> root.left, root.right = tree_node2, tree_node3 + >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 + >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 + >>> level_order(root) + 1,2,3,4,5,6,7, + """ if not isinstance(node, TreeNode) or not node: return q: queue.Queue = queue.Queue() @@ -75,6 +134,22 @@ def level_order_actual(node: TreeNode) -> None: + """ + >>> root = TreeNode(1) + >>> tree_node2 = TreeNode(2) + >>> tree_node3 = TreeNode(3) + >>> tree_node4 = TreeNode(4) + >>> tree_node5 = TreeNode(5) + >>> tree_node6 = TreeNode(6) + >>> tree_node7 = TreeNode(7) + >>> root.left, root.right = tree_node2, tree_node3 + >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 + >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 + >>> level_order_actual(root) + 1, + 2,3, + 4,5,6,7, + """ if not isinstance(node, TreeNode) or not node: return q: queue.Queue = queue.Queue() @@ -95,6 +170,20 @@ # iteration version def pre_order_iter(node: TreeNode) -> None: + """ + >>> root = TreeNode(1) + >>> tree_node2 = TreeNode(2) + >>> tree_node3 = TreeNode(3) + >>> tree_node4 = TreeNode(4) + >>> tree_node5 = TreeNode(5) + >>> tree_node6 = TreeNode(6) + >>> tree_node7 = TreeNode(7) + >>> root.left, root.right = tree_node2, tree_node3 + >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 + >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 + >>> pre_order_iter(root) + 1,2,4,5,3,6,7, + """ if not isinstance(node, TreeNode) or not node: return stack: list[TreeNode] = [] @@ -111,6 +200,20 @@ def in_order_iter(node: TreeNode) -> None: + """ + >>> root = TreeNode(1) + >>> tree_node2 = TreeNode(2) + >>> tree_node3 = TreeNode(3) + >>> tree_node4 = TreeNode(4) + >>> tree_node5 = TreeNode(5) + >>> tree_node6 = TreeNode(6) + >>> tree_node7 = TreeNode(7) + >>> root.left, root.right = tree_node2, tree_node3 + >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 + >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 + >>> in_order_iter(root) + 4,2,5,1,6,3,7, + """ if not isinstance(node, TreeNode) or not node: return stack: list[TreeNode] = [] @@ -125,6 +228,20 @@ def post_order_iter(node: TreeNode) -> None: + """ + >>> root = TreeNode(1) + >>> tree_node2 = TreeNode(2) + >>> tree_node3 = TreeNode(3) + >>> tree_node4 = TreeNode(4) + >>> tree_node5 = TreeNode(5) + >>> tree_node6 = TreeNode(6) + >>> tree_node7 = TreeNode(7) + >>> root.left, root.right = tree_node2, tree_node3 + >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 + >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 + >>> post_order_iter(root) + 4,5,2,6,7,3,1, + """ if not isinstance(node, TreeNode) or not node: return stack1, stack2 = [], [] @@ -185,4 +302,4 @@ print(prompt("Post Order Traversal - Iteration Version")) post_order_iter(node) - print(prompt())+ print(prompt())
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/binary_tree_traversal.py
Generate descriptive docstrings automatically
from itertools import count from math import asin, pi, sqrt def circle_bottom_arc_integral(point: float) -> float: return ( (1 - 2 * point) * sqrt(point - point**2) + 2 * point + asin(sqrt(1 - point)) ) / 4 def concave_triangle_area(circles_number: int) -> float: intersection_y = (circles_number + 1 - sqrt(2 * circles_number)) / ( 2 * (circles_number**2 + 1) ) intersection_x = circles_number * intersection_y triangle_area = intersection_x * intersection_y / 2 concave_region_area = circle_bottom_arc_integral( 1 / 2 ) - circle_bottom_arc_integral(intersection_x) return triangle_area + concave_region_area def solution(fraction: float = 1 / 1000) -> int: l_section_area = (1 - pi / 4) / 4 for n in count(1): if concave_triangle_area(n) / l_section_area < fraction: return n return -1 if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,9 +1,47 @@+""" +Project Euler Problem 587: https://projecteuler.net/problem=587 + +A square is drawn around a circle as shown in the diagram below on the left. +We shall call the blue shaded region the L-section. +A line is drawn from the bottom left of the square to the top right +as shown in the diagram on the right. +We shall call the orange shaded region a concave triangle. + +It should be clear that the concave triangle occupies exactly half of the L-section. + +Two circles are placed next to each other horizontally, +a rectangle is drawn around both circles, and +a line is drawn from the bottom left to the top right as shown in the diagram below. + +This time the concave triangle occupies approximately 36.46% of the L-section. + +If n circles are placed next to each other horizontally, +a rectangle is drawn around the n circles, and +a line is drawn from the bottom left to the top right, +then it can be shown that the least value of n +for which the concave triangle occupies less than 10% of the L-section is n = 15. + +What is the least value of n +for which the concave triangle occupies less than 0.1% of the L-section? +""" from itertools import count from math import asin, pi, sqrt def circle_bottom_arc_integral(point: float) -> float: + """ + Returns integral of circle bottom arc y = 1 / 2 - sqrt(1 / 4 - (x - 1 / 2) ^ 2) + + >>> circle_bottom_arc_integral(0) + 0.39269908169872414 + + >>> circle_bottom_arc_integral(1 / 2) + 0.44634954084936207 + + >>> circle_bottom_arc_integral(1) + 0.5 + """ return ( (1 - 2 * point) * sqrt(point - point**2) + 2 * point + asin(sqrt(1 - point)) @@ -11,6 +49,15 @@ def concave_triangle_area(circles_number: int) -> float: + """ + Returns area of concave triangle + + >>> concave_triangle_area(1) + 0.026825229575318944 + + >>> concave_triangle_area(2) + 0.01956236140083944 + """ intersection_y = (circles_number + 1 - sqrt(2 * circles_number)) / ( 2 * (circles_number**2 + 1) @@ -26,6 +73,13 @@ def solution(fraction: float = 1 / 1000) -> int: + """ + Returns least value of n + for which the concave triangle occupies less than fraction of the L-section + + >>> solution(1 / 10) + 15 + """ l_section_area = (1 - pi / 4) / 4 @@ -37,4 +91,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_587/sol1.py
Add inline docstrings for readability
ks = range(2, 20 + 1) base = [10**k for k in range(ks[-1] + 1)] memo: dict[int, dict[int, list[list[int]]]] = {} def next_term(a_i, k, i, n): # ds_b - digitsum(b) ds_b = sum(a_i[j] for j in range(k, len(a_i))) c = sum(a_i[j] * base[j] for j in range(min(len(a_i), k))) diff, dn = 0, 0 max_dn = n - i sub_memo = memo.get(ds_b) if sub_memo is not None: jumps = sub_memo.get(c) if jumps is not None and len(jumps) > 0: # find and make the largest jump without going over max_jump = -1 for _k in range(len(jumps) - 1, -1, -1): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: max_jump = _k break if max_jump >= 0: diff, dn, _kk = jumps[max_jump] # since the difference between jumps is cached, add c new_c = diff + c for j in range(min(k, len(a_i))): new_c, a_i[j] = divmod(new_c, 10) if new_c > 0: add(a_i, k, new_c) else: sub_memo[c] = [] else: sub_memo = {c: []} memo[ds_b] = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps _diff, terms_jumped = next_term(a_i, k - 1, i + dn, n) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead _diff, terms_jumped = compute(a_i, k, i + dn, n) diff += _diff dn += terms_jumped jumps = sub_memo[c] # keep jumps sorted by # of terms skipped j = 0 while j < len(jumps): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(j, (diff, dn, k)) return (diff, dn) def compute(a_i, k, i, n): if i >= n: return 0, i if k > len(a_i): a_i.extend([0 for _ in range(k - len(a_i))]) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) start_i = i ds_b, ds_c, diff = 0, 0, 0 for j in range(len(a_i)): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 addend = ds_c + ds_b diff += addend ds_c = 0 for j in range(k): s = a_i[j] + addend addend, a_i[j] = divmod(s, 10) ds_c += a_i[j] if addend > 0: break if addend > 0: add(a_i, k, addend) return diff, i - start_i def add(digits, k, addend): for j in range(k, len(digits)): s = digits[j] + addend if s >= 10: quotient, digits[j] = divmod(s, 10) addend = addend // 10 + quotient else: digits[j] = s addend = addend // 10 if addend == 0: break while addend > 0: addend, digit = divmod(addend, 10) digits.append(digit) def solution(n: int = 10**15) -> int: digits = [1] i = 1 dn = 0 while True: _diff, terms_jumped = next_term(digits, 20, i + dn, n) dn += terms_jumped if dn == n - i: break a_n = 0 for j in range(len(digits)): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,3 +1,16 @@+""" +Sum of digits sequence +Problem 551 + +Let a(0), a(1),... be an integer sequence defined by: + a(0) = 1 + for n >= 1, a(n) is the sum of the digits of all preceding terms + +The sequence starts with 1, 1, 2, 4, 8, ... +You are given a(10^6) = 31054319. + +Find a(10^15) +""" ks = range(2, 20 + 1) base = [10**k for k in range(ks[-1] + 1)] @@ -5,6 +18,27 @@ def next_term(a_i, k, i, n): + """ + Calculates and updates a_i in-place to either the n-th term or the + smallest term for which c > 10^k when the terms are written in the form: + a(i) = b * 10^k + c + + For any a(i), if digitsum(b) and c have the same value, the difference + between subsequent terms will be the same until c >= 10^k. This difference + is cached to greatly speed up the computation. + + Arguments: + a_i -- array of digits starting from the one's place that represent + the i-th term in the sequence + k -- k when terms are written in the from a(i) = b*10^k + c. + Term are calulcated until c > 10^k or the n-th term is reached. + i -- position along the sequence + n -- term to calculate up to if k is large enough + + Return: a tuple of difference between ending term and starting term, and + the number of terms calculated. ex. if starting term is a_0=1, and + ending term is a_10=62, then (61, 9) is returned. + """ # ds_b - digitsum(b) ds_b = sum(a_i[j] for j in range(k, len(a_i))) c = sum(a_i[j] * base[j] for j in range(min(len(a_i), k))) @@ -73,6 +107,9 @@ def compute(a_i, k, i, n): + """ + same as next_term(a_i, k, i, n) but computes terms without memoizing results. + """ if i >= n: return 0, i if k > len(a_i): @@ -109,6 +146,10 @@ def add(digits, k, addend): + """ + adds addend to digit array given in digits + starting at index k + """ for j in range(k, len(digits)): s = digits[j] + addend if s >= 10: @@ -127,6 +168,18 @@ def solution(n: int = 10**15) -> int: + """ + returns n-th term of sequence + + >>> solution(10) + 62 + + >>> solution(10**6) + 31054319 + + >>> solution(10**15) + 73597483551591773 + """ digits = [1] i = 1 @@ -144,4 +197,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_551/sol1.py
Add professional docstrings to my codebase
from statistics import mean import numpy as np def calculate_turn_around_time( process_name: list, arrival_time: list, burst_time: list, no_of_process: int ) -> list: current_time = 0 # Number of processes finished finished_process_count = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. finished_process = [0] * no_of_process # List to include calculation results turn_around_time = [0] * no_of_process # Sort by arrival time. burst_time = [burst_time[i] for i in np.argsort(arrival_time)] process_name = [process_name[i] for i in np.argsort(arrival_time)] arrival_time.sort() while no_of_process > finished_process_count: """ If the current time is less than the arrival time of the process that arrives first among the processes that have not been performed, change the current time. """ i = 0 while finished_process[i] == 1: i += 1 current_time = max(current_time, arrival_time[i]) response_ratio = 0 # Index showing the location of the process being performed loc = 0 # Saves the current response ratio. temp = 0 for i in range(no_of_process): if finished_process[i] == 0 and arrival_time[i] <= current_time: temp = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: response_ratio = temp loc = i # Calculate the turn around time turn_around_time[loc] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. finished_process[loc] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def calculate_waiting_time( process_name: list, # noqa: ARG001 turn_around_time: list, burst_time: list, no_of_process: int, ) -> list: waiting_time = [0] * no_of_process for i in range(no_of_process): waiting_time[i] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": no_of_process = 5 process_name = ["A", "B", "C", "D", "E"] arrival_time = [1, 2, 3, 4, 5] burst_time = [1, 2, 3, 4, 5] turn_around_time = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) waiting_time = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print("Process name \tArrival time \tBurst time \tTurn around time \tWaiting time") for i in range(no_of_process): print( f"{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t" f"{turn_around_time[i]}\t\t\t{waiting_time[i]}" ) print(f"average waiting time : {mean(waiting_time):.5f}") print(f"average turn around time : {mean(turn_around_time):.5f}")
--- +++ @@ -1,3 +1,9 @@+""" +Highest response ratio next (HRRN) scheduling is a non-preemptive discipline. +It was developed as modification of shortest job next or shortest job first (SJN or SJF) +to mitigate the problem of process starvation. +https://en.wikipedia.org/wiki/Highest_response_ratio_next +""" from statistics import mean @@ -7,6 +13,15 @@ def calculate_turn_around_time( process_name: list, arrival_time: list, burst_time: list, no_of_process: int ) -> list: + """ + Calculate the turn around time of each processes + + Return: The turn around time time for each process. + >>> calculate_turn_around_time(["A", "B", "C"], [3, 5, 8], [2, 4, 6], 3) + [2, 4, 7] + >>> calculate_turn_around_time(["A", "B", "C"], [0, 2, 4], [3, 5, 7], 3) + [3, 6, 11] + """ current_time = 0 # Number of processes finished @@ -64,6 +79,15 @@ burst_time: list, no_of_process: int, ) -> list: + """ + Calculate the waiting time of each processes. + + Return: The waiting time for each process. + >>> calculate_waiting_time(["A", "B", "C"], [2, 4, 7], [2, 4, 6], 3) + [0, 0, 1] + >>> calculate_waiting_time(["A", "B", "C"], [3, 6, 11], [3, 5, 7], 3) + [0, 1, 4] + """ waiting_time = [0] * no_of_process for i in range(no_of_process): @@ -92,4 +116,4 @@ ) print(f"average waiting time : {mean(waiting_time):.5f}") - print(f"average turn around time : {mean(turn_around_time):.5f}")+ print(f"average turn around time : {mean(turn_around_time):.5f}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/scheduling/highest_response_ratio_next.py
Document this script properly
from dataclasses import dataclass from operator import attrgetter @dataclass class Task: task_id: int deadline: int reward: int def max_tasks(tasks_info: list[tuple[int, int]]) -> list[int]: tasks = sorted( ( Task(task_id, deadline, reward) for task_id, (deadline, reward) in enumerate(tasks_info) ), key=attrgetter("reward"), reverse=True, ) return [task.task_id for i, task in enumerate(tasks, start=1) if task.deadline >= i] if __name__ == "__main__": import doctest doctest.testmod() print(f"{max_tasks([(4, 20), (1, 10), (1, 40), (1, 30)]) = }") print(f"{max_tasks([(1, 10), (2, 20), (3, 30), (2, 40)]) = }")
--- +++ @@ -1,3 +1,18 @@+""" +Given a list of tasks, each with a deadline and reward, calculate which tasks can be +completed to yield the maximum reward. Each task takes one unit of time to complete, +and we can only work on one task at a time. Once a task has passed its deadline, it +can no longer be scheduled. + +Example : +tasks_info = [(4, 20), (1, 10), (1, 40), (1, 30)] +max_tasks will return (2, [2, 0]) - +Scheduling these tasks would result in a reward of 40 + 20 + +This problem can be solved using the concept of "GREEDY ALGORITHM". +Time Complexity - O(n log n) +https://medium.com/@nihardudhat2000/job-sequencing-with-deadline-17ddbb5890b5 +""" from dataclasses import dataclass from operator import attrgetter @@ -11,6 +26,24 @@ def max_tasks(tasks_info: list[tuple[int, int]]) -> list[int]: + """ + Create a list of Task objects that are sorted so the highest rewards come first. + Return a list of those task ids that can be completed before i becomes too high. + >>> max_tasks([(4, 20), (1, 10), (1, 40), (1, 30)]) + [2, 0] + >>> max_tasks([(1, 10), (2, 20), (3, 30), (2, 40)]) + [3, 2] + >>> max_tasks([(9, 10)]) + [0] + >>> max_tasks([(-9, 10)]) + [] + >>> max_tasks([]) + [] + >>> max_tasks([(0, 10), (0, 20), (0, 30), (0, 40)]) + [] + >>> max_tasks([(-1, 10), (-2, 20), (-3, 30), (-4, 40)]) + [] + """ tasks = sorted( ( Task(task_id, deadline, reward) @@ -27,4 +60,4 @@ doctest.testmod() print(f"{max_tasks([(4, 20), (1, 10), (1, 40), (1, 30)]) = }") - print(f"{max_tasks([(1, 10), (2, 20), (3, 30), (2, 40)]) = }")+ print(f"{max_tasks([(1, 10), (2, 20), (3, 30), (2, 40)]) = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/scheduling/job_sequence_with_deadline.py
Write docstrings for algorithm functions
# Implementation of First Come First Served scheduling algorithm # In this Algorithm we just care about the order that the processes arrived # without carring about their duration time # https://en.wikipedia.org/wiki/Scheduling_(computing)#First_come,_first_served from __future__ import annotations def calculate_waiting_times(duration_times: list[int]) -> list[int]: waiting_times = [0] * len(duration_times) for i in range(1, len(duration_times)): waiting_times[i] = duration_times[i - 1] + waiting_times[i - 1] return waiting_times def calculate_turnaround_times( duration_times: list[int], waiting_times: list[int] ) -> list[int]: return [ duration_time + waiting_times[i] for i, duration_time in enumerate(duration_times) ] def calculate_average_turnaround_time(turnaround_times: list[int]) -> float: return sum(turnaround_times) / len(turnaround_times) def calculate_average_waiting_time(waiting_times: list[int]) -> float: return sum(waiting_times) / len(waiting_times) if __name__ == "__main__": # process id's processes = [1, 2, 3] # ensure that we actually have processes if len(processes) == 0: print("Zero amount of processes") raise SystemExit(0) # duration time of all processes duration_times = [19, 8, 9] # ensure we can match each id to a duration time if len(duration_times) != len(processes): print("Unable to match all id's with their duration time") raise SystemExit(0) # get the waiting times and the turnaround times waiting_times = calculate_waiting_times(duration_times) turnaround_times = calculate_turnaround_times(duration_times, waiting_times) # get the average times average_waiting_time = calculate_average_waiting_time(waiting_times) average_turnaround_time = calculate_average_turnaround_time(turnaround_times) # print all the results print("Process ID\tDuration Time\tWaiting Time\tTurnaround Time") for i, process in enumerate(processes): print( f"{process}\t\t{duration_times[i]}\t\t{waiting_times[i]}\t\t" f"{turnaround_times[i]}" ) print(f"Average waiting time = {average_waiting_time}") print(f"Average turn around time = {average_turnaround_time}")
--- +++ @@ -6,6 +6,17 @@ def calculate_waiting_times(duration_times: list[int]) -> list[int]: + """ + This function calculates the waiting time of some processes that have a + specified duration time. + Return: The waiting time for each process. + >>> calculate_waiting_times([5, 10, 15]) + [0, 5, 15] + >>> calculate_waiting_times([1, 2, 3, 4, 5]) + [0, 1, 3, 6, 10] + >>> calculate_waiting_times([10, 3]) + [0, 10] + """ waiting_times = [0] * len(duration_times) for i in range(1, len(duration_times)): waiting_times[i] = duration_times[i - 1] + waiting_times[i - 1] @@ -15,6 +26,18 @@ def calculate_turnaround_times( duration_times: list[int], waiting_times: list[int] ) -> list[int]: + """ + This function calculates the turnaround time of some processes. + Return: The time difference between the completion time and the + arrival time. + Practically waiting_time + duration_time + >>> calculate_turnaround_times([5, 10, 15], [0, 5, 15]) + [5, 15, 30] + >>> calculate_turnaround_times([1, 2, 3, 4, 5], [0, 1, 3, 6, 10]) + [1, 3, 6, 10, 15] + >>> calculate_turnaround_times([10, 3], [0, 10]) + [10, 13] + """ return [ duration_time + waiting_times[i] for i, duration_time in enumerate(duration_times) @@ -22,10 +45,30 @@ def calculate_average_turnaround_time(turnaround_times: list[int]) -> float: + """ + This function calculates the average of the turnaround times + Return: The average of the turnaround times. + >>> calculate_average_turnaround_time([0, 5, 16]) + 7.0 + >>> calculate_average_turnaround_time([1, 5, 8, 12]) + 6.5 + >>> calculate_average_turnaround_time([10, 24]) + 17.0 + """ return sum(turnaround_times) / len(turnaround_times) def calculate_average_waiting_time(waiting_times: list[int]) -> float: + """ + This function calculates the average of the waiting times + Return: The average of the waiting times. + >>> calculate_average_waiting_time([0, 5, 16]) + 7.0 + >>> calculate_average_waiting_time([1, 5, 8, 12]) + 6.5 + >>> calculate_average_waiting_time([10, 24]) + 17.0 + """ return sum(waiting_times) / len(waiting_times) @@ -62,4 +105,4 @@ f"{turnaround_times[i]}" ) print(f"Average waiting time = {average_waiting_time}") - print(f"Average turn around time = {average_turnaround_time}")+ print(f"Average turn around time = {average_turnaround_time}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/scheduling/first_come_first_served.py
Add docstrings to incomplete code
from __future__ import annotations from statistics import mean def calculate_waiting_times(burst_times: list[int]) -> list[int]: quantum = 2 rem_burst_times = list(burst_times) waiting_times = [0] * len(burst_times) t = 0 while True: done = True for i, burst_time in enumerate(burst_times): if rem_burst_times[i] > 0: done = False if rem_burst_times[i] > quantum: t += quantum rem_burst_times[i] -= quantum else: t += rem_burst_times[i] waiting_times[i] = t - burst_time rem_burst_times[i] = 0 if done is True: return waiting_times def calculate_turn_around_times( burst_times: list[int], waiting_times: list[int] ) -> list[int]: return [burst + waiting for burst, waiting in zip(burst_times, waiting_times)] if __name__ == "__main__": burst_times = [3, 5, 7] waiting_times = calculate_waiting_times(burst_times) turn_around_times = calculate_turn_around_times(burst_times, waiting_times) print("Process ID \tBurst Time \tWaiting Time \tTurnaround Time") for i, burst_time in enumerate(burst_times): print( f" {i + 1}\t\t {burst_time}\t\t {waiting_times[i]}\t\t " f"{turn_around_times[i]}" ) print(f"\nAverage waiting time = {mean(waiting_times):.5f}") print(f"Average turn around time = {mean(turn_around_times):.5f}")
--- +++ @@ -1,45 +1,67 @@- -from __future__ import annotations - -from statistics import mean - - -def calculate_waiting_times(burst_times: list[int]) -> list[int]: - quantum = 2 - rem_burst_times = list(burst_times) - waiting_times = [0] * len(burst_times) - t = 0 - while True: - done = True - for i, burst_time in enumerate(burst_times): - if rem_burst_times[i] > 0: - done = False - if rem_burst_times[i] > quantum: - t += quantum - rem_burst_times[i] -= quantum - else: - t += rem_burst_times[i] - waiting_times[i] = t - burst_time - rem_burst_times[i] = 0 - if done is True: - return waiting_times - - -def calculate_turn_around_times( - burst_times: list[int], waiting_times: list[int] -) -> list[int]: - return [burst + waiting for burst, waiting in zip(burst_times, waiting_times)] - - -if __name__ == "__main__": - burst_times = [3, 5, 7] - waiting_times = calculate_waiting_times(burst_times) - turn_around_times = calculate_turn_around_times(burst_times, waiting_times) - print("Process ID \tBurst Time \tWaiting Time \tTurnaround Time") - for i, burst_time in enumerate(burst_times): - print( - f" {i + 1}\t\t {burst_time}\t\t {waiting_times[i]}\t\t " - f"{turn_around_times[i]}" - ) - print(f"\nAverage waiting time = {mean(waiting_times):.5f}") - print(f"Average turn around time = {mean(turn_around_times):.5f}")+""" +Round Robin is a scheduling algorithm. +In Round Robin each process is assigned a fixed time slot in a cyclic way. +https://en.wikipedia.org/wiki/Round-robin_scheduling +""" + +from __future__ import annotations + +from statistics import mean + + +def calculate_waiting_times(burst_times: list[int]) -> list[int]: + """ + Calculate the waiting times of a list of processes that have a specified duration. + + Return: The waiting time for each process. + >>> calculate_waiting_times([10, 5, 8]) + [13, 10, 13] + >>> calculate_waiting_times([4, 6, 3, 1]) + [5, 8, 9, 6] + >>> calculate_waiting_times([12, 2, 10]) + [12, 2, 12] + """ + quantum = 2 + rem_burst_times = list(burst_times) + waiting_times = [0] * len(burst_times) + t = 0 + while True: + done = True + for i, burst_time in enumerate(burst_times): + if rem_burst_times[i] > 0: + done = False + if rem_burst_times[i] > quantum: + t += quantum + rem_burst_times[i] -= quantum + else: + t += rem_burst_times[i] + waiting_times[i] = t - burst_time + rem_burst_times[i] = 0 + if done is True: + return waiting_times + + +def calculate_turn_around_times( + burst_times: list[int], waiting_times: list[int] +) -> list[int]: + """ + >>> calculate_turn_around_times([1, 2, 3, 4], [0, 1, 3]) + [1, 3, 6] + >>> calculate_turn_around_times([10, 3, 7], [10, 6, 11]) + [20, 9, 18] + """ + return [burst + waiting for burst, waiting in zip(burst_times, waiting_times)] + + +if __name__ == "__main__": + burst_times = [3, 5, 7] + waiting_times = calculate_waiting_times(burst_times) + turn_around_times = calculate_turn_around_times(burst_times, waiting_times) + print("Process ID \tBurst Time \tWaiting Time \tTurnaround Time") + for i, burst_time in enumerate(burst_times): + print( + f" {i + 1}\t\t {burst_time}\t\t {waiting_times[i]}\t\t " + f"{turn_around_times[i]}" + ) + print(f"\nAverage waiting time = {mean(waiting_times):.5f}") + print(f"Average turn around time = {mean(turn_around_times):.5f}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/scheduling/round_robin.py
Add missing documentation to my Python functions
#!/usr/bin/env python3 from __future__ import annotations def bucket_sort(my_list: list, bucket_count: int = 10) -> list: if len(my_list) == 0 or bucket_count <= 0: return [] min_value, max_value = min(my_list), max(my_list) if min_value == max_value: return my_list bucket_size = (max_value - min_value) / bucket_count buckets: list[list] = [[] for _ in range(bucket_count)] for val in my_list: index = min(int((val - min_value) / bucket_size), bucket_count - 1) buckets[index].append(val) return [val for bucket in buckets for val in sorted(bucket)] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15] assert bucket_sort([1.1, 1.2, -1.2, 0, 2.4]) == [-1.2, 0, 1.1, 1.2, 2.4] assert bucket_sort([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5] assert bucket_sort([-5, -1, -6, -2]) == [-6, -5, -2, -1]
--- +++ @@ -1,9 +1,77 @@ #!/usr/bin/env python3 +""" +Illustrate how to implement bucket sort algorithm. + +Author: OMKAR PATHAK +This program will illustrate how to implement bucket sort algorithm + +Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works +by distributing the elements of an array into a number of buckets. +Each bucket is then sorted individually, either using a different sorting +algorithm, or by recursively applying the bucket sorting algorithm. It is a +distribution sort, and is a cousin of radix sort in the most to least +significant digit flavour. +Bucket sort is a generalization of pigeonhole sort. Bucket sort can be +implemented with comparisons and therefore can also be considered a +comparison sort algorithm. The computational complexity estimates involve the +number of buckets. + +Time Complexity of Solution: +Worst case scenario occurs when all the elements are placed in a single bucket. +The overall performance would then be dominated by the algorithm used to sort each +bucket. In this case, O(n log n), because of TimSort + +Average Case O(n + (n^2)/k + k), where k is the number of buckets + +If k = O(n), time complexity is O(n) + +Source: https://en.wikipedia.org/wiki/Bucket_sort +""" from __future__ import annotations def bucket_sort(my_list: list, bucket_count: int = 10) -> list: + """ + >>> data = [-1, 2, -5, 0] + >>> bucket_sort(data) == sorted(data) + True + >>> data = [9, 8, 7, 6, -12] + >>> bucket_sort(data) == sorted(data) + True + >>> data = [.4, 1.2, .1, .2, -.9] + >>> bucket_sort(data) == sorted(data) + True + >>> bucket_sort([]) == sorted([]) + True + >>> data = [-1e10, 1e10] + >>> bucket_sort(data) == sorted(data) + True + >>> import random + >>> collection = random.sample(range(-50, 50), 50) + >>> bucket_sort(collection) == sorted(collection) + True + >>> data = [1, 2, 2, 1, 1, 3] + >>> bucket_sort(data) == sorted(data) + True + >>> data = [5, 5, 5, 5, 5] + >>> bucket_sort(data) == sorted(data) + True + >>> data = [1000, -1000, 500, -500, 0] + >>> bucket_sort(data) == sorted(data) + True + >>> data = [5.5, 2.2, -1.1, 3.3, 0.0] + >>> bucket_sort(data) == sorted(data) + True + >>> bucket_sort([1]) == [1] + True + >>> data = [-1.1, -1.5, -3.4, 2.5, 3.6, -3.3] + >>> bucket_sort(data) == sorted(data) + True + >>> data = [9, 2, 7, 1, 5] + >>> bucket_sort(data) == sorted(data) + True + """ if len(my_list) == 0 or bucket_count <= 0: return [] @@ -30,4 +98,4 @@ assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15] assert bucket_sort([1.1, 1.2, -1.2, 0, 2.4]) == [-1.2, 0, 1.1, 1.2, 2.4] assert bucket_sort([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5] - assert bucket_sort([-5, -1, -6, -2]) == [-6, -5, -2, -1]+ assert bucket_sort([-5, -1, -6, -2]) == [-6, -5, -2, -1]
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/bucket_sort.py
Include argument descriptions in docstrings
import random def _partition(data: list, pivot) -> tuple: less, equal, greater = [], [], [] for element in data: if element < pivot: less.append(element) elif element > pivot: greater.append(element) else: equal.append(element) return less, equal, greater def quick_select(items: list, index: int): # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(items) or index < 0: return None pivot = items[random.randint(0, len(items) - 1)] count = 0 smaller, equal, larger = _partition(items, pivot) count = len(equal) m = len(smaller) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(smaller, index) # must be in larger else: return quick_select(larger, index - (m + count)) def median(items: list): mid, rem = divmod(len(items), 2) if rem != 0: return quick_select(items=items, index=mid) else: low_mid = quick_select(items=items, index=mid - 1) high_mid = quick_select(items=items, index=mid) return (low_mid + high_mid) / 2
--- +++ @@ -1,8 +1,21 @@+""" +A Python implementation of the quick select algorithm, which is efficient for +calculating the value that would appear in the index of a list if it would be +sorted, even if it is not already sorted +https://en.wikipedia.org/wiki/Quickselect +""" import random def _partition(data: list, pivot) -> tuple: + """ + Three way partition the data into smaller, equal and greater lists, + in relationship to the pivot + :param data: The data to be sorted (a list) + :param pivot: The value to partition the data on + :return: Three list: smaller, equal and greater + """ less, equal, greater = [], [], [] for element in data: if element < pivot: @@ -15,6 +28,16 @@ def quick_select(items: list, index: int): + """ + >>> quick_select([2, 4, 5, 7, 899, 54, 32], 5) + 54 + >>> quick_select([2, 4, 5, 7, 899, 54, 32], 1) + 4 + >>> quick_select([5, 4, 3, 2], 2) + 4 + >>> quick_select([3, 5, 7, 10, 2, 12], 3) + 7 + """ # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) @@ -40,10 +63,22 @@ def median(items: list): + """ + One common application of Quickselect is finding the median, which is + the middle element (or average of the two middle elements) in a sorted dataset. + It works efficiently on unsorted lists by partially sorting the data without + fully sorting the entire list. + + >>> median([3, 2, 2, 9, 9]) + 3 + + >>> median([2, 2, 9, 9, 9, 3]) + 6.0 + """ mid, rem = divmod(len(items), 2) if rem != 0: return quick_select(items=items, index=mid) else: low_mid = quick_select(items=items, index=mid - 1) high_mid = quick_select(items=items, index=mid) - return (low_mid + high_mid) / 2+ return (low_mid + high_mid) / 2
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/quick_select.py
Create documentation for each function signature
#!/usr/bin/env python3 import bisect from itertools import pairwise def bisect_left( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> int: if hi < 0: hi = len(sorted_collection) while lo < hi: mid = lo + (hi - lo) // 2 if sorted_collection[mid] < item: lo = mid + 1 else: hi = mid return lo def bisect_right( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> int: if hi < 0: hi = len(sorted_collection) while lo < hi: mid = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: lo = mid + 1 else: hi = mid return lo def insort_left( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> None: sorted_collection.insert(bisect_left(sorted_collection, item, lo, hi), item) def insort_right( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> None: sorted_collection.insert(bisect_right(sorted_collection, item, lo, hi), item) def binary_search(sorted_collection: list[int], item: int) -> int: if any(a > b for a, b in pairwise(sorted_collection)): raise ValueError("sorted_collection must be sorted in ascending order") left = 0 right = len(sorted_collection) - 1 while left <= right: midpoint = left + (right - left) // 2 current_item = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: right = midpoint - 1 else: left = midpoint + 1 return -1 def binary_search_std_lib(sorted_collection: list[int], item: int) -> int: if list(sorted_collection) != sorted(sorted_collection): raise ValueError("sorted_collection must be sorted in ascending order") index = bisect.bisect_left(sorted_collection, item) if index != len(sorted_collection) and sorted_collection[index] == item: return index return -1 def binary_search_with_duplicates(sorted_collection: list[int], item: int) -> list[int]: if list(sorted_collection) != sorted(sorted_collection): raise ValueError("sorted_collection must be sorted in ascending order") def lower_bound(sorted_collection: list[int], item: int) -> int: left = 0 right = len(sorted_collection) while left < right: midpoint = left + (right - left) // 2 current_item = sorted_collection[midpoint] if current_item < item: left = midpoint + 1 else: right = midpoint return left def upper_bound(sorted_collection: list[int], item: int) -> int: left = 0 right = len(sorted_collection) while left < right: midpoint = left + (right - left) // 2 current_item = sorted_collection[midpoint] if current_item <= item: left = midpoint + 1 else: right = midpoint return left left = lower_bound(sorted_collection, item) right = upper_bound(sorted_collection, item) if left == len(sorted_collection) or sorted_collection[left] != item: return [] return list(range(left, right)) def binary_search_by_recursion( sorted_collection: list[int], item: int, left: int = 0, right: int = -1 ) -> int: if right < 0: right = len(sorted_collection) - 1 if list(sorted_collection) != sorted(sorted_collection): raise ValueError("sorted_collection must be sorted in ascending order") if right < left: return -1 midpoint = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1) else: return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right) def exponential_search(sorted_collection: list[int], item: int) -> int: if list(sorted_collection) != sorted(sorted_collection): raise ValueError("sorted_collection must be sorted in ascending order") bound = 1 while bound < len(sorted_collection) and sorted_collection[bound] < item: bound *= 2 left = bound // 2 right = min(bound, len(sorted_collection) - 1) last_result = binary_search_by_recursion( sorted_collection=sorted_collection, item=item, left=left, right=right ) if last_result is None: return -1 return last_result searches = ( # Fastest to slowest... binary_search_std_lib, binary_search, exponential_search, binary_search_by_recursion, ) if __name__ == "__main__": import doctest import timeit doctest.testmod() for search in searches: name = f"{search.__name__:>26}" print(f"{name}: {search([0, 5, 7, 10, 15], 10) = }") # type: ignore[operator] print("\nBenchmarks...") setup = "collection = range(1000)" for search in searches: name = search.__name__ print( f"{name:>26}:", timeit.timeit( f"{name}(collection, 500)", setup=setup, number=5_000, globals=globals() ), ) user_input = input("\nEnter numbers separated by comma: ").strip() collection = sorted(int(item) for item in user_input.split(",")) target = int(input("Enter a single number to be found in the list: ")) result = binary_search(sorted_collection=collection, item=target) if result == -1: print(f"{target} was not found in {collection}.") else: print(f"{target} was found at position {result} of {collection}.")
--- +++ @@ -1,5 +1,14 @@ #!/usr/bin/env python3 +""" +Pure Python implementations of binary search algorithms + +For doctests run the following command: +python3 -m doctest -v binary_search.py + +For manual testing run: +python3 binary_search.py +""" import bisect from itertools import pairwise @@ -8,6 +17,32 @@ def bisect_left( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> int: + """ + Locates the first element in a sorted array that is larger or equal to a given + value. + + It has the same interface as + https://docs.python.org/3/library/bisect.html#bisect.bisect_left . + + :param sorted_collection: some ascending sorted collection with comparable items + :param item: item to bisect + :param lo: lowest index to consider (as in sorted_collection[lo:hi]) + :param hi: past the highest index to consider (as in sorted_collection[lo:hi]) + :return: index i such that all values in sorted_collection[lo:i] are < item and all + values in sorted_collection[i:hi] are >= item. + + Examples: + >>> bisect_left([0, 5, 7, 10, 15], 0) + 0 + >>> bisect_left([0, 5, 7, 10, 15], 6) + 2 + >>> bisect_left([0, 5, 7, 10, 15], 20) + 5 + >>> bisect_left([0, 5, 7, 10, 15], 15, 1, 3) + 3 + >>> bisect_left([0, 5, 7, 10, 15], 6, 2) + 2 + """ if hi < 0: hi = len(sorted_collection) @@ -24,6 +59,31 @@ def bisect_right( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> int: + """ + Locates the first element in a sorted array that is larger than a given value. + + It has the same interface as + https://docs.python.org/3/library/bisect.html#bisect.bisect_right . + + :param sorted_collection: some ascending sorted collection with comparable items + :param item: item to bisect + :param lo: lowest index to consider (as in sorted_collection[lo:hi]) + :param hi: past the highest index to consider (as in sorted_collection[lo:hi]) + :return: index i such that all values in sorted_collection[lo:i] are <= item and + all values in sorted_collection[i:hi] are > item. + + Examples: + >>> bisect_right([0, 5, 7, 10, 15], 0) + 1 + >>> bisect_right([0, 5, 7, 10, 15], 15) + 5 + >>> bisect_right([0, 5, 7, 10, 15], 6) + 2 + >>> bisect_right([0, 5, 7, 10, 15], 15, 1, 3) + 3 + >>> bisect_right([0, 5, 7, 10, 15], 6, 2) + 2 + """ if hi < 0: hi = len(sorted_collection) @@ -40,16 +100,103 @@ def insort_left( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> None: + """ + Inserts a given value into a sorted array before other values with the same value. + + It has the same interface as + https://docs.python.org/3/library/bisect.html#bisect.insort_left . + + :param sorted_collection: some ascending sorted collection with comparable items + :param item: item to insert + :param lo: lowest index to consider (as in sorted_collection[lo:hi]) + :param hi: past the highest index to consider (as in sorted_collection[lo:hi]) + + Examples: + >>> sorted_collection = [0, 5, 7, 10, 15] + >>> insort_left(sorted_collection, 6) + >>> sorted_collection + [0, 5, 6, 7, 10, 15] + >>> sorted_collection = [(0, 0), (5, 5), (7, 7), (10, 10), (15, 15)] + >>> item = (5, 5) + >>> insort_left(sorted_collection, item) + >>> sorted_collection + [(0, 0), (5, 5), (5, 5), (7, 7), (10, 10), (15, 15)] + >>> item is sorted_collection[1] + True + >>> item is sorted_collection[2] + False + >>> sorted_collection = [0, 5, 7, 10, 15] + >>> insort_left(sorted_collection, 20) + >>> sorted_collection + [0, 5, 7, 10, 15, 20] + >>> sorted_collection = [0, 5, 7, 10, 15] + >>> insort_left(sorted_collection, 15, 1, 3) + >>> sorted_collection + [0, 5, 7, 15, 10, 15] + """ sorted_collection.insert(bisect_left(sorted_collection, item, lo, hi), item) def insort_right( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> None: + """ + Inserts a given value into a sorted array after other values with the same value. + + It has the same interface as + https://docs.python.org/3/library/bisect.html#bisect.insort_right . + + :param sorted_collection: some ascending sorted collection with comparable items + :param item: item to insert + :param lo: lowest index to consider (as in sorted_collection[lo:hi]) + :param hi: past the highest index to consider (as in sorted_collection[lo:hi]) + + Examples: + >>> sorted_collection = [0, 5, 7, 10, 15] + >>> insort_right(sorted_collection, 6) + >>> sorted_collection + [0, 5, 6, 7, 10, 15] + >>> sorted_collection = [(0, 0), (5, 5), (7, 7), (10, 10), (15, 15)] + >>> item = (5, 5) + >>> insort_right(sorted_collection, item) + >>> sorted_collection + [(0, 0), (5, 5), (5, 5), (7, 7), (10, 10), (15, 15)] + >>> item is sorted_collection[1] + False + >>> item is sorted_collection[2] + True + >>> sorted_collection = [0, 5, 7, 10, 15] + >>> insort_right(sorted_collection, 20) + >>> sorted_collection + [0, 5, 7, 10, 15, 20] + >>> sorted_collection = [0, 5, 7, 10, 15] + >>> insort_right(sorted_collection, 15, 1, 3) + >>> sorted_collection + [0, 5, 7, 15, 10, 15] + """ sorted_collection.insert(bisect_right(sorted_collection, item, lo, hi), item) def binary_search(sorted_collection: list[int], item: int) -> int: + """Pure implementation of a binary search algorithm in Python + + Be careful collection must be ascending sorted otherwise, the result will be + unpredictable + + :param sorted_collection: some ascending sorted collection with comparable items + :param item: item value to search + :return: index of the found item or -1 if the item is not found + + Examples: + >>> binary_search([0, 5, 7, 10, 15], 0) + 0 + >>> binary_search([0, 5, 7, 10, 15], 15) + 4 + >>> binary_search([0, 5, 7, 10, 15], 5) + 1 + >>> binary_search([0, 5, 7, 10, 15], 6) + -1 + """ if any(a > b for a, b in pairwise(sorted_collection)): raise ValueError("sorted_collection must be sorted in ascending order") left = 0 @@ -68,6 +215,25 @@ def binary_search_std_lib(sorted_collection: list[int], item: int) -> int: + """Pure implementation of a binary search algorithm in Python using stdlib + + Be careful collection must be ascending sorted otherwise, the result will be + unpredictable + + :param sorted_collection: some ascending sorted collection with comparable items + :param item: item value to search + :return: index of the found item or -1 if the item is not found + + Examples: + >>> binary_search_std_lib([0, 5, 7, 10, 15], 0) + 0 + >>> binary_search_std_lib([0, 5, 7, 10, 15], 15) + 4 + >>> binary_search_std_lib([0, 5, 7, 10, 15], 5) + 1 + >>> binary_search_std_lib([0, 5, 7, 10, 15], 6) + -1 + """ if list(sorted_collection) != sorted(sorted_collection): raise ValueError("sorted_collection must be sorted in ascending order") index = bisect.bisect_left(sorted_collection, item) @@ -77,10 +243,42 @@ def binary_search_with_duplicates(sorted_collection: list[int], item: int) -> list[int]: + """Pure implementation of a binary search algorithm in Python that supports + duplicates. + + Resources used: + https://stackoverflow.com/questions/13197552/using-binary-search-with-sorted-array-with-duplicates + + The collection must be sorted in ascending order; otherwise the result will be + unpredictable. If the target appears multiple times, this function returns a + list of all indexes where the target occurs. If the target is not found, + this function returns an empty list. + + :param sorted_collection: some ascending sorted collection with comparable items + :param item: item value to search for + :return: a list of indexes where the item is found (empty list if not found) + + Examples: + >>> binary_search_with_duplicates([0, 5, 7, 10, 15], 0) + [0] + >>> binary_search_with_duplicates([0, 5, 7, 10, 15], 15) + [4] + >>> binary_search_with_duplicates([1, 2, 2, 2, 3], 2) + [1, 2, 3] + >>> binary_search_with_duplicates([1, 2, 2, 2, 3], 4) + [] + """ if list(sorted_collection) != sorted(sorted_collection): raise ValueError("sorted_collection must be sorted in ascending order") def lower_bound(sorted_collection: list[int], item: int) -> int: + """ + Returns the index of the first element greater than or equal to the item. + + :param sorted_collection: The sorted list to search. + :param item: The item to find the lower bound for. + :return: The index where the item can be inserted while maintaining order. + """ left = 0 right = len(sorted_collection) while left < right: @@ -93,6 +291,13 @@ return left def upper_bound(sorted_collection: list[int], item: int) -> int: + """ + Returns the index of the first element strictly greater than the item. + + :param sorted_collection: The sorted list to search. + :param item: The item to find the upper bound for. + :return: The index where the item can be inserted after all existing instances. + """ left = 0 right = len(sorted_collection) while left < right: @@ -115,6 +320,26 @@ def binary_search_by_recursion( sorted_collection: list[int], item: int, left: int = 0, right: int = -1 ) -> int: + """Pure implementation of a binary search algorithm in Python by recursion + + Be careful collection must be ascending sorted otherwise, the result will be + unpredictable + First recursion should be started with left=0 and right=(len(sorted_collection)-1) + + :param sorted_collection: some ascending sorted collection with comparable items + :param item: item value to search + :return: index of the found item or -1 if the item is not found + + Examples: + >>> binary_search_by_recursion([0, 5, 7, 10, 15], 0, 0, 4) + 0 + >>> binary_search_by_recursion([0, 5, 7, 10, 15], 15, 0, 4) + 4 + >>> binary_search_by_recursion([0, 5, 7, 10, 15], 5, 0, 4) + 1 + >>> binary_search_by_recursion([0, 5, 7, 10, 15], 6, 0, 4) + -1 + """ if right < 0: right = len(sorted_collection) - 1 if list(sorted_collection) != sorted(sorted_collection): @@ -133,6 +358,29 @@ def exponential_search(sorted_collection: list[int], item: int) -> int: + """Pure implementation of an exponential search algorithm in Python + Resources used: + https://en.wikipedia.org/wiki/Exponential_search + + Be careful collection must be ascending sorted otherwise, result will be + unpredictable + + :param sorted_collection: some ascending sorted collection with comparable items + :param item: item value to search + :return: index of the found item or -1 if the item is not found + + the order of this algorithm is O(lg I) where I is index position of item if exist + + Examples: + >>> exponential_search([0, 5, 7, 10, 15], 0) + 0 + >>> exponential_search([0, 5, 7, 10, 15], 15) + 4 + >>> exponential_search([0, 5, 7, 10, 15], 5) + 1 + >>> exponential_search([0, 5, 7, 10, 15], 6) + -1 + """ if list(sorted_collection) != sorted(sorted_collection): raise ValueError("sorted_collection must be sorted in ascending order") bound = 1 @@ -183,4 +431,4 @@ if result == -1: print(f"{target} was not found in {collection}.") else: - print(f"{target} was found at position {result} of {collection}.")+ print(f"{target} was found at position {result} of {collection}.")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/binary_search.py
Write reusable docstrings
from collections import deque class Process: def __init__(self, process_name: str, arrival_time: int, burst_time: int) -> None: self.process_name = process_name # process name self.arrival_time = arrival_time # arrival time of the process # completion time of finished process or last interrupted time self.stop_time = arrival_time self.burst_time = burst_time # remaining burst time self.waiting_time = 0 # total time of the process wait in ready queue self.turnaround_time = 0 # time from arrival time to completion time class MLFQ: def __init__( self, number_of_queues: int, time_slices: list[int], queue: deque[Process], current_time: int, ) -> None: # total number of mlfq's queues self.number_of_queues = number_of_queues # time slice of queues that round robin algorithm applied self.time_slices = time_slices # unfinished process is in this ready_queue self.ready_queue = queue # current time self.current_time = current_time # finished process is in this sequence queue self.finish_queue: deque[Process] = deque() def calculate_sequence_of_finish_queue(self) -> list[str]: sequence = [] for i in range(len(self.finish_queue)): sequence.append(self.finish_queue[i].process_name) return sequence def calculate_waiting_time(self, queue: list[Process]) -> list[int]: waiting_times = [] for i in range(len(queue)): waiting_times.append(queue[i].waiting_time) return waiting_times def calculate_turnaround_time(self, queue: list[Process]) -> list[int]: turnaround_times = [] for i in range(len(queue)): turnaround_times.append(queue[i].turnaround_time) return turnaround_times def calculate_completion_time(self, queue: list[Process]) -> list[int]: completion_times = [] for i in range(len(queue)): completion_times.append(queue[i].stop_time) return completion_times def calculate_remaining_burst_time_of_processes( self, queue: deque[Process] ) -> list[int]: return [q.burst_time for q in queue] def update_waiting_time(self, process: Process) -> int: process.waiting_time += self.current_time - process.stop_time return process.waiting_time def first_come_first_served(self, ready_queue: deque[Process]) -> deque[Process]: finished: deque[Process] = deque() # sequence deque of finished process while len(ready_queue) != 0: cp = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(cp) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 cp.burst_time = 0 # set the process's turnaround time because it is finished cp.turnaround_time = self.current_time - cp.arrival_time # set the completion time cp.stop_time = self.current_time # add the process to queue that has finished queue finished.append(cp) self.finish_queue.extend(finished) # add finished process to finish queue # FCFS will finish all remaining processes return finished def round_robin( self, ready_queue: deque[Process], time_slice: int ) -> tuple[deque[Process], deque[Process]]: finished: deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(ready_queue)): cp = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(cp) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time cp.stop_time = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(cp) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished cp.burst_time = 0 # set the finish time cp.stop_time = self.current_time # update the process' turnaround time because it is finished cp.turnaround_time = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(cp) self.finish_queue.extend(finished) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def multi_level_feedback_queue(self) -> deque[Process]: # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1): _finished, self.ready_queue = self.round_robin( self.ready_queue, self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue) return self.finish_queue if __name__ == "__main__": import doctest P1 = Process("P1", 0, 53) P2 = Process("P2", 0, 17) P3 = Process("P3", 0, 68) P4 = Process("P4", 0, 24) number_of_queues = 3 time_slices = [17, 25] queue = deque([P1, P2, P3, P4]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={"queue": deque([P1, P2, P3, P4])}) P1 = Process("P1", 0, 53) P2 = Process("P2", 0, 17) P3 = Process("P3", 0, 68) P4 = Process("P4", 0, 24) number_of_queues = 3 time_slices = [17, 25] queue = deque([P1, P2, P3, P4]) mlfq = MLFQ(number_of_queues, time_slices, queue, 0) finish_queue = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f"waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [P1, P2, P3, P4])}" ) # print completion times of processes(P1, P2, P3, P4) print( f"completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [P1, P2, P3, P4])}" ) # print total turnaround times of processes(P1, P2, P3, P4) print( f"turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [P1, P2, P3, P4])}" ) # print sequence of finished processes print( f"sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}" )
--- +++ @@ -13,6 +13,14 @@ class MLFQ: + """ + MLFQ(Multi Level Feedback Queue) + https://en.wikipedia.org/wiki/Multilevel_feedback_queue + MLFQ has a lot of queues that have different priority + In this MLFQ, + The first Queue(0) to last second Queue(N-2) of MLFQ have Round Robin Algorithm + The last Queue(N-1) has First Come, First Served Algorithm + """ def __init__( self, @@ -33,24 +41,68 @@ self.finish_queue: deque[Process] = deque() def calculate_sequence_of_finish_queue(self) -> list[str]: + """ + This method returns the sequence of finished processes + >>> P1 = Process("P1", 0, 53) + >>> P2 = Process("P2", 0, 17) + >>> P3 = Process("P3", 0, 68) + >>> P4 = Process("P4", 0, 24) + >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) + >>> _ = mlfq.multi_level_feedback_queue() + >>> mlfq.calculate_sequence_of_finish_queue() + ['P2', 'P4', 'P1', 'P3'] + """ sequence = [] for i in range(len(self.finish_queue)): sequence.append(self.finish_queue[i].process_name) return sequence def calculate_waiting_time(self, queue: list[Process]) -> list[int]: + """ + This method calculates waiting time of processes + >>> P1 = Process("P1", 0, 53) + >>> P2 = Process("P2", 0, 17) + >>> P3 = Process("P3", 0, 68) + >>> P4 = Process("P4", 0, 24) + >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) + >>> _ = mlfq.multi_level_feedback_queue() + >>> mlfq.calculate_waiting_time([P1, P2, P3, P4]) + [83, 17, 94, 101] + """ waiting_times = [] for i in range(len(queue)): waiting_times.append(queue[i].waiting_time) return waiting_times def calculate_turnaround_time(self, queue: list[Process]) -> list[int]: + """ + This method calculates turnaround time of processes + >>> P1 = Process("P1", 0, 53) + >>> P2 = Process("P2", 0, 17) + >>> P3 = Process("P3", 0, 68) + >>> P4 = Process("P4", 0, 24) + >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) + >>> _ = mlfq.multi_level_feedback_queue() + >>> mlfq.calculate_turnaround_time([P1, P2, P3, P4]) + [136, 34, 162, 125] + """ turnaround_times = [] for i in range(len(queue)): turnaround_times.append(queue[i].turnaround_time) return turnaround_times def calculate_completion_time(self, queue: list[Process]) -> list[int]: + """ + This method calculates completion time of processes + >>> P1 = Process("P1", 0, 53) + >>> P2 = Process("P2", 0, 17) + >>> P3 = Process("P3", 0, 68) + >>> P4 = Process("P4", 0, 24) + >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) + >>> _ = mlfq.multi_level_feedback_queue() + >>> mlfq.calculate_turnaround_time([P1, P2, P3, P4]) + [136, 34, 162, 125] + """ completion_times = [] for i in range(len(queue)): completion_times.append(queue[i].stop_time) @@ -59,13 +111,56 @@ def calculate_remaining_burst_time_of_processes( self, queue: deque[Process] ) -> list[int]: + """ + This method calculate remaining burst time of processes + >>> P1 = Process("P1", 0, 53) + >>> P2 = Process("P2", 0, 17) + >>> P3 = Process("P3", 0, 68) + >>> P4 = Process("P4", 0, 24) + >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) + >>> finish_queue, ready_queue = mlfq.round_robin(deque([P1, P2, P3, P4]), 17) + >>> mlfq.calculate_remaining_burst_time_of_processes(mlfq.finish_queue) + [0] + >>> mlfq.calculate_remaining_burst_time_of_processes(ready_queue) + [36, 51, 7] + >>> finish_queue, ready_queue = mlfq.round_robin(ready_queue, 25) + >>> mlfq.calculate_remaining_burst_time_of_processes(mlfq.finish_queue) + [0, 0] + >>> mlfq.calculate_remaining_burst_time_of_processes(ready_queue) + [11, 26] + """ return [q.burst_time for q in queue] def update_waiting_time(self, process: Process) -> int: + """ + This method updates waiting times of unfinished processes + >>> P1 = Process("P1", 0, 53) + >>> P2 = Process("P2", 0, 17) + >>> P3 = Process("P3", 0, 68) + >>> P4 = Process("P4", 0, 24) + >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) + >>> mlfq.current_time = 10 + >>> P1.stop_time = 5 + >>> mlfq.update_waiting_time(P1) + 5 + """ process.waiting_time += self.current_time - process.stop_time return process.waiting_time def first_come_first_served(self, ready_queue: deque[Process]) -> deque[Process]: + """ + FCFS(First Come, First Served) + FCFS will be applied to MLFQ's last queue + A first came process will be finished at first + >>> P1 = Process("P1", 0, 53) + >>> P2 = Process("P2", 0, 17) + >>> P3 = Process("P3", 0, 68) + >>> P4 = Process("P4", 0, 24) + >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) + >>> _ = mlfq.first_come_first_served(mlfq.ready_queue) + >>> mlfq.calculate_sequence_of_finish_queue() + ['P1', 'P2', 'P3', 'P4'] + """ finished: deque[Process] = deque() # sequence deque of finished process while len(ready_queue) != 0: cp = ready_queue.popleft() # current process @@ -94,6 +189,20 @@ def round_robin( self, ready_queue: deque[Process], time_slice: int ) -> tuple[deque[Process], deque[Process]]: + """ + RR(Round Robin) + RR will be applied to MLFQ's all queues except last queue + All processes can't use CPU for time more than time_slice + If the process consume CPU up to time_slice, it will go back to ready queue + >>> P1 = Process("P1", 0, 53) + >>> P2 = Process("P2", 0, 17) + >>> P3 = Process("P3", 0, 68) + >>> P4 = Process("P4", 0, 24) + >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) + >>> finish_queue, ready_queue = mlfq.round_robin(mlfq.ready_queue, 17) + >>> mlfq.calculate_sequence_of_finish_queue() + ['P2'] + """ finished: deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(ready_queue)): @@ -132,6 +241,17 @@ return finished, ready_queue def multi_level_feedback_queue(self) -> deque[Process]: + """ + MLFQ(Multi Level Feedback Queue) + >>> P1 = Process("P1", 0, 53) + >>> P2 = Process("P2", 0, 17) + >>> P3 = Process("P3", 0, 68) + >>> P4 = Process("P4", 0, 24) + >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) + >>> finish_queue = mlfq.multi_level_feedback_queue() + >>> mlfq.calculate_sequence_of_finish_queue() + ['P2', 'P4', 'P1', 'P3'] + """ # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1): @@ -189,4 +309,4 @@ print( f"sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}" - )+ )
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/scheduling/multi_level_feedback_queue.py
Add docstrings to make code maintainable
from math import isqrt, log2 def calculate_prime_numbers(max_number: int) -> list[int]: is_prime = [True] * max_number for i in range(2, isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2, max_number, i): is_prime[j] = False return [i for i in range(2, max_number) if is_prime[i]] def solution(base: int = 800800, degree: int = 800800) -> int: upper_bound = degree * log2(base) max_prime = int(upper_bound) prime_numbers = calculate_prime_numbers(max_prime) hybrid_integers_count = 0 left = 0 right = len(prime_numbers) - 1 while left < right: while ( prime_numbers[right] * log2(prime_numbers[left]) + prime_numbers[left] * log2(prime_numbers[right]) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f"{solution() = }")
--- +++ @@ -1,8 +1,25 @@+""" +Project Euler Problem 800: https://projecteuler.net/problem=800 + +An integer of the form p^q q^p with prime numbers p != q is called a hybrid-integer. +For example, 800 = 2^5 5^2 is a hybrid-integer. + +We define C(n) to be the number of hybrid-integers less than or equal to n. +You are given C(800) = 2 and C(800^800) = 10790 + +Find C(800800^800800) +""" from math import isqrt, log2 def calculate_prime_numbers(max_number: int) -> list[int]: + """ + Returns prime numbers below max_number + + >>> calculate_prime_numbers(10) + [2, 3, 5, 7] + """ is_prime = [True] * max_number for i in range(2, isqrt(max_number - 1) + 1): @@ -14,6 +31,15 @@ def solution(base: int = 800800, degree: int = 800800) -> int: + """ + Returns the number of hybrid-integers less than or equal to base^degree + + >>> solution(800, 1) + 2 + + >>> solution(800, 800) + 10790 + """ upper_bound = degree * log2(base) max_prime = int(upper_bound) @@ -36,4 +62,4 @@ if __name__ == "__main__": - print(f"{solution() = }")+ print(f"{solution() = }")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/project_euler/problem_800/sol1.py
Generate consistent docstrings
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def quantum_fourier_transform(number_of_qubits: int = 3) -> qiskit.result.counts.Counts: if isinstance(number_of_qubits, str): raise TypeError("number of qubits must be a integer.") if number_of_qubits <= 0: raise ValueError("number of qubits must be > 0.") if math.floor(number_of_qubits) != number_of_qubits: raise ValueError("number of qubits must be exact integer.") if number_of_qubits > 10: raise ValueError("number of qubits too large to simulate(>10).") qr = QuantumRegister(number_of_qubits, "qr") cr = ClassicalRegister(number_of_qubits, "cr") quantum_circuit = QuantumCircuit(qr, cr) counter = number_of_qubits for i in range(counter): quantum_circuit.h(number_of_qubits - i - 1) counter -= 1 for j in range(counter): quantum_circuit.cp(np.pi / 2 ** (counter - j), j, counter) for k in range(number_of_qubits // 2): quantum_circuit.swap(k, number_of_qubits - k - 1) # measure all the qubits quantum_circuit.measure(qr, cr) # simulate with 10000 shots backend = Aer.get_backend("qasm_simulator") job = execute(quantum_circuit, backend, shots=10000) return job.result().get_counts(quantum_circuit) if __name__ == "__main__": print( f"Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}" )
--- +++ @@ -1,3 +1,15 @@+""" +Build the quantum fourier transform (qft) for a desire +number of quantum bits using Qiskit framework. This +experiment run in IBM Q simulator with 10000 shots. +This circuit can be use as a building block to design +the Shor's algorithm in quantum computing. As well as, +quantum phase estimation among others. +. +References: +https://en.wikipedia.org/wiki/Quantum_Fourier_transform +https://qiskit.org/textbook/ch-algorithms/quantum-fourier-transform.html +""" import math @@ -7,6 +19,42 @@ def quantum_fourier_transform(number_of_qubits: int = 3) -> qiskit.result.counts.Counts: + """ + # >>> quantum_fourier_transform(2) + # {'00': 2500, '01': 2500, '11': 2500, '10': 2500} + # quantum circuit for number_of_qubits = 3: + ┌───┐ + qr_0: ──────■──────────────────────■───────┤ H ├─X─ + │ ┌───┐ │P(π/2) └───┘ │ + qr_1: ──────┼────────■───────┤ H ├─■─────────────┼─ + ┌───┐ │P(π/4) │P(π/2) └───┘ │ + qr_2: ┤ H ├─■────────■───────────────────────────X─ + └───┘ + cr: 3/═════════════════════════════════════════════ + Args: + n : number of qubits + Returns: + qiskit.result.counts.Counts: distribute counts. + + >>> quantum_fourier_transform(2) + {'00': 2500, '01': 2500, '10': 2500, '11': 2500} + >>> quantum_fourier_transform(-1) + Traceback (most recent call last): + ... + ValueError: number of qubits must be > 0. + >>> quantum_fourier_transform('a') + Traceback (most recent call last): + ... + TypeError: number of qubits must be a integer. + >>> quantum_fourier_transform(100) + Traceback (most recent call last): + ... + ValueError: number of qubits too large to simulate(>10). + >>> quantum_fourier_transform(0.5) + Traceback (most recent call last): + ... + ValueError: number of qubits must be exact integer. + """ if isinstance(number_of_qubits, str): raise TypeError("number of qubits must be a integer.") if number_of_qubits <= 0: @@ -45,4 +93,4 @@ print( f"Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}" - )+ )
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/quantum/q_fourier_transform.py
Document all endpoints with docstrings
def interpolation_search(sorted_collection: list[int], item: int) -> int | None: left = 0 right = len(sorted_collection) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left return None point = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(sorted_collection): return None current_item = sorted_collection[point] if current_item == item: return point if point < left: right = left left = point elif point > right: left = right right = point elif item < current_item: right = point - 1 else: left = point + 1 return None def interpolation_search_by_recursion( sorted_collection: list[int], item: int, left: int = 0, right: int | None = None ) -> int | None: if right is None: right = len(sorted_collection) - 1 # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left return None point = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(sorted_collection): return None if sorted_collection[point] == item: return point if point < left: return interpolation_search_by_recursion(sorted_collection, item, point, left) if point > right: return interpolation_search_by_recursion(sorted_collection, item, right, left) if sorted_collection[point] > item: return interpolation_search_by_recursion( sorted_collection, item, left, point - 1 ) return interpolation_search_by_recursion(sorted_collection, item, point + 1, right) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,6 +1,44 @@+""" +This is pure Python implementation of interpolation search algorithm +""" def interpolation_search(sorted_collection: list[int], item: int) -> int | None: + """ + Searches for an item in a sorted collection by interpolation search algorithm. + + Args: + sorted_collection: sorted list of integers + item: item value to search + + Returns: + int: The index of the found item, or None if the item is not found. + Examples: + >>> interpolation_search([1, 2, 3, 4, 5], 2) + 1 + >>> interpolation_search([1, 2, 3, 4, 5], 4) + 3 + >>> interpolation_search([1, 2, 3, 4, 5], 6) is None + True + >>> interpolation_search([], 1) is None + True + >>> interpolation_search([100], 100) + 0 + >>> interpolation_search([1, 2, 3, 4, 5], 0) is None + True + >>> interpolation_search([1, 2, 3, 4, 5], 7) is None + True + >>> interpolation_search([1, 2, 3, 4, 5], 2) + 1 + >>> interpolation_search([1, 2, 3, 4, 5], 0) is None + True + >>> interpolation_search([1, 2, 3, 4, 5], 7) is None + True + >>> interpolation_search([1, 2, 3, 4, 5], 2) + 1 + >>> interpolation_search([5, 5, 5, 5, 5], 3) is None + True + """ left = 0 right = len(sorted_collection) - 1 @@ -38,6 +76,32 @@ def interpolation_search_by_recursion( sorted_collection: list[int], item: int, left: int = 0, right: int | None = None ) -> int | None: + """Pure implementation of interpolation search algorithm in Python by recursion + Be careful collection must be ascending sorted, otherwise result will be + unpredictable + First recursion should be started with left=0 and right=(len(sorted_collection)-1) + + Args: + sorted_collection: some sorted collection with comparable items + item: item value to search + left: left index in collection + right: right index in collection + + Returns: + index of item in collection or None if item is not present + + Examples: + >>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 0) + 0 + >>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 15) + 4 + >>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 5) + 1 + >>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 100) is None + True + >>> interpolation_search_by_recursion([5, 5, 5, 5, 5], 3) is None + True + """ if right is None: right = len(sorted_collection) - 1 # avoid divided by 0 during interpolation @@ -70,4 +134,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/interpolation_search.py
Add docstrings for utility scripts
#!/usr/bin/env python3 from __future__ import annotations def binary_search_by_recursion( sorted_collection: list[int], item: int, left: int = 0, right: int = -1 ) -> int: if right < 0: right = len(sorted_collection) - 1 if list(sorted_collection) != sorted(sorted_collection): raise ValueError("sorted_collection must be sorted in ascending order") if right < left: return -1 midpoint = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1) else: return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right) def exponential_search(sorted_collection: list[int], item: int) -> int: if list(sorted_collection) != sorted(sorted_collection): raise ValueError("sorted_collection must be sorted in ascending order") if sorted_collection[0] == item: return 0 bound = 1 while bound < len(sorted_collection) and sorted_collection[bound] < item: bound *= 2 left = bound // 2 right = min(bound, len(sorted_collection) - 1) return binary_search_by_recursion(sorted_collection, item, left, right) if __name__ == "__main__": import doctest doctest.testmod() # Manual testing user_input = input("Enter numbers separated by commas: ").strip() collection = sorted(int(item) for item in user_input.split(",")) target = int(input("Enter a number to search for: ")) result = exponential_search(sorted_collection=collection, item=target) if result == -1: print(f"{target} was not found in {collection}.") else: print(f"{target} was found at index {result} in {collection}.")
--- +++ @@ -1,5 +1,17 @@ #!/usr/bin/env python3 +""" +Pure Python implementation of exponential search algorithm + +For more information, see the Wikipedia page: +https://en.wikipedia.org/wiki/Exponential_search + +For doctests run the following command: +python3 -m doctest -v exponential_search.py + +For manual testing run: +python3 exponential_search.py +""" from __future__ import annotations @@ -7,6 +19,27 @@ def binary_search_by_recursion( sorted_collection: list[int], item: int, left: int = 0, right: int = -1 ) -> int: + """Pure implementation of binary search algorithm in Python using recursion + + Be careful: the collection must be ascending sorted otherwise, the result will be + unpredictable. + + :param sorted_collection: some ascending sorted collection with comparable items + :param item: item value to search + :param left: starting index for the search + :param right: ending index for the search + :return: index of the found item or -1 if the item is not found + + Examples: + >>> binary_search_by_recursion([0, 5, 7, 10, 15], 0, 0, 4) + 0 + >>> binary_search_by_recursion([0, 5, 7, 10, 15], 15, 0, 4) + 4 + >>> binary_search_by_recursion([0, 5, 7, 10, 15], 5, 0, 4) + 1 + >>> binary_search_by_recursion([0, 5, 7, 10, 15], 6, 0, 4) + -1 + """ if right < 0: right = len(sorted_collection) - 1 if list(sorted_collection) != sorted(sorted_collection): @@ -25,6 +58,30 @@ def exponential_search(sorted_collection: list[int], item: int) -> int: + """ + Pure implementation of an exponential search algorithm in Python. + For more information, refer to: + https://en.wikipedia.org/wiki/Exponential_search + + Be careful: the collection must be ascending sorted, otherwise the result will be + unpredictable. + + :param sorted_collection: some ascending sorted collection with comparable items + :param item: item value to search + :return: index of the found item or -1 if the item is not found + + The time complexity of this algorithm is O(log i) where i is the index of the item. + + Examples: + >>> exponential_search([0, 5, 7, 10, 15], 0) + 0 + >>> exponential_search([0, 5, 7, 10, 15], 15) + 4 + >>> exponential_search([0, 5, 7, 10, 15], 5) + 1 + >>> exponential_search([0, 5, 7, 10, 15], 6) + -1 + """ if list(sorted_collection) != sorted(sorted_collection): raise ValueError("sorted_collection must be sorted in ascending order") @@ -53,4 +110,4 @@ if result == -1: print(f"{target} was not found in {collection}.") else: - print(f"{target} was found at index {result} in {collection}.")+ print(f"{target} was found at index {result} in {collection}.")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/exponential_search.py
Generate documentation strings for clarity
#!/usr/bin/env python3 # /// script # requires-python = ">=3.13" # dependencies = [ # "httpx", # "pytest", # ] # /// import hashlib import importlib.util import json import os import pathlib from types import ModuleType import httpx import pytest PROJECT_EULER_DIR_PATH = pathlib.Path.cwd().joinpath("project_euler") PROJECT_EULER_ANSWERS_PATH = pathlib.Path.cwd().joinpath( "scripts", "project_euler_answers.json" ) with open(PROJECT_EULER_ANSWERS_PATH) as file_handle: PROBLEM_ANSWERS: dict[str, str] = json.load(file_handle) def convert_path_to_module(file_path: pathlib.Path) -> ModuleType: spec = importlib.util.spec_from_file_location(file_path.name, str(file_path)) module = importlib.util.module_from_spec(spec) # type: ignore[arg-type] spec.loader.exec_module(module) # type: ignore[union-attr] return module def all_solution_file_paths() -> list[pathlib.Path]: solution_file_paths = [] for problem_dir_path in PROJECT_EULER_DIR_PATH.iterdir(): if problem_dir_path.is_file() or problem_dir_path.name.startswith("_"): continue for file_path in problem_dir_path.iterdir(): if file_path.suffix != ".py" or file_path.name.startswith(("_", "test")): continue solution_file_paths.append(file_path) return solution_file_paths def get_files_url() -> str: with open(os.environ["GITHUB_EVENT_PATH"]) as file: event = json.load(file) return event["pull_request"]["url"] + "/files" def added_solution_file_path() -> list[pathlib.Path]: solution_file_paths = [] headers = { "Accept": "application/vnd.github.v3+json", "Authorization": "token " + os.environ["GITHUB_TOKEN"], } files = httpx.get(get_files_url(), headers=headers, timeout=10).json() for file in files: filepath = pathlib.Path.cwd().joinpath(file["filename"]) if ( filepath.suffix != ".py" or filepath.name.startswith(("_", "test")) or not filepath.name.startswith("sol") ): continue solution_file_paths.append(filepath) return solution_file_paths def collect_solution_file_paths() -> list[pathlib.Path]: # Return only if there are any, otherwise default to all solutions if ( os.environ.get("CI") and os.environ.get("GITHUB_EVENT_NAME") == "pull_request" and (filepaths := added_solution_file_path()) ): return filepaths return all_solution_file_paths() @pytest.mark.parametrize( "solution_path", collect_solution_file_paths(), ids=lambda path: f"{path.parent.name}/{path.name}", ) def test_project_euler(solution_path: pathlib.Path) -> None: # problem_[extract this part] and pad it with zeroes for width 3 problem_number: str = solution_path.parent.name[8:].zfill(3) expected: str = PROBLEM_ANSWERS[problem_number] solution_module = convert_path_to_module(solution_path) answer = str(solution_module.solution()) answer = hashlib.sha256(answer.encode()).hexdigest() assert answer == expected, ( f"Expected solution to {problem_number} to have hash {expected}, got {answer}" )
--- +++ @@ -28,6 +28,7 @@ def convert_path_to_module(file_path: pathlib.Path) -> ModuleType: + """Converts a file path to a Python module""" spec = importlib.util.spec_from_file_location(file_path.name, str(file_path)) module = importlib.util.module_from_spec(spec) # type: ignore[arg-type] spec.loader.exec_module(module) # type: ignore[union-attr] @@ -35,6 +36,7 @@ def all_solution_file_paths() -> list[pathlib.Path]: + """Collects all the solution file path in the Project Euler directory""" solution_file_paths = [] for problem_dir_path in PROJECT_EULER_DIR_PATH.iterdir(): if problem_dir_path.is_file() or problem_dir_path.name.startswith("_"): @@ -47,12 +49,18 @@ def get_files_url() -> str: + """Return the pull request number which triggered this action.""" with open(os.environ["GITHUB_EVENT_PATH"]) as file: event = json.load(file) return event["pull_request"]["url"] + "/files" def added_solution_file_path() -> list[pathlib.Path]: + """Collects only the solution file path which got added in the current + pull request. + + This will only be triggered if the script is ran from GitHub Actions. + """ solution_file_paths = [] headers = { "Accept": "application/vnd.github.v3+json", @@ -88,6 +96,7 @@ ids=lambda path: f"{path.parent.name}/{path.name}", ) def test_project_euler(solution_path: pathlib.Path) -> None: + """Testing for all Project Euler solutions""" # problem_[extract this part] and pad it with zeroes for width 3 problem_number: str = solution_path.parent.name[8:].zfill(3) expected: str = PROBLEM_ANSWERS[problem_number] @@ -96,4 +105,4 @@ answer = hashlib.sha256(answer.encode()).hexdigest() assert answer == expected, ( f"Expected solution to {problem_number} to have hash {expected}, got {answer}" - )+ )
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/scripts/validate_solutions.py
Add verbose docstrings with examples
# https://en.wikipedia.org/wiki/Hill_climbing import math class SearchProblem: def __init__(self, x: int, y: int, step_size: int, function_to_optimize): self.x = x self.y = y self.step_size = step_size self.function = function_to_optimize def score(self) -> int: return self.function(self.x, self.y) def get_neighbors(self): step_size = self.step_size return [ SearchProblem(x, y, step_size, self.function) for x, y in ( (self.x - step_size, self.y - step_size), (self.x - step_size, self.y), (self.x - step_size, self.y + step_size), (self.x, self.y - step_size), (self.x, self.y + step_size), (self.x + step_size, self.y - step_size), (self.x + step_size, self.y), (self.x + step_size, self.y + step_size), ) ] def __hash__(self): return hash(str(self)) def __eq__(self, obj): if isinstance(obj, SearchProblem): return hash(str(self)) == hash(str(obj)) return False def __str__(self): return f"x: {self.x} y: {self.y}" def hill_climbing( search_prob, find_max: bool = True, max_x: float = math.inf, min_x: float = -math.inf, max_y: float = math.inf, min_y: float = -math.inf, visualization: bool = False, max_iter: int = 10000, ) -> SearchProblem: current_state = search_prob scores = [] # list to store the current score at each iteration iterations = 0 solution_found = False visited = set() while not solution_found and iterations < max_iter: visited.add(current_state) iterations += 1 current_score = current_state.score() scores.append(current_score) neighbors = current_state.get_neighbors() max_change = -math.inf min_change = math.inf next_state = None # to hold the next best neighbor for neighbor in neighbors: if neighbor in visited: continue # do not want to visit the same state again if ( neighbor.x > max_x or neighbor.x < min_x or neighbor.y > max_y or neighbor.y < min_y ): continue # neighbor outside our bounds change = neighbor.score() - current_score if find_max: # finding max # going to direction with greatest ascent if change > max_change and change > 0: max_change = change next_state = neighbor elif change < min_change and change < 0: # finding min # to direction with greatest descent min_change = change next_state = neighbor if next_state is not None: # we found at least one neighbor which improved the current state current_state = next_state else: # since we have no neighbor that improves the solution we stop the search solution_found = True if visualization: from matplotlib import pyplot as plt plt.plot(range(iterations), scores) plt.xlabel("Iterations") plt.ylabel("Function values") plt.show() return current_state if __name__ == "__main__": import doctest doctest.testmod() def test_f1(x, y): return (x**2) + (y**2) # starting the problem with initial coordinates (3, 4) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing(prob, find_max=False) print( "The minimum score for f(x, y) = x^2 + y^2 found via hill climbing: " f"{local_min.score()}" ) # starting the problem with initial coordinates (12, 47) prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f"and 50 > y > - 5 found via hill climbing: {local_min.score()}" ) def test_f2(x, y): return (3 * x**2) - (6 * y) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = hill_climbing(prob, find_max=True) print( "The maximum score for f(x, y) = x^2 + y^2 found via hill climbing: " f"{local_min.score()}" )
--- +++ @@ -3,17 +3,46 @@ class SearchProblem: + """ + An interface to define search problems. + The interface will be illustrated using the example of mathematical function. + """ def __init__(self, x: int, y: int, step_size: int, function_to_optimize): + """ + The constructor of the search problem. + + x: the x coordinate of the current search state. + y: the y coordinate of the current search state. + step_size: size of the step to take when looking for neighbors. + function_to_optimize: a function to optimize having the signature f(x, y). + """ self.x = x self.y = y self.step_size = step_size self.function = function_to_optimize def score(self) -> int: + """ + Returns the output of the function called with current x and y coordinates. + >>> def test_function(x, y): + ... return x + y + >>> SearchProblem(0, 0, 1, test_function).score() # 0 + 0 = 0 + 0 + >>> SearchProblem(5, 7, 1, test_function).score() # 5 + 7 = 12 + 12 + """ return self.function(self.x, self.y) def get_neighbors(self): + """ + Returns a list of coordinates of neighbors adjacent to the current coordinates. + + Neighbors: + | 0 | 1 | 2 | + | 3 | _ | 4 | + | 5 | 6 | 7 | + """ step_size = self.step_size return [ SearchProblem(x, y, step_size, self.function) @@ -30,14 +59,27 @@ ] def __hash__(self): + """ + hash the string representation of the current search state. + """ return hash(str(self)) def __eq__(self, obj): + """ + Check if the 2 objects are equal. + """ if isinstance(obj, SearchProblem): return hash(str(self)) == hash(str(obj)) return False def __str__(self): + """ + string representation of the current search state. + >>> str(SearchProblem(0, 0, 1, None)) + 'x: 0 y: 0' + >>> str(SearchProblem(2, 5, 1, None)) + 'x: 2 y: 5' + """ return f"x: {self.x} y: {self.y}" @@ -51,6 +93,20 @@ visualization: bool = False, max_iter: int = 10000, ) -> SearchProblem: + """ + Implementation of the hill climbling algorithm. + We start with a given state, find all its neighbors, + move towards the neighbor which provides the maximum (or minimum) change. + We keep doing this until we are at a state where we do not have any + neighbors which can improve the solution. + Args: + search_prob: The search state at the start. + find_max: If True, the algorithm should find the maximum else the minimum. + max_x, min_x, max_y, min_y: the maximum and minimum bounds of x and y. + visualization: If True, a matplotlib graph is displayed. + max_iter: number of times to run the iteration. + Returns a search state having the maximum (or minimum) score. + """ current_state = search_prob scores = [] # list to store the current score at each iteration iterations = 0 @@ -137,4 +193,4 @@ print( "The maximum score for f(x, y) = x^2 + y^2 found via hill climbing: " f"{local_min.score()}" - )+ )
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/hill_climbing.py
Add docstrings for production code
from functools import lru_cache @lru_cache def fibonacci(k: int) -> int: if not isinstance(k, int): raise TypeError("k must be an integer.") if k < 0: raise ValueError("k integer must be greater or equal to zero.") if k == 0: return 0 elif k == 1: return 1 else: return fibonacci(k - 1) + fibonacci(k - 2) def fibonacci_search(arr: list, val: int) -> int: len_list = len(arr) # Find m such that F_m >= n where F_i is the i_th fibonacci number. i = 0 while True: if fibonacci(i) >= len_list: fibb_k = i break i += 1 offset = 0 while fibb_k > 0: index_k = min( offset + fibonacci(fibb_k - 1), len_list - 1 ) # Prevent out of range item_k_1 = arr[index_k] if item_k_1 == val: return index_k elif val < item_k_1: fibb_k -= 1 elif val > item_k_1: offset += fibonacci(fibb_k - 1) fibb_k -= 2 return -1 if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -1,9 +1,48 @@+""" +This is pure Python implementation of fibonacci search. + +Resources used: +https://en.wikipedia.org/wiki/Fibonacci_search_technique + +For doctests run following command: +python3 -m doctest -v fibonacci_search.py + +For manual testing run: +python3 fibonacci_search.py +""" from functools import lru_cache @lru_cache def fibonacci(k: int) -> int: + """Finds fibonacci number in index k. + + Parameters + ---------- + k : + Index of fibonacci. + + Returns + ------- + int + Fibonacci number in position k. + + >>> fibonacci(0) + 0 + >>> fibonacci(2) + 1 + >>> fibonacci(5) + 5 + >>> fibonacci(15) + 610 + >>> fibonacci('a') + Traceback (most recent call last): + TypeError: k must be an integer. + >>> fibonacci(-5) + Traceback (most recent call last): + ValueError: k integer must be greater or equal to zero. + """ if not isinstance(k, int): raise TypeError("k must be an integer.") if k < 0: @@ -17,6 +56,52 @@ def fibonacci_search(arr: list, val: int) -> int: + """A pure Python implementation of a fibonacci search algorithm. + + Parameters + ---------- + arr + List of sorted elements. + val + Element to search in list. + + Returns + ------- + int + The index of the element in the array. + -1 if the element is not found. + + >>> fibonacci_search([4, 5, 6, 7], 4) + 0 + >>> fibonacci_search([4, 5, 6, 7], -10) + -1 + >>> fibonacci_search([-18, 2], -18) + 0 + >>> fibonacci_search([5], 5) + 0 + >>> fibonacci_search(['a', 'c', 'd'], 'c') + 1 + >>> fibonacci_search(['a', 'c', 'd'], 'f') + -1 + >>> fibonacci_search([], 1) + -1 + >>> fibonacci_search([.1, .4 , 7], .4) + 1 + >>> fibonacci_search([], 9) + -1 + >>> fibonacci_search(list(range(100)), 63) + 63 + >>> fibonacci_search(list(range(100)), 99) + 99 + >>> fibonacci_search(list(range(-100, 100, 3)), -97) + 1 + >>> fibonacci_search(list(range(-100, 100, 3)), 0) + -1 + >>> fibonacci_search(list(range(-100, 100, 5)), 0) + 20 + >>> fibonacci_search(list(range(-100, 100, 5)), 95) + 39 + """ len_list = len(arr) # Find m such that F_m >= n where F_i is the i_th fibonacci number. i = 0 @@ -44,4 +129,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/fibonacci_search.py
Add docstrings to meet PEP guidelines
from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. precision = 10 # This is the linear search that will occur after the search space has become smaller. def lin_search(left: int, right: int, array: list[int], target: int) -> int: for i in range(left, right): if array[i] == target: return i return -1 def ite_ternary_search(array: list[int], target: int) -> int: left = 0 right = len(array) while left <= right: if right - left < precision: return lin_search(left, right, array, target) one_third = (left + right) // 3 + 1 two_third = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: right = one_third - 1 elif array[two_third] < target: left = two_third + 1 else: left = one_third + 1 right = two_third - 1 return -1 def rec_ternary_search(left: int, right: int, array: list[int], target: int) -> int: if left < right: if right - left < precision: return lin_search(left, right, array, target) one_third = (left + right) // 3 + 1 two_third = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(left, one_third - 1, array, target) elif array[two_third] < target: return rec_ternary_search(two_third + 1, right, array, target) else: return rec_ternary_search(one_third + 1, two_third - 1, array, target) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by comma:\n").strip() collection = [int(item.strip()) for item in user_input.split(",")] assert collection == sorted(collection), f"List must be ordered.\n{collection}." target = int(input("Enter the number to be found in the list:\n").strip()) result1 = ite_ternary_search(collection, target) result2 = rec_ternary_search(0, len(collection) - 1, collection, target) if result2 != -1: print(f"Iterative search: {target} found at positions: {result1}") print(f"Recursive search: {target} found at positions: {result2}") else: print("Not found")
--- +++ @@ -1,3 +1,11 @@+""" +This is a type of divide and conquer algorithm which divides the search space into +3 parts and finds the target value based on the property of the array or list +(usually monotonic property). + +Time Complexity : O(log3 N) +Space Complexity : O(1) +""" from __future__ import annotations @@ -10,6 +18,41 @@ def lin_search(left: int, right: int, array: list[int], target: int) -> int: + """Perform linear search in list. Returns -1 if element is not found. + + Parameters + ---------- + left : int + left index bound. + right : int + right index bound. + array : List[int] + List of elements to be searched on + target : int + Element that is searched + + Returns + ------- + int + index of element that is looked for. + + Examples + -------- + >>> lin_search(0, 4, [4, 5, 6, 7], 7) + 3 + >>> lin_search(0, 3, [4, 5, 6, 7], 7) + -1 + >>> lin_search(0, 2, [-18, 2], -18) + 0 + >>> lin_search(0, 1, [5], 5) + 0 + >>> lin_search(0, 3, ['a', 'c', 'd'], 'c') + 1 + >>> lin_search(0, 3, [.1, .4 , -.1], .1) + 0 + >>> lin_search(0, 3, [.1, .4 , -.1], -.1) + 2 + """ for i in range(left, right): if array[i] == target: return i @@ -17,6 +60,29 @@ def ite_ternary_search(array: list[int], target: int) -> int: + """Iterative method of the ternary search algorithm. + >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] + >>> ite_ternary_search(test_list, 3) + -1 + >>> ite_ternary_search(test_list, 13) + 4 + >>> ite_ternary_search([4, 5, 6, 7], 4) + 0 + >>> ite_ternary_search([4, 5, 6, 7], -10) + -1 + >>> ite_ternary_search([-18, 2], -18) + 0 + >>> ite_ternary_search([5], 5) + 0 + >>> ite_ternary_search(['a', 'c', 'd'], 'c') + 1 + >>> ite_ternary_search(['a', 'c', 'd'], 'f') + -1 + >>> ite_ternary_search([], 1) + -1 + >>> ite_ternary_search([.1, .4 , -.1], .1) + 0 + """ left = 0 right = len(array) @@ -44,6 +110,30 @@ def rec_ternary_search(left: int, right: int, array: list[int], target: int) -> int: + """Recursive method of the ternary search algorithm. + + >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] + >>> rec_ternary_search(0, len(test_list), test_list, 3) + -1 + >>> rec_ternary_search(4, len(test_list), test_list, 42) + 8 + >>> rec_ternary_search(0, 2, [4, 5, 6, 7], 4) + 0 + >>> rec_ternary_search(0, 3, [4, 5, 6, 7], -10) + -1 + >>> rec_ternary_search(0, 1, [-18, 2], -18) + 0 + >>> rec_ternary_search(0, 1, [5], 5) + 0 + >>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'c') + 1 + >>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'f') + -1 + >>> rec_ternary_search(0, 0, [], 1) + -1 + >>> rec_ternary_search(0, 3, [.1, .4 , -.1], .1) + 0 + """ if left < right: if right - left < precision: return lin_search(left, right, array, target) @@ -80,4 +170,4 @@ print(f"Iterative search: {target} found at positions: {result1}") print(f"Recursive search: {target} found at positions: {result2}") else: - print("Not found")+ print("Not found")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/ternary_search.py
Write docstrings for utility functions
def sentinel_linear_search(sequence, target): sequence.append(target) index = 0 while sequence[index] != target: index += 1 sequence.pop() if index == len(sequence): return None return index if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item) for item in user_input.split(",")] target_input = input("Enter a single number to be found in the list:\n") target = int(target_input) result = sentinel_linear_search(sequence, target) if result is not None: print(f"{target} found at positions: {result}") else: print("Not found")
--- +++ @@ -1,6 +1,36 @@+""" +This is pure Python implementation of sentinel linear search algorithm + +For doctests run following command: +python -m doctest -v sentinel_linear_search.py +or +python3 -m doctest -v sentinel_linear_search.py + +For manual testing run: +python sentinel_linear_search.py +""" def sentinel_linear_search(sequence, target): + """Pure implementation of sentinel linear search algorithm in Python + + :param sequence: some sequence with comparable items + :param target: item value to search + :return: index of found item or None if item is not found + + Examples: + >>> sentinel_linear_search([0, 5, 7, 10, 15], 0) + 0 + + >>> sentinel_linear_search([0, 5, 7, 10, 15], 15) + 4 + + >>> sentinel_linear_search([0, 5, 7, 10, 15], 5) + 1 + + >>> sentinel_linear_search([0, 5, 7, 10, 15], 6) + + """ sequence.append(target) index = 0 @@ -25,4 +55,4 @@ if result is not None: print(f"{target} found at positions: {result}") else: - print("Not found")+ print("Not found")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/sentinel_linear_search.py
Improve documentation using docstrings
def linear_search(sequence: list, target: int) -> int: for index, item in enumerate(sequence): if item == target: return index return -1 def rec_linear_search(sequence: list, low: int, high: int, target: int) -> int: if not (0 <= high < len(sequence) and 0 <= low < len(sequence)): raise Exception("Invalid upper or lower bound!") if high < low: return -1 if sequence[low] == target: return low if sequence[high] == target: return high return rec_linear_search(sequence, low + 1, high - 1, target) if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item.strip()) for item in user_input.split(",")] target = int(input("Enter a single number to be found in the list:\n").strip()) result = linear_search(sequence, target) if result != -1: print(f"linear_search({sequence}, {target}) = {result}") else: print(f"{target} was not found in {sequence}")
--- +++ @@ -1,6 +1,32 @@+""" +This is a pure Python implementation of the linear search algorithm. + +For doctests run following command: +python3 -m doctest -v linear_search.py + +For manual testing run: +python3 linear_search.py +""" def linear_search(sequence: list, target: int) -> int: + """A pure Python implementation of a linear search algorithm + + :param sequence: a collection with comparable items (sorting is not required for + linear search) + :param target: item value to search + :return: index of found item or -1 if item is not found + + Examples: + >>> linear_search([0, 5, 7, 10, 15], 0) + 0 + >>> linear_search([0, 5, 7, 10, 15], 15) + 4 + >>> linear_search([0, 5, 7, 10, 15], 5) + 1 + >>> linear_search([0, 5, 7, 10, 15], 6) + -1 + """ for index, item in enumerate(sequence): if item == target: return index @@ -8,6 +34,26 @@ def rec_linear_search(sequence: list, low: int, high: int, target: int) -> int: + """ + A pure Python implementation of a recursive linear search algorithm + + :param sequence: a collection with comparable items (as sorted items not required + in Linear Search) + :param low: Lower bound of the array + :param high: Higher bound of the array + :param target: The element to be found + :return: Index of the key or -1 if key not found + + Examples: + >>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 0) + 0 + >>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 700) + 4 + >>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 30) + 1 + >>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, -6) + -1 + """ if not (0 <= high < len(sequence) and 0 <= low < len(sequence)): raise Exception("Invalid upper or lower bound!") if high < low: @@ -28,4 +74,4 @@ if result != -1: print(f"linear_search({sequence}, {target}) = {result}") else: - print(f"{target} was not found in {sequence}")+ print(f"{target} was not found in {sequence}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/linear_search.py
Write reusable docstrings
from __future__ import annotations def binary_search(a_list: list[int], item: int) -> bool: if len(a_list) == 0: return False midpoint = len(a_list) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint], item) else: return binary_search(a_list[midpoint + 1 :], item) if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item.strip()) for item in user_input.split(",")] target = int(input("Enter the number to be found in the list:\n").strip()) not_str = "" if binary_search(sequence, target) else "not " print(f"{target} was {not_str}found in {sequence}")
--- +++ @@ -1,8 +1,46 @@+""" +Pure Python implementation of a binary search algorithm. + +For doctests run following command: +python3 -m doctest -v simple_binary_search.py + +For manual testing run: +python3 simple_binary_search.py +""" from __future__ import annotations def binary_search(a_list: list[int], item: int) -> bool: + """ + >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] + >>> binary_search(test_list, 3) + False + >>> binary_search(test_list, 13) + True + >>> binary_search([4, 4, 5, 6, 7], 4) + True + >>> binary_search([4, 4, 5, 6, 7], -10) + False + >>> binary_search([-18, 2], -18) + True + >>> binary_search([5], 5) + True + >>> binary_search(['a', 'c', 'd'], 'c') + True + >>> binary_search(['a', 'c', 'd'], 'f') + False + >>> binary_search([], 1) + False + >>> binary_search([-.1, .1 , .8], .1) + True + >>> binary_search(range(-5000, 5000, 10), 80) + True + >>> binary_search(range(-5000, 5000, 10), 1255) + False + >>> binary_search(range(0, 10000, 5), 2) + False + """ if len(a_list) == 0: return False midpoint = len(a_list) // 2 @@ -19,4 +57,4 @@ sequence = [int(item.strip()) for item in user_input.split(",")] target = int(input("Enter the number to be found in the list:\n").strip()) not_str = "" if binary_search(sequence, target) else "not " - print(f"{target} was {not_str}found in {sequence}")+ print(f"{target} was {not_str}found in {sequence}")
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/simple_binary_search.py