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 ...
--- +++ @@ -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 orde...
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: ...
--- +++ @@ -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 ...
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 ...
--- +++ @@ -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 +...
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: ...
--- +++ @@ -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:...
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): ...
--- +++ @@ -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:...
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...
--- +++ @@ -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 ...
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 m...
--- +++ @@ -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 num...
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 ...
--- +++ @@ -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 + ...
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,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)...
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 itertoo...
--- +++ @@ -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 charact...
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 ...
--- +++ @@ -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 gr...
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(...
--- +++ @@ -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...
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(mat...
--- +++ @@ -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...
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...
--- +++ @@ -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 ...
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, } d...
--- +++ @@ -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 numb...
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...
--- +++ @@ -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 writi...
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...
--- +++ @@ -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...
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] r...
--- +++ @@ -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 tw...
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*...
--- +++ @@ -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 p...
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...
--- +++ @@ -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 t...
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 r...
--- +++ @@ -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 p...
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...
--- +++ @@ -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...
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] nu...
--- +++ @@ -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 ...
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_squar...
--- +++ @@ -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 coor...
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 pandigitalit...
--- +++ @@ -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 ...
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,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 ...
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...
--- +++ @@ -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 t...
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...
--- +++ @@ -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 +...
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 ...
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" "62229893423...
--- +++ @@ -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 + 9698352031277450632623957...
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] + squ...
--- +++ @@ -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 tripl...
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 denomina...
--- +++ @@ -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) = ...
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...
--- +++ @@ -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 + 9698352031277450632623957...
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 + +Hen...
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, y...
--- +++ @@ -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 ...
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][...
--- +++ @@ -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 ...
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())...
--- +++ @@ -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 c...
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 soft...
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 retur...
--- +++ @@ -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, w...
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(i...
--- +++ @@ -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 ge...
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_pa...
--- +++ @@ -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 w...
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...
--- +++ @@ -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 ...
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 < ...
--- +++ @@ -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:...
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 + ...
--- +++ @@ -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...
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[ r...
--- +++ @@ -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. +...
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,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 +...
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 th...
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): ...
--- +++ @@ -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 a...
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 - til...
--- +++ @@ -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 f...
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_len...
--- +++ @@ -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...
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...
--- +++ @@ -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 +consec...
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] ...
--- +++ @@ -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...
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...
--- +++ @@ -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 hav...
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 ...
--- +++ @@ -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 ...
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: ...
--- +++ @@ -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...
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...
--- +++ @@ -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 i...
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 ...
--- +++ @@ -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: + +3...
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 ran...
--- +++ @@ -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: ...
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)...
--- +++ @@ -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...
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 ...
--- +++ @@ -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...
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): ...
--- +++ @@ -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 in...
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: d...
--- +++ @@ -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 +...
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_...
--- +++ @@ -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...
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( ...
--- +++ @@ -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 wit...
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) ret...
--- +++ @@ -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.b...
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 verif...
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 prim...
--- +++ @@ -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...
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 ...
--- +++ @@ -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 ...
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) % modu...
--- +++ @@ -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...
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 ...
--- +++ @@ -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 ar...
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 ...
--- +++ @@ -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 sp...
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] ...
--- +++ @@ -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(10...
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] ...
--- +++ @@ -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...
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_fa...
--- +++ @@ -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 h...
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 ...
--- +++ @@ -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 equ...
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(...
--- +++ @@ -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 ...
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_lim...
--- +++ @@ -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^...
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(ar...
--- +++ @@ -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 +dete...
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 ...
--- +++ @@ -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_n...
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_num...
--- +++ @@ -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...
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 ...
--- +++ @@ -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 =...
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, th...
--- +++ @@ -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 sta...
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, re...
--- +++ @@ -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. + +...
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_wait...
--- +++ @@ -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,...
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(bur...
--- +++ @@ -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 - ...
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 = (...
--- +++ @@ -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 i...
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, equa...
--- +++ @@ -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: ...
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: ...
--- +++ @@ -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 @@ ...
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 int...
--- +++ @@ -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 + T...
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, m...
--- +++ @@ -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 g...
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 inte...
--- +++ @@ -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 est...
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] == ite...
--- +++ @@ -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_collecti...
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 Valu...
--- +++ @@ -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 test...
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...
--- +++ @@ -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.l...
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: retur...
--- +++ @@ -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 t...
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: ...
--- +++ @@ -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 functo...
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: i...
--- +++ @@ -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 annotatio...
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 com...
--- +++ @@ -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 sent...
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)): ...
--- +++ @@ -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 im...
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...
--- +++ @@ -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], it...
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/simple_binary_search.py