Description
stringlengths
18
161k
Code
stringlengths
15
300k
problem 81 https projecteuler netproblem81 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 netprojectresourcesp081matrix txt a 31k text file containing an 80 by 80 matrix returns the minimal path sum from the top left to the bottom right of the matrix solution 427337 returns the minimal path sum from the top left to the bottom right of the matrix solution 427337
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() = }")
project euler problem 82 https projecteuler netproblem82 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 netprojectresourcesp082matrix txt right click and save linktarget as a 31k text file containing an 80 by 80 matrix 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 solutiontestmatrix txt 994 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
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() = }")
project euler problem 85 https projecteuler netproblem85 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 sidelengths a and b the number of rectangles contained in the grid is aa12 bb12 which happens to be the product of the ath and bth 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 tatb 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 aa12 we can assume that a and similarly b are roughly bounded by sqrt2 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 ti ti1 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 bb12 as well as the quadratic formula we can solve for b b is roughly 1 sqrt1 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 orgwikitriangularnumber https en wikipedia orgwikiquadraticformula find the area of the grid which contains as close to two million rectangles as possible solution20 6 solution2000 72 solution2000000000 86595 we want this to be as close as possible to target the area corresponding to the grid that gives the product closest to target an estimate of b using the quadratic formula the largest integer less than bestimate the largest integer less than bestimate the triangle number corresponding to bfloor the triangle number corresponding to bceil 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 we want this to be as close as possible to target the area corresponding to the grid that gives the product closest to target an estimate of b using the quadratic formula the largest integer less than b_estimate the largest integer less than b_estimate the triangle number corresponding to b_floor the triangle number corresponding to b_ceil
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) best_product: int = 0 area: int = 0 b_estimate: float b_floor: int b_ceil: int triangle_b_first_guess: int 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() = }")
project euler problem 86 https projecteuler netproblem86 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 sidelengths 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 sqrtab2 c2 this distance is an integer if and only if ab 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 sidelength m we can calculate this number iteratively each time we increase m as follows the set of cuboids satisfying this property with maximum sidelength m1 is a subset of the cuboids satisfying the property with maximum sidelength m since any cuboids with side lengths m1 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 sqrtab2 m2 is integer 1 a b m to count the number of pairs a b satisfying these conditions write d ab now we have 1 a b m 2 d 2m we can actually make the second equality strict since d 2m d2 m2 5m2 shortest distance m sqrt5 not integral a b d b d a and a b a d2 also a m a minm d2 a b d a d b and b m a d m also a 1 a max1 d m so a is in rangemax1 d m minm 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 minm d 2 1 max1 d m in the code below d is sumshortestsides and m is maxcuboidsize 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 solution100 24 solution1000 72 solution2000 100 solution20000 288 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
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() = }")
project euler problem 87 https projecteuler netproblem87 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 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 solution50 4 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
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() = }")
project euler problem 89 https projecteuler netproblem89 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 linktarget 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 converts a string of roman numerals to an integer e g parseromannumeralslxxxix 89 parseromannumeralsiiii 4 generates a string of roman numerals for a given integer e g generateromannumerals89 lxxxix generateromannumerals4 iv calculates and returns the answer to project euler problem 89 solutionnumeralcleanuptest txt 16 converts a string of roman numerals to an integer e g parse_roman_numerals lxxxix 89 parse_roman_numerals iiii 4 generates a string of roman numerals for a given integer e g generate_roman_numerals 89 lxxxix generate_roman_numerals 4 iv calculates and returns the answer to project euler problem 89 solution numeralcleanup_test txt 16
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() = }")
project euler problem 91 https projecteuler netproblem91 the points p x1 y1 and q x2 y2 are plotted at integer coordinates and are joined to the origin o0 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 check if the triangle described by px1 y1 qx2 y2 and o0 0 is rightangled 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 isright0 1 2 0 true isright1 0 2 2 false 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 solution2 14 solution10 448 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 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
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() = }")
project euler problem 092 https projecteuler netproblem92 square digit chains a number chain is 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 returns the next number of the chain by adding the square of each digit to form a new number for example if number 12 nextnumber will return 12 22 5 therefore 5 is the next number of the chain nextnumber44 32 nextnumber10 1 nextnumber32 13 increased speed slightly by checking every 5 digits together 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 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 nextnumber is 1 chain10 true chain58 false chain1 true 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 solution100 80 solution10000000 8581146 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 increased speed slightly by checking every 5 digits together 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 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 type ignore 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
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: sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared 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] 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() = }")
project euler problem 94 https projecteuler netproblem94 it is easily proved that no equilateral triangle exists with integral length sides and integral area however the almost equilateral triangle 556 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 returns the sum of the perimeters of all almost equilateral triangles with integral side lengths and area and whose perimeters do not exceed maxperimeter solution20 16 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
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() = }")
the first known prime found to exceed one million digits was discovered in 1999 and is a mersenne prime of the form 26972593 1 it contains exactly 2 098 960 digits subsequently other mersenne primes of the form 2p 1 have been found which contain more digits however in 2004 there was found a massive nonmersenne prime which contains 2 357 207 digits 28433 2 7830457 1 find the last ten digits of this prime number returns the last n digits of number solution 8739992577 solution8 39992577 solution1 7 solution1 traceback most recent call last valueerror invalid input solution8 3 traceback most recent call last valueerror invalid input solutiona traceback most recent call last valueerror invalid input 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
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) = }")
problem comparing two numbers written in index form like 2 11 and 3 7 is not difficult as any calculator would confirm that 211 2048 37 2187 however confirming that 632382518061 519432525806 would be much more difficult as both numbers contain over three million digits using baseexp txt a 22k text file containing one thousand lines with a baseexponent pair on each line determine which line number has the greatest numerical value note the first two lines in the file represent the numbers in the example given above solution 709 solution 709
import os from math import log10 def solution(data_file: str = "base_exp.txt") -> int: largest: float = 0 result = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(__file__), data_file))): a, x = list(map(int, line.split(","))) if x * log10(a) > largest: largest = x * log10(a) result = i + 1 return result if __name__ == "__main__": print(solution())
project euler problem 100 https projecteuler netproblem100 if a box contains twentyone 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 pbb 1521 x 1420 12 the next such arrangement for which there is exactly 50 chance of taking two blue discs at random is a box containing eightyfive blue discs and thirtyfive red discs by finding the first arrangement to contain over 1012 1 000 000 000 000 discs in total determine the number of blue discs that the box would contain returns the number of blue discs for the first arrangement to contain over mintotal discs in total solution2 3 solution4 15 solution21 85 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
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() = }")
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 un 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 opk 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 opk n will accurately generate the terms of the sequence for n k and potentially the first incorrect term fit will be opk k1 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 op1 n u1 hence we obtain the following ops for the cubic sequence op1 n 1 1 1 1 1 op2 n 7n6 1 8 15 op3 n 6n211n6 1 8 27 58 op4 n n3 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 n2 n3 n4 n5 n6 n7 n8 n9 n10 find the sum of fits for the bops 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 solve1 0 0 1 1 2 1 0 2 0 solve2 1 1 3 1 2 2 1 2 8 11 3 2 0 3 0 1 0 pivoting back substitution round to get rid of numbers like 2 000000000000004 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 interpolate13 1 interpolate1 83 15 interpolate1 8 274 58 interpolate1 8 27 646 216 interpolate13 1 interpolate1 83 15 interpolate1 8 274 58 interpolate1 8 27 646 216 the generating function u as specified in the question questionfunction0 1 questionfunction1 1 questionfunction5 8138021 questionfunction10 9090909091 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 ux solutionlambda n n 3 3 74 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 pivoting back substitution round to get rid of numbers like 2 000000000000004 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 interpolate 1 3 1 interpolate 1 8 3 15 interpolate 1 8 27 4 58 interpolate 1 8 27 64 6 216 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 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
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: 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 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 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() = }")
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 a340 495 b153 910 c835 947 x175 41 y421 714 z574 645 it can be verified that triangle abc contains the origin whereas triangle xyz does not using triangles txt right click and save linktarget 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 return the 2d vector product of two vectors vectorproduct1 2 5 0 10 vectorproduct3 1 6 10 24 check if the triangle given by the points ax1 y1 bx2 y2 cx3 y3 contains the origin containsorigin340 495 153 910 835 947 true containsorigin175 41 421 714 574 645 false find the number of triangles whose interior contains the origin solutiontesttriangles txt 1 return the 2 d vector product of two vectors vector_product 1 2 5 0 10 vector_product 3 1 6 10 24 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 find the number of triangles whose interior contains the origin solution test_triangles txt 1
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() = }")
project euler problem 104 https projecteuler netproblem104 the fibonacci sequence is defined by the recurrence relation fn fn1 fn2 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 19 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 19 pandigital given that fk is the first fibonacci number for which the first nine digits and the last nine digits are 19 pandigital find k takes a number and checks if it is pandigital both from start and end check123456789987654321 true check120000987654321 false check1234567895765677987654321 true mark last 9 numbers flag check last 9 numbers for pandigitality mark first 9 numbers check first 9 numbers for pandigitality takes a number and checks if it is pandigital from end check1123456789987654321 true check1120000987654321 true check112345678957656779870004321 false mark last 9 numbers flag check last 9 numbers for pandigitality outputs the answer is the least fibonacci number pandigital from both sides solution 329468 temporary fibonacci numbers temporary fibonacci numbers mod 1e9 mod m1e9 done for fast optimisation perform check only if in tocheck type ignore takes a number and checks if it is pandigital both from start and end check 123456789987654321 true check 120000987654321 false check 1234567895765677987654321 true mark last 9 numbers flag check last 9 numbers for pandigitality mark first 9 numbers check first 9 numbers for pandigitality takes a number and checks if it is pandigital from end check1 123456789987654321 true check1 120000987654321 true check1 12345678957656779870004321 false mark last 9 numbers flag check last 9 numbers for pandigitality outputs the answer is the least fibonacci number pandigital from both sides solution 329468 temporary fibonacci numbers temporary fibonacci numbers mod 1e9 mod m 1e9 done for fast optimisation perform check only if in tocheck first 2 already done
import sys sys.set_int_max_str_digits(0) def check(number: int) -> bool: check_last = [0] * 11 check_front = [0] * 11 for _ in range(9): check_last[int(number % 10)] = 1 number = number // 10 f = True for x in range(9): if not check_last[x + 1]: f = False if not f: return f number = int(str(number)[:9]) for _ in range(9): check_front[int(number % 10)] = 1 number = number // 10 for x in range(9): if not check_front[x + 1]: f = False return f def check1(number: int) -> bool: check_last = [0] * 11 for _ in range(9): check_last[int(number % 10)] = 1 number = number // 10 f = True for x in range(9): if not check_last[x + 1]: f = False return f def solution() -> int: a = 1 b = 1 c = 2 a1 = 1 b1 = 1 c1 = 2 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 if tocheck[x + 3] and check(b): return x + 3 return -1 if __name__ == "__main__": print(f"{solution() = }")
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 linktarget 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 orgwikiprim27salgorithm a class representing an undirected weighted graph add a new edge to the graph graph graph1 2 2 1 4 graph addedge3 1 5 sortedgraph vertices 1 2 3 sortedv k for k v in graph edges items 4 1 2 5 1 3 run prim s algorithm to find the minimum spanning tree reference https en wikipedia orgwikiprim27salgorithm graph graph1 2 3 4 1 2 5 1 3 10 1 4 20 2 4 30 3 4 1 mst graph primsalgorithm sortedmst vertices 1 2 3 4 sortedmst edges 1 2 1 3 3 4 find the maximum saving which can be achieved by removing redundant edges whilst ensuring that the network remains connected solutiontestnetwork txt 150 a class representing an undirected weighted graph 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 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 find the maximum saving which can be achieved by removing redundant edges whilst ensuring that the network remains connected solution test_network txt 150
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): if 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() = }")
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 redgreen outer ring scores zero the black and cream regions inside this ring represent single scores however the redgreen 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 bullseye 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 bullseye 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 count the number of distinct ways a player can checkout with a score less than limit solution171 42336 solution50 12577 count the number of distinct ways a player can checkout with a score less than limit solution 171 42336 solution 50 12577
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() = }")
problem 112 https projecteuler netproblem112 working from lefttoright 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 onehundred but just over half of the numbers below onethousand 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 returns true if number is bouncy false otherwise checkbouncy6789 false checkbouncy12345 false checkbouncy0 false checkbouncy6 74 traceback most recent call last valueerror checkbouncy accepts only integer arguments checkbouncy132475 true checkbouncy34 false checkbouncy341 true checkbouncy47 false checkbouncy12 54 traceback most recent call last valueerror checkbouncy accepts only integer arguments checkbouncy6548 true returns the least number for which the proportion of bouncy numbers is exactly percent solution50 538 solution90 21780 solution80 4770 solution105 traceback most recent call last valueerror solution only accepts values from 0 to 100 solution100 011 traceback most recent call last valueerror solution only accepts values from 0 to 100 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 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
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)}")
project euler problem 113 https projecteuler netproblem113 working from lefttoright 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 onemillion that are not bouncy and only 277032 nonbouncy numbers below 1010 how many numbers below a googol 10100 are not bouncy calculate the binomial coefficient cn r using the multiplicative formula choose4 2 6 choose5 3 10 choose20 6 38760 calculate the number of nonbouncy numbers with at most n digits nonbouncyexact1 9 nonbouncyexact6 7998 nonbouncyexact10 136126 calculate the number of nonbouncy numbers with at most n digits nonbouncyupto1 9 nonbouncyupto6 12951 nonbouncyupto10 277032 calculate the number of nonbouncy numbers less than a googol solution6 12951 solution10 277032 calculate the binomial coefficient c n r using the multiplicative formula choose 4 2 6 choose 5 3 10 choose 20 6 38760 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 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 calculate the number of non bouncy numbers less than a googol solution 6 12951 solution 10 277032
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() = }")
project euler problem 114 https projecteuler netproblem114 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 ggggggg r r rgggg gr r rggg ggr r rgg gggr r rg ggggr r r r r rgr r r r r r rggg gr r r rgg ggr r r rg gggr r r r r r r r rgg gr r r r rg ggr r r r r r r r r r rg gr 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 returns the number of ways a row of the given length can be filled solution7 17 returns the number of ways a row of the given length can be filled solution 7 17
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() = }")
project euler problem 115 https projecteuler netproblem115 note this is a more difficult version of problem 114 https projecteuler netproblem114 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 fillcount function fm n represent the number of ways that a row can be filled for example f3 29 673135 and f3 30 1089155 that is for m 3 it can be seen that n 30 is the smallest value for which the fillcount function first exceeds one million in the same way for m 10 it can be verified that f10 56 880711 and f10 57 1148904 so n 57 is the least value for which the fillcount function first exceeds one million for m 50 find the least value of n for which the fillcount function first exceeds one million returns for given minimum block length the least value of n for which the fillcount function first exceeds one million solution3 30 solution10 57 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
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() = }")
project euler problem 116 https projecteuler netproblem116 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 redgreygreygrey greyred redgreygrey greygreyred redgrey greygreygreyred red red redred redgrey red redgreyred red greyred redred red if green tiles are chosen there are three ways green green greengreygrey greygreen green greengrey greygreygreen green green and if blue tiles are chosen there are two ways blue blue blue bluegrey greyblue 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 netproblem117 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 solution5 12 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
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() = }")
project euler problem 117 https projecteuler netproblem117 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 greygreygreygreygrey red redgreygreygrey greyred redgreygrey greygreyred redgrey greygreygreyred red red redred redgrey red redgreyred red greyred redred red green green greengreygrey greygreen green greengrey greygreygreen green green red redgreen green green green green greenred red blue blue blue bluegrey greyblue 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 netproblem116 returns the number of ways can a row of the given length be tiled solution5 15 returns the number of ways can a row of the given length be tiled solution 5 15
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() = }")
problem 119 https projecteuler netproblem119 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 83 512 another example of a number with this property is 614656 284 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 returns the sum of the digits of the number digitsum123 6 digitsum456 15 digitsum78910 25 returns the value of 30th digit power sum solution2 512 solution5 5832 solution10 614656 returns the sum of the digits of the number digit_sum 123 6 digit_sum 456 15 digit_sum 78910 25 returns the value of 30th digit power sum solution 2 512 solution 5 5832 solution 10 614656
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())
problem 120 square remainders https projecteuler netproblem120 description let r be the remainder when a1n a1n is divided by a2 for example if a 7 and n 3 then r 42 63 83 728 42 mod 49 and as n varies so too will r but for a 7 it turns out that rmax 42 for 3 a 1000 find rmax solution on expanding the terms we get 2 if n is even and 2an if n is odd for maximizing the value 2an aa n a 12 integer division returns rmax for 3 a n as explained above solution10 300 solution100 330750 solution1000 333082500 returns r_max for 3 a n as explained above solution 10 300 solution 100 330750 solution 1000 333082500
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())
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 11120 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 15disc 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 find the maximum prize fund that should be allocated to a single game in which fifteen turns are played solution4 10 solution10 225 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
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() = }")
problem 123 https projecteuler netproblem123 name prime square remainders let pn be the nth prime 2 3 5 7 11 and let r be the remainder when pn1n pn1n is divided by pn2 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 109 is 7037 find the least value of n for which the remainder first exceeds 1010 solution n1 p1 p1 2p n2 p12 p12 p2 1 2p p2 1 2p using pb2 p2 b2 2pb pb2 p2 b2 2pb and b 1 2p2 2 n3 p13 p13 similarly using pb3 pb3 formula and so on 2p3 6p n4 2p4 12p2 2 n5 2p5 20p3 10p as you could see when the expression is divided by p2 except for the last term the rest will result in the remainder 0 n1 2p n2 2 n3 6p n4 2 n5 10p so it could be simplified as r 2pn when n is odd r 2 when n is even returns a prime number generator using sieve method typesieve class generator primes sieve nextprimes 2 nextprimes 3 nextprimes 5 nextprimes 7 nextprimes 11 nextprimes 13 returns the least value of n for which the remainder first exceeds 1010 solution1e8 2371 solution1e9 7037 ignore the next prime as the reminder will be 2 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 returns the least value of n for which the remainder first exceeds 10 10 solution 1e8 2371 solution 1e9 7037 ignore the next prime as the reminder will be 2
from __future__ import annotations from collections.abc import Generator def sieve() -> Generator[int, None, None]: 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 next(primes) n += 2 if __name__ == "__main__": print(solution())
problem 125 https projecteuler netproblem125 the palindromic number 595 is interesting because it can be written as the sum of consecutive squares 62 72 82 92 102 112 122 there are exactly eleven palindromes below onethousand that can be written as consecutive square sums and the sum of these palindromes is 4164 note that 1 02 12 has not been included as this problem is concerned with the squares of positive integers find the sum of all the numbers less than 108 that are both palindromic and can be written as the sum of consecutive squares check if an integer is palindromic ispalindrome12521 true ispalindrome12522 false ispalindrome12210 false returns the sum of all numbers less than 1e8 that are both palindromic and can be written as the sum of consecutive squares check if an integer is palindromic is_palindrome 12521 true is_palindrome 12522 false is_palindrome 12210 false returns the sum of all numbers less than 1e8 that are both palindromic and can be written as the sum of consecutive squares
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())
project euler problem 129 https projecteuler netproblem129 a number consisting entirely of ones is called a repunit we shall define rk to be a repunit of length k for example r6 111111 given that n is a positive integer and gcdn 10 1 it can be shown that there always exists a value k for which rk is divisible by n and let an be the least such value of k for example a7 6 and a41 5 the least value of n for which an first exceeds ten is 17 find the least value of n for which an first exceeds onemillion return the least value k such that the repunit of length k is divisible by divisor leastdivisiblerepunit7 6 leastdivisiblerepunit41 5 leastdivisiblerepunit1234567 34020 return the least value of n for which leastdivisiblerepunitn first exceeds limit solution10 17 solution100 109 solution1000 1017 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 return the least value of n for which least_divisible_repunit n first exceeds limit solution 10 17 solution 100 109 solution 1000 1017
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() = }")
project euler problem 131 https projecteuler netproblem131 there are some prime values p for which there exists a positive integer n such that the expression n3 n2p is a perfect cube for example when p 19 83 82 x 19 123 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 onehundred how many primes below one million have this remarkable property determines whether number is prime isprime3 true isprime4 false returns number of primes below maxprime with the property solution100 4 determines whether number is prime is_prime 3 true is_prime 4 false returns number of primes below max_prime with the property solution 100 4
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() = }")
project euler problem 135 https projecteuler netproblem135 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 11 12 13 14 1n so roughly onlogn time complexity returns the values of n less than or equal to the limit have exactly ten distinct solutions solution100 0 solution10000 45 solution50050 292 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 d must be divisible by 4 since x y z are positive integers so z 0 a d and 4d a
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: continue else: common_difference /= 4 if ( first_term > common_difference and first_term < 4 * common_difference ): frequency[n] += 1 count = sum(1 for x in frequency[1:limit] if x == 10) return count if __name__ == "__main__": print(f"{solution() = }")
in laser physics a white cell is a mirror system that acts as a delay line for the laser beam the beam enters the cell bounces around on the mirrors and eventually works its way back out the specific white cell we will be considering is an ellipse with the equation 4x2 y2 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 4xy 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 given that a laser beam hits the interior of the white cell at point pointx pointy with gradient incominggradient return a tuple x y m1 where the next point of contact with the interior is x y with gradient m1 nextpoint5 0 0 0 0 0 5 0 0 0 0 0 nextpoint5 0 0 0 2 0 0 0 10 0 2 0 normalgradient gradient of line through which the beam is reflected outgoinggradient gradient of reflected line to find the next point solve the simultaeneous equations y2 4x2 100 y b m x a a x2 b x c 0 two solutions one of which is our input point return the number of times that the beam hits the interior wall of the cell before exiting solution0 00001 10 1 solution5 0 287 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 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 two solutions one of which is our input point 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
from math import isclose, sqrt def next_point( point_x: float, point_y: float, incoming_gradient: float ) -> tuple[float, float, float]: 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) 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) 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() = }")
project euler problem 145 https projecteuler netproblem145 vineet rao maxim smolskiy problem statement some positive integers n have the property that the sum n reversen 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 reversen there are 120 reversible numbers below onethousand how many reversible numbers are there below onebillion 109 count the number of reversible numbers of given length iterate over possible digits considering parity of current sum remainder slowreversiblenumbers1 0 0 1 0 slowreversiblenumbers2 0 0 2 2 20 slowreversiblenumbers3 0 0 3 3 100 to evaluate the solution use solution slowsolution3 120 slowsolution6 18720 slowsolution7 68720 count the number of reversible numbers of given length iterate over possible digits considering parity of current sum remainder reversiblenumbers1 0 0 1 0 reversiblenumbers2 0 0 2 2 20 reversiblenumbers3 0 0 3 3 100 there exist no reversible 1 5 9 13 ie 4k1 digit numbers to evaluate the solution use solution solution3 120 solution6 18720 solution7 68720 benchmarks running performance benchmarks slowsolution 292 9300301000003 solution 54 90970860000016 for i in range1 15 printfi reversiblenumbersi 0 0i i 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 to evaluate the solution use solution slow_solution 3 120 slow_solution 6 18720 slow_solution 7 68720 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 to evaluate the solution use solution solution 3 120 solution 6 18720 solution 7 68720 benchmarks running performance benchmarks slow_solution 292 9300301000003 solution 54 90970860000016 for i in range 1 15 print f i reversible_numbers i 0 0 i i
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: if (length - 1) % 4 == 0: return 0 return slow_reversible_numbers(length, 0, [0] * length, 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: 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()
project euler problem 173 https projecteuler netproblem173 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 thirtytwo square tiles we can form two different square laminae with onehundred tiles and not necessarily using all of the tiles at one time it is possible to form fortyone different square laminae using up to one million tiles how many different square laminae can be formed return the number of different square laminae that can be formed using up to one million tiles solution100 41 return the number of different square laminae that can be formed using up to one million tiles solution 100 41
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() = }")
project euler problem 174 https projecteuler netproblem174 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 thirtytwo 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 l1 and t 32 is type l2 let nn be the number of t 1000000 such that t is type ln for example n15 832 what is nn for 1 n 10 return the sum of nn for 1 n nlimit solution1000 5 249 solution10000 10 2383 return the sum of n n for 1 n n_limit solution 1000 5 249 solution 10000 10 2383
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 <= 10) if __name__ == "__main__": print(f"{solution() = }")
project euler problem 234 https projecteuler netproblem234 for any integer n consider the three functions f1 nx y z xn1 yn1 zn1 f2 nx y z xy yz zxxn1 yn1 zn1 f3 nx y z xyzxn2 yn2 zn2 and their combination fnx y z f1 nx y z f2 nx y z f3 nx 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 fnx y z 0 let sx y z x y z let t u v be the sum of all distinct sx y z for all golden triples x y z of order 35 all the sx y z and t must be in reduced form find u v solution by expanding the brackets it is easy to show that fnx y z x y z xn yn zn since x y z are positive the requirement fnx y z 0 is fulfilled if and only if xn yn zn 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 znum zden 0 we use a set uniquqs 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 orgwikifermat27slasttheorem check if number is a perfect square issq1 true issq1000001 false issq1000000 true given the numerators and denominators of three fractions return the numerator and denominator of their sum in lowest form addthree1 3 1 3 1 3 1 1 addthree2 5 4 11 12 3 262 55 find the sum of the numerator and denominator of the sum of all sx y z for golden triples x y z of the given order solution5 296 solution10 12519 solution20 19408891927 n1 n2 n1 n2 check if number is a perfect square is_sq 1 true is_sq 1000001 false is_sq 1000000 true 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 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 n 1 n 2 n 1 n 2
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): 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) 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) 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) 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() = }")
project euler problem 187 https projecteuler netproblem187 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 108 have precisely two not necessarily distinct prime factors returns prime numbers below maxnumber see https en wikipedia orgwikisieveoferatosthenes slowcalculateprimenumbers10 2 3 5 7 slowcalculateprimenumbers2 list containing a bool value for every number below maxnumber2 mark all multiple of i as not prime returns prime numbers below maxnumber see https en wikipedia orgwikisieveoferatosthenes calculateprimenumbers10 2 3 5 7 calculateprimenumbers2 list containing a bool value for every odd number below maxnumber2 mark all multiple of i as not prime using list slicing same as maxnumber i2 2 i 1 but faster than lenisprimei2 2 i returns the number of composite integers below maxnumber have precisely two not necessarily distinct prime factors slowsolution30 10 returns the number of composite integers below maxnumber have precisely two not necessarily distinct prime factors whilesolution30 10 returns the number of composite integers below maxnumber have precisely two not necessarily distinct prime factors solution30 10 benchmarks running performance benchmarks slowsolution 108 50874730000032 whilesol 28 09581200000048 solution 25 063097400000515 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 mark all multiple of i as not prime 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 list containing a bool value for every odd number below max_number 2 mark all multiple of i as not prime using list slicing same as max_number i 2 2 i 1 but faster than len is_prime i 2 2 i returns the number of composite integers below max_number have precisely two not necessarily distinct prime factors slow_solution 30 10 returns the number of composite integers below max_number have precisely two not necessarily distinct prime factors while_solution 30 10 returns the number of composite integers below max_number have precisely two not necessarily distinct prime factors solution 30 10 benchmarks running performance benchmarks slow_solution 108 50874730000032 while_sol 28 09581200000048 solution 25 063097400000515
from math import isqrt def slow_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 calculate_prime_numbers(max_number: int) -> list[int]: if max_number <= 2: return [] is_prime = [True] * (max_number // 2) for i in range(3, isqrt(max_number - 1) + 1, 2): if is_prime[i // 2]: is_prime[i**2 // 2 :: i] = [False] * ( 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: 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()
project euler problem 188 https projecteuler netproblem188 the hyperexponentiation of a number the hyperexponentiation or tetration of a number a by a positive integer b denoted by ab or ba is recursively defined by a1 a ak1 aak thus we have e g 32 33 27 hence 33 327 7625597484987 and 34 is roughly 103 63833464002409961012 find the last 8 digits of 17771855 references https en wikipedia orgwikitetration small helper function for modular exponentiation fast exponentiation algorithm returns the modular exponentiation that is the value of base exponent modulovalue without calculating the actual number modexpt2 4 10 6 modexpt2 1024 100 16 modexpt13 65535 7 6 returns the last 8 digits of the hyperexponentiation of base by height i e the number baseheight solutionbase3 height2 27 solutionbase3 height3 97484987 solutionbase123 height456 digits4 2547 calculate baseheight by rightassiciative repeated modular exponentiation small helper function for modular exponentiation fast exponentiation algorithm 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 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
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: result = base for _ in range(1, height): result = _modexpt(base, result, 10**digits) return result if __name__ == "__main__": print(f"{solution() = }")
prize strings problem 191 a particular school offers cash rewards to children with good attendance and punctuality if they are absent for three consecutive days or late on more than one occasion then they forfeit their prize during an nday 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 eightyone trinary strings for a 4day period that can be formed exactly fortythree 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 30day period references the original project euler project page https projecteuler netproblem191 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 calculatedays4 absent0 late0 43 calculatedays30 absent2 late0 0 calculatedays30 absent1 late0 98950096 if we are absent twice or late 3 consecutive days no further prize strings are possible if we have no days left and have not failed any other rules we have a prize string 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 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 2 if we are absent the absent counter increases by 1 and the late counter resets to 0 3 if we are on time this resets the late counter and keeps the absent counter 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 solution4 43 a small helper function for the recursion mainly to have a clean interface for the solution function below it should get called with the number of days corresponding to the desired length of the prize strings and the initial values for the number of consecutive absent days and number of total late days _calculate days 4 absent 0 late 0 43 _calculate days 30 absent 2 late 0 0 _calculate days 30 absent 1 late 0 98950096 if we are absent twice or late 3 consecutive days no further prize strings are possible if we have no days left and have not failed any other rules we have a prize string 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 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 2 if we are absent the absent counter increases by 1 and the late counter resets to 0 3 if we are on time this resets the late counter and keeps the absent counter 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
cache: dict[tuple[int, int, int], int] = {} def _calculate(days: int, absent: int, late: int) -> int: if late == 3 or absent == 2: return 0 if days == 0: return 1 key = (days, absent, late) if key in cache: return cache[key] state_late = _calculate(days - 1, absent, late + 1) state_absent = _calculate(days - 1, absent + 1, 0) 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())
project euler problem 203 https projecteuler netproblem203 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 orgwikipascal27striangle 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 getpascaltriangleuniquecoefficients1 1 getpascaltriangleuniquecoefficients2 1 getpascaltriangleuniquecoefficients3 1 2 getpascaltriangleuniquecoefficients8 1 2 3 4 5 6 7 35 10 15 20 21 calculates the squarefree numbers inside uniquecoefficients based on the definition of a nonsquarefree number then any nonsquarefree n can be decomposed as n ppr where p is positive prime number and r is a positive integer under the previous formula any coefficient that is lower than pp is squarefree as r cannot be negative on the contrary if any r exists such that n ppr then the number is nonsquarefree getsquarefrees1 1 getsquarefrees1 2 1 2 getsquarefrees1 2 3 4 5 6 7 35 10 15 20 21 1 2 3 5 6 7 35 10 15 21 returns the sum of squarefrees for a given pascal s triangle of depth n solution1 1 solution8 105 solution9 175 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 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 returns the sum of squarefrees for a given pascal s triangle of depth n solution 1 1 solution 8 105 solution 9 175
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() = }")
project euler problem 205 https projecteuler netproblem205 peter has nine foursided pyramidal dice each with faces numbered 1 2 3 4 colin has six sixsided 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 returns frequency distribution of total totalfrequencydistributionsidesnumber6 dicenumber1 0 1 1 1 1 1 1 totalfrequencydistributionsidesnumber4 dicenumber2 0 0 1 2 3 4 3 2 1 returns probability that pyramidal peter beats cubic colin rounded to seven decimal places in the form 0 abcdefg solution 0 5731441 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 returns probability that pyramidal peter beats cubic colin rounded to seven decimal places in the form 0 abcdefg solution 0 5731441
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() = }")
project euler problem 206 https projecteuler netproblem206 find the unique positive integer whose square has the form 1234567890 where each is a single digit instead of computing every single permutation of that number and going through a 109 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 determines if num is in the form 123456789 issquareform1 false issquareform112233445566778899 true issquareform123456789012345678 false returns the first integer whose square is of the form 1234567890 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 returns the first integer whose square is of the form 1_2_3_4_5_6_7_8_9_0 3 6 10 7 7 4 10 3
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 else: num -= 4 return num * 10 if __name__ == "__main__": print(f"{solution() = }")
project euler problem 207 https projecteuler netproblem207 problem statement for some positive integers k there exists an integer partition of the form 4t 2t k where 4t 2t and k are all positive integers and t is a real number the first two such partitions are 41 21 2 and 41 5849625 21 5849625 6 partitions where t is also an integer are called perfect for any m 1 let pm be the proportion of such partitions that are perfect with k m thus p6 12 in the following table are listed some values of pm p5 11 p10 12 p15 23 p20 12 p25 12 p30 25 p180 14 p185 313 find the smallest m for which pm 112345 solution equation 4t 2t k solved for t gives t log2sqrt4k12 12 for t to be real valued sqrt4k1 must be an integer which is implemented in function checktrealk 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 i2 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 check if t fpositiveinteger log2sqrt4positiveinteger12 12 is a real number checkpartitionperfect2 true checkpartitionperfect6 false find m for which the proportion of perfect partitions to total partitions is lower than maxproportion solution1 5 true solution12 10 true solution3 13 185 true if candidate is an integer then there is a partition for k 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 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 if candidate is an integer then there is a partition for k
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 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: if perfect_partitions / total_partitions < max_proportion: return int(partition_candidate) integer += 1 if __name__ == "__main__": print(f"{solution() = }")
https projecteuler netproblem234 for an integer n 4 we define the lower prime square root of n denoted by lpsn as the largest prime n and the upper prime square root of n upsn as the smallest prime n so for example lps4 2 ups4 lps1000 31 ups1000 37 let us call an integer n 4 semidivisible if one of lpsn and upsn 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 lps15 3 and ups15 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 sieve of erotosthenes function to return all the prime numbers up to a certain number https en wikipedia orgwikisieveoferatosthenes primesieve3 2 primesieve50 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 computes the solution to the problem up to the specified limit solution1000 34825 solution10000 1134942 solution100000 36393008 get numbers divisible by lpscurrent reset the upperbound add the numbers divisible by upscurrent remove the numbers divisible by both ups and lps increment the current number remove twice since it was added by both ups and lps increment the current number setup for next pair 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 computes the solution to the problem up to the specified limit solution 1000 34825 solution 10_000 1134942 solution 100_000 36393008 get numbers divisible by lps current reset the upper_bound add the numbers divisible by ups current remove the numbers divisible by both ups and lps increment the current number remove twice since it was added by both ups and lps increment the current number setup for next pair
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 current = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime while (upper_bound - next_prime) > limit: upper_bound -= next_prime current = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime current = 0 while upper_bound > current <= limit: if current <= lower_bound: current += last_prime * next_prime continue if current > limit: break matches_sum -= current * 2 current += last_prime * next_prime last_prime = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
project euler problem 301 https projecteuler netproblem301 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 threeheap normalplay 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 xn1 n2 n3 that returns zero if with perfect strategy the player about to move will eventually lose or nonzero if with perfect strategy the player about to move will eventually win for example x1 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 230 does xn 2n 3n 0 for any given exponent x 0 1 n 2x this function returns how many nim games are lost given that each nim game has three heaps of the form n 2n 3n solution0 1 solution2 3 solution10 144 to find how many total games were lost for a given exponent x we need to find the fibonacci number fx2 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
def solution(exponent: int = 30) -> int: 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() = }")
project euler problem 493 https projecteuler netproblem493 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 binomcoeff70 20 2 calculate the number of combinations with one colour missing missing binomcoeff60 20 3 calculate the probability of one colour missing missingprob missing combinations 4 calculate the probability of no colour missing nomissingprob 1 missingprob 5 calculate the expected number of distinct colours expected 7 nomissingprob references https en wikipedia orgwikibinomialcoefficient calculates the expected number of distinct colours solution10 5 669644129 solution30 6 985042712 calculates the expected number of distinct colours solution 10 5 669644129 solution 30 6 985042712
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))
sum of digits sequence problem 551 let a0 a1 be an integer sequence defined by a0 1 for n 1 an is the sum of the digits of all preceding terms the sequence starts with 1 1 2 4 8 you are given a106 31054319 find a1015 calculates and updates ai inplace to either the nth term or the smallest term for which c 10k when the terms are written in the form ai b 10k c for any ai if digitsumb and c have the same value the difference between subsequent terms will be the same until c 10k this difference is cached to greatly speed up the computation arguments ai array of digits starting from the one s place that represent the ith term in the sequence k k when terms are written in the from ai b10k c term are calulcated until c 10k or the nth 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 a01 and ending term is a1062 then 61 9 is returned dsb digitsumb find and make the largest jump without going over since the difference between jumps is cached add c keep doing smaller jumps would be too small a jump just compute sequential terms instead keep jumps sorted by of terms skipped cache the jump for this value digitsumb and c same as nexttermai k i n but computes terms without memoizing results note ai b 10k c dsb digitsumb dsc digitsumc adds addend to digit array given in digits starting at index k returns nth term of sequence solution10 62 solution106 31054319 solution1015 73597483551591773 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 find and make the largest jump without going over since the difference between jumps is cached add c keep doing smaller jumps would be too small a jump just compute sequential terms instead keep jumps sorted by of terms skipped cache the jump for this value digitsum b and c same as next_term a_i k i n but computes terms without memoizing results note a_i b 10 k c ds_b digitsum b ds_c digitsum c adds addend to digit array given in digits starting at index k returns n th term of sequence solution 10 62 solution 10 6 31054319 solution 10 15 73597483551591773
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 = 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: 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] 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: _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: _diff, terms_jumped = compute(a_i, k, i + dn, n) diff += _diff dn += terms_jumped jumps = sub_memo[c] j = 0 while j < len(jumps): if jumps[j][1] > dn: break j += 1 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))]) 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() = }")
project euler problem 587 https projecteuler netproblem587 a square is drawn around a circle as shown in the diagram below on the left we shall call the blue shaded region the lsection 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 lsection 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 lsection 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 lsection is n 15 what is the least value of n for which the concave triangle occupies less than 0 1 of the lsection returns integral of circle bottom arc y 1 2 sqrt1 4 x 1 2 2 circlebottomarcintegral0 0 39269908169872414 circlebottomarcintegral1 2 0 44634954084936207 circlebottomarcintegral1 0 5 returns area of concave triangle concavetrianglearea1 0 026825229575318944 concavetrianglearea2 0 01956236140083944 returns least value of n for which the concave triangle occupies less than fraction of the lsection solution1 10 15 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 returns area of concave triangle concave_triangle_area 1 0 026825229575318944 concave_triangle_area 2 0 01956236140083944 returns least value of n for which the concave triangle occupies less than fraction of the l section solution 1 10 15
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() = }")
project euler problem 686 https projecteuler netproblem686 27 128 is the first power of two whose leading digits are 12 the next power of two whose leading digits are 12 is 280 define pl n to be the nthsmallest value of j such that the base 10 representation of 2j begins with the digits of l so p12 1 7 and p12 2 80 you are given that p123 45 12710 find p123 678910 this function returns the decimal value of a number multiplied with log2 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 290 is time consuming hence we find log290 90log2 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 logdifference90 0 092699609758302 logdifference379 0 090368356648852 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 2power 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 log1 23 upperbound log1 24 because we need to find the powers that yield 123 as starting digits log1 23 0 08990511143939792 log1 24 0 09342168516223506 we use 1 23 and not 12 3 or 123 because log1 23 yields only decimal value which is less than 1 log12 3 will be same decimal value but 1 added to it which is log12 3 1 093421685162235 we observe that decimal value remains same no matter 1 23 or 12 3 since we use the function logdifference which returns the value that is only decimal part using 1 23 is logical if we see 90log2 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 logdifference 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 logdifference286 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 logdifference1256 0 09367455396034 which is greater than upperbound hence we increment by 93 now iterator is 1349 logdifference1349 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 logdifference 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 logdifference is greater than or equal upperbound we will increment by 93 3 if logdifference lowerbound we increment by 196 reference to the above logic https math stackexchange comquestions4093970powersof2startingwith123doesapatternexist solution1000 284168 solution56000 15924915 solution678910 193060223 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 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
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() = }")
project euler problem 800 https projecteuler netproblem800 an integer of the form pq qp with prime numbers p q is called a hybridinteger for example 800 25 52 is a hybridinteger we define cn to be the number of hybridintegers less than or equal to n you are given c800 2 and c800800 10790 find c800800800800 returns prime numbers below maxnumber calculateprimenumbers10 2 3 5 7 returns the number of hybridintegers less than or equal to basedegree solution800 1 2 solution800 800 10790 returns prime numbers below max_number calculate_prime_numbers 10 2 3 5 7 returns the number of hybrid integers less than or equal to base degree solution 800 1 2 solution 800 800 10790
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() = }")
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 orgwikiquantumfouriertransform https qiskit orgtextbookchalgorithmsquantumfouriertransform html quantumfouriertransform2 00 2500 01 2500 11 2500 10 2500 quantum circuit for numberofqubits 3 qr0 h x p2 qr1 h p4 p2 qr2 h x cr 3 args n number of qubits returns qiskit result counts counts distribute counts quantumfouriertransform2 00 2500 01 2500 10 2500 11 2500 quantumfouriertransform1 traceback most recent call last valueerror number of qubits must be 0 quantumfouriertransform a traceback most recent call last typeerror number of qubits must be a integer quantumfouriertransform100 traceback most recent call last valueerror number of qubits too large to simulate10 quantumfouriertransform0 5 traceback most recent call last valueerror number of qubits must be exact integer measure all the qubits simulate with 10000 shots 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 measure all the qubits simulate with 10000 shots
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) quantum_circuit.measure(qr, cr) 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)}" )
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 orgwikischedulingcomputingfirstcome firstserved this function calculates the waiting time of some processes that have a specified duration time return the waiting time for each process calculatewaitingtimes5 10 15 0 5 15 calculatewaitingtimes1 2 3 4 5 0 1 3 6 10 calculatewaitingtimes10 3 0 10 this function calculates the turnaround time of some processes return the time difference between the completion time and the arrival time practically waitingtime durationtime calculateturnaroundtimes5 10 15 0 5 15 5 15 30 calculateturnaroundtimes1 2 3 4 5 0 1 3 6 10 1 3 6 10 15 calculateturnaroundtimes10 3 0 10 10 13 this function calculates the average of the turnaround times return the average of the turnaround times calculateaverageturnaroundtime0 5 16 7 0 calculateaverageturnaroundtime1 5 8 12 6 5 calculateaverageturnaroundtime10 24 17 0 this function calculates the average of the waiting times return the average of the waiting times calculateaveragewaitingtime0 5 16 7 0 calculateaveragewaitingtime1 5 8 12 6 5 calculateaveragewaitingtime10 24 17 0 process id s ensure that we actually have processes duration time of all processes ensure we can match each id to a duration time get the waiting times and the turnaround times get the average times print all the results 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 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 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 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 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 process id s ensure that we actually have processes duration time of all processes ensure we can match each id to a duration time get the waiting times and the turnaround times get the average times print all the results
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__": processes = [1, 2, 3] if len(processes) == 0: print("Zero amount of processes") raise SystemExit(0) duration_times = [19, 8, 9] if len(duration_times) != len(processes): print("Unable to match all id's with their duration time") raise SystemExit(0) waiting_times = calculate_waiting_times(duration_times) turnaround_times = calculate_turnaround_times(duration_times, waiting_times) average_waiting_time = calculate_average_waiting_time(waiting_times) average_turnaround_time = calculate_average_turnaround_time(turnaround_times) 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}")
highest response ratio next hrrn scheduling is a nonpreemptive 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 orgwikihighestresponserationext calculate the turn around time of each processes return the turn around time time for each process calculateturnaroundtimea b c 3 5 8 2 4 6 3 2 4 7 calculateturnaroundtimea b c 0 2 4 3 5 7 3 3 6 11 number of processes finished displays the finished process if it is 0 the performance is completed if it is 1 before the performance list to include calculation results sort by arrival time 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 index showing the location of the process being performed saves the current response ratio calculate the turn around time indicates that the process has been performed increase finishedprocesscount by 1 calculate the waiting time of each processes return the waiting time for each process calculatewaitingtimea b c 2 4 7 2 4 6 3 0 0 1 calculatewaitingtimea b c 3 6 11 3 5 7 3 0 1 4 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 number of processes finished displays the finished process if it is 0 the performance is completed if it is 1 before the performance list to include calculation results sort by arrival time 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 index showing the location of the process being performed saves the current response ratio calculate the turn around time indicates that the process has been performed increase finished_process_count by 1 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
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 finished_process_count = 0 finished_process = [0] * no_of_process turn_around_time = [0] * no_of_process 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: i = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: current_time = arrival_time[i] response_ratio = 0 loc = 0 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 turn_around_time[loc] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] finished_process[loc] = 1 finished_process_count += 1 return turn_around_time def calculate_waiting_time( process_name: list, 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}")
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 tasksinfo 4 20 1 10 1 40 1 30 maxtasks 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 on log n https medium comnihardudhat2000jobsequencingwithdeadline17ddbb5890b5 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 maxtasks4 20 1 10 1 40 1 30 2 0 maxtasks1 10 2 20 3 30 2 40 3 2 maxtasks9 10 0 maxtasks9 10 maxtasks maxtasks0 10 0 20 0 30 0 40 maxtasks1 10 2 20 3 30 4 40 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
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)]) = }")
function to find the maximum profit by doing jobs in a given time frame args numjobs int number of jobs jobs list a list of tuples of jobid deadline profit returns maxprofit int maximum profit that can be earned by doing jobs in a given time frame examples jobsequencingwithdeadlines4 1 4 20 2 1 10 3 1 40 4 1 30 2 60 jobsequencingwithdeadlines5 1 2 100 2 1 19 3 2 27 4 1 25 5 1 15 2 127 sort the jobs in descending order of profit create a list of size equal to the maximum deadline and initialize it with 1 finding the maximum profit and the count of jobs find a free time slot for this job note that we start from the last possible slot function to find the maximum profit by doing jobs in a given time frame args num_jobs int number of jobs jobs list a list of tuples of job_id deadline profit returns max_profit int maximum profit that can be earned by doing jobs in a given time frame examples job_sequencing_with_deadlines 4 1 4 20 2 1 10 3 1 40 4 1 30 2 60 job_sequencing_with_deadlines 5 1 2 100 2 1 19 3 2 27 4 1 25 5 1 15 2 127 sort the jobs in descending order of profit create a list of size equal to the maximum deadline and initialize it with 1 finding the maximum profit and the count of jobs find a free time slot for this job note that we start from the last possible slot
def job_sequencing_with_deadlines(num_jobs: int, jobs: list) -> list: jobs = sorted(jobs, key=lambda value: value[2], reverse=True) max_deadline = max(jobs, key=lambda value: value[1])[1] time_slots = [-1] * max_deadline count = 0 max_profit = 0 for job in jobs: for i in range(job[1] - 1, -1, -1): if time_slots[i] == -1: time_slots[i] = job[0] count += 1 max_profit += job[2] break return [count, max_profit] if __name__ == "__main__": import doctest doctest.testmod()
completion time of finished process or last interrupted time mlfqmulti level feedback queue https en wikipedia orgwikimultilevelfeedbackqueue mlfq has a lot of queues that have different priority in this mlfq the first queue0 to last second queuen2 of mlfq have round robin algorithm the last queuen1 has first come first served algorithm total number of mlfq s queues time slice of queues that round robin algorithm applied unfinished process is in this readyqueue current time finished process is in this sequence queue this method returns the sequence of finished processes p1 processp1 0 53 p2 processp2 0 17 p3 processp3 0 68 p4 processp4 0 24 mlfq mlfq3 17 25 dequep1 p2 p3 p4 0 mlfq multilevelfeedbackqueue mlfq calculatesequenceoffinishqueue p2 p4 p1 p3 this method calculates waiting time of processes p1 processp1 0 53 p2 processp2 0 17 p3 processp3 0 68 p4 processp4 0 24 mlfq mlfq3 17 25 dequep1 p2 p3 p4 0 mlfq multilevelfeedbackqueue mlfq calculatewaitingtimep1 p2 p3 p4 83 17 94 101 this method calculates turnaround time of processes p1 processp1 0 53 p2 processp2 0 17 p3 processp3 0 68 p4 processp4 0 24 mlfq mlfq3 17 25 dequep1 p2 p3 p4 0 mlfq multilevelfeedbackqueue mlfq calculateturnaroundtimep1 p2 p3 p4 136 34 162 125 this method calculates completion time of processes p1 processp1 0 53 p2 processp2 0 17 p3 processp3 0 68 p4 processp4 0 24 mlfq mlfq3 17 25 dequep1 p2 p3 p4 0 mlfq multilevelfeedbackqueue mlfq calculateturnaroundtimep1 p2 p3 p4 136 34 162 125 this method calculate remaining burst time of processes p1 processp1 0 53 p2 processp2 0 17 p3 processp3 0 68 p4 processp4 0 24 mlfq mlfq3 17 25 dequep1 p2 p3 p4 0 finishqueue readyqueue mlfq roundrobindequep1 p2 p3 p4 17 mlfq calculateremainingbursttimeofprocessesmlfq finishqueue 0 mlfq calculateremainingbursttimeofprocessesreadyqueue 36 51 7 finishqueue readyqueue mlfq roundrobinreadyqueue 25 mlfq calculateremainingbursttimeofprocessesmlfq finishqueue 0 0 mlfq calculateremainingbursttimeofprocessesreadyqueue 11 26 this method updates waiting times of unfinished processes p1 processp1 0 53 p2 processp2 0 17 p3 processp3 0 68 p4 processp4 0 24 mlfq mlfq3 17 25 dequep1 p2 p3 p4 0 mlfq currenttime 10 p1 stoptime 5 mlfq updatewaitingtimep1 5 fcfsfirst come first served fcfs will be applied to mlfq s last queue a first came process will be finished at first p1 processp1 0 53 p2 processp2 0 17 p3 processp3 0 68 p4 processp4 0 24 mlfq mlfq3 17 25 dequep1 p2 p3 p4 0 mlfq firstcomefirstservedmlfq readyqueue mlfq calculatesequenceoffinishqueue p1 p2 p3 p4 if process s arrival time is later than current time update current time update waiting time of current process update current time finish the process and set the process s bursttime 0 set the process s turnaround time because it is finished set the completion time add the process to queue that has finished queue fcfs will finish all remaining processes rrround robin rr will be applied to mlfq s all queues except last queue all processes can t use cpu for time more than timeslice if the process consume cpu up to timeslice it will go back to ready queue p1 processp1 0 53 p2 processp2 0 17 p3 processp3 0 68 p4 processp4 0 24 mlfq mlfq3 17 25 dequep1 p2 p3 p4 0 finishqueue readyqueue mlfq roundrobinmlfq readyqueue 17 mlfq calculatesequenceoffinishqueue p2 just for 1 cycle and unfinished processes will go back to queue if process s arrival time is later than current time update current time update waiting time of unfinished processes if the burst time of process is bigger than timeslice use cpu for only timeslice update remaining burst time update end point time locate the process behind the queue because it is not finished use cpu for remaining burst time set burst time 0 because the process is finished set the finish time update the process turnaround time because it is finished add the process to queue that has finished queue return finished processes queue and remaining processes queue mlfqmulti level feedback queue p1 processp1 0 53 p2 processp2 0 17 p3 processp3 0 68 p4 processp4 0 24 mlfq mlfq3 17 25 dequep1 p2 p3 p4 0 finishqueue mlfq multilevelfeedbackqueue mlfq calculatesequenceoffinishqueue p2 p4 p1 p3 all queues except last one have roundrobin algorithm the last queue has firstcomefirstserved algorithm print total waiting times of processesp1 p2 p3 p4 print completion times of processesp1 p2 p3 p4 print total turnaround times of processesp1 p2 p3 p4 print sequence of finished processes process name arrival time of the process completion time of finished process or last interrupted time remaining burst time total time of the process wait in ready queue time from arrival time to completion time 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 total number of mlfq s queues time slice of queues that round robin algorithm applied unfinished process is in this ready_queue current time finished process is in this sequence queue 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 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 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 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 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 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 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 sequence deque of finished process current process if process s arrival time is later than current time update current time update waiting time of current process update current time finish the process and set the process s burst time 0 set the process s turnaround time because it is finished set the completion time add the process to queue that has finished queue add finished process to finish queue fcfs will finish all remaining processes 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 sequence deque of terminated process just for 1 cycle and unfinished processes will go back to queue current process if process s arrival time is later than current time update current time update waiting time of unfinished processes if the burst time of process is bigger than time slice use cpu for only time slice update remaining burst time update end point time locate the process behind the queue because it is not finished use cpu for remaining burst time set burst time 0 because the process is finished set the finish time update the process turnaround time because it is finished add the process to queue that has finished queue add finished process to finish queue return finished processes queue and remaining processes queue 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 the last queue has first_come_first_served algorithm print total waiting times of processes p1 p2 p3 p4 print completion times of processes p1 p2 p3 p4 print total turnaround times of processes p1 p2 p3 p4 print sequence of finished processes
from collections import deque class Process: def __init__(self, process_name: str, arrival_time: int, burst_time: int) -> None: self.process_name = process_name self.arrival_time = arrival_time self.stop_time = arrival_time self.burst_time = burst_time self.waiting_time = 0 self.turnaround_time = 0 class MLFQ: def __init__( self, number_of_queues: int, time_slices: list[int], queue: deque[Process], current_time: int, ) -> None: self.number_of_queues = number_of_queues self.time_slices = time_slices self.ready_queue = queue self.current_time = current_time 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() while len(ready_queue) != 0: cp = ready_queue.popleft() if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time self.update_waiting_time(cp) self.current_time += cp.burst_time cp.burst_time = 0 cp.turnaround_time = self.current_time - cp.arrival_time cp.stop_time = self.current_time finished.append(cp) self.finish_queue.extend(finished) return finished def round_robin( self, ready_queue: deque[Process], time_slice: int ) -> tuple[deque[Process], deque[Process]]: finished: deque[Process] = deque() for _ in range(len(ready_queue)): cp = ready_queue.popleft() if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time self.update_waiting_time(cp) if cp.burst_time > time_slice: self.current_time += time_slice cp.burst_time -= time_slice cp.stop_time = self.current_time ready_queue.append(cp) else: self.current_time += cp.burst_time cp.burst_time = 0 cp.stop_time = self.current_time cp.turnaround_time = self.current_time - cp.arrival_time finished.append(cp) self.finish_queue.extend(finished) return finished, ready_queue def multi_level_feedback_queue(self) -> deque[Process]: for i in range(self.number_of_queues - 1): finished, self.ready_queue = self.round_robin( self.ready_queue, self.time_slices[i] ) 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( f"waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [P1, P2, P3, P4])}" ) print( f"completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [P1, P2, P3, P4])}" ) print( f"turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [P1, P2, P3, P4])}" ) print( f"sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}" )
nonpreemptive shortest job first shortest execution time process is chosen for the next execution https www guru99 comshortestjobfirstsjfscheduling html https en wikipedia orgwikishortestjobnext calculate the waiting time of each processes return the waiting time for each process calculatewaitingtime0 1 2 10 5 8 3 0 9 13 calculatewaitingtime1 2 2 4 4 6 3 1 4 0 7 4 1 calculatewaitingtime0 0 0 12 2 10 3 12 0 2 initialize remainingtime to waitingtime when processes are not completed a process whose arrival time has passed and has remaining execution time is put into the readyprocess the shortest process in the readyprocess targetprocess is executed calculate the turnaround time of each process return the turnaround time for each process calculateturnaroundtime0 1 2 3 0 10 15 0 11 17 calculateturnaroundtime1 2 2 4 4 1 8 5 4 2 10 7 8 calculateturnaroundtime0 0 0 3 12 0 2 12 0 2 printing the result calculate the waiting time of each processes return the waiting time for each process calculate_waitingtime 0 1 2 10 5 8 3 0 9 13 calculate_waitingtime 1 2 2 4 4 6 3 1 4 0 7 4 1 calculate_waitingtime 0 0 0 12 2 10 3 12 0 2 initialize remaining_time to waiting_time when processes are not completed a process whose arrival time has passed and has remaining execution time is put into the ready_process the shortest process in the ready_process target_process is executed calculate the turnaround time of each process return the turnaround time for each process calculate_turnaroundtime 0 1 2 3 0 10 15 0 11 17 calculate_turnaroundtime 1 2 2 4 4 1 8 5 4 2 10 7 8 calculate_turnaroundtime 0 0 0 3 12 0 2 12 0 2 printing the result
from __future__ import annotations from statistics import mean def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: waiting_time = [0] * no_of_processes remaining_time = [0] * no_of_processes for i in range(no_of_processes): remaining_time[i] = burst_time[i] ready_process: list[int] = [] completed = 0 total_time = 0 while completed != no_of_processes: ready_process = [] target_process = -1 for i in range(no_of_processes): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(i) if len(ready_process) > 0: target_process = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: target_process = i total_time += burst_time[target_process] completed += 1 remaining_time[target_process] = 0 waiting_time[target_process] = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") no_of_processes = 4 burst_time = [2, 5, 3, 7] arrival_time = [0, 0, 0, 0] waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) turn_around_time = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( f"{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t" f"{waiting_time[i]}\t\t\t\t{turn_around_time[i]}" ) print(f"\nAverage waiting time = {mean(waiting_time):.5f}") print(f"Average turnaround time = {mean(turn_around_time):.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 orgwikiroundrobinscheduling calculate the waiting times of a list of processes that have a specified duration return the waiting time for each process calculatewaitingtimes10 5 8 13 10 13 calculatewaitingtimes4 6 3 1 5 8 9 6 calculatewaitingtimes12 2 10 12 2 12 calculateturnaroundtimes1 2 3 4 0 1 3 1 3 6 calculateturnaroundtimes10 3 7 10 6 11 20 9 18 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 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
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}")
shortest job remaining first please note arrival time and burst please use spaces to separate times entered calculate the waiting time of each processes return list of waiting times calculatewaitingtime1 2 3 4 3 3 5 1 4 0 3 5 0 calculatewaitingtime1 2 3 2 5 1 3 0 2 0 calculatewaitingtime2 3 5 1 2 1 0 copy the burst time into remainingtime process until all processes are completed find finish time of current process calculate waiting time increment time calculate the turn around time of each processes return list of turn around times calculateturnaroundtime3 3 5 1 4 0 3 5 0 3 6 10 1 calculateturnaroundtime3 3 2 0 3 3 6 calculateturnaroundtime8 10 1 3 1 0 3 9 10 4 this function calculates the average of the waiting turnaround times prints average waiting time average turn around time calculateaveragetimes0 3 5 0 3 6 10 1 4 average waiting time 2 00000 average turn around time 5 0 calculateaveragetimes2 3 3 6 2 average waiting time 2 50000 average turn around time 4 5 calculateaveragetimes10 4 3 2 7 6 3 average waiting time 5 66667 average turn around time 5 0 printing the dataframe calculate the waiting time of each processes return list of waiting times calculate_waitingtime 1 2 3 4 3 3 5 1 4 0 3 5 0 calculate_waitingtime 1 2 3 2 5 1 3 0 2 0 calculate_waitingtime 2 3 5 1 2 1 0 copy the burst time into remaining_time process until all processes are completed find finish time of current process calculate waiting time increment time calculate the turn around time of each processes return list of turn around times calculate_turnaroundtime 3 3 5 1 4 0 3 5 0 3 6 10 1 calculate_turnaroundtime 3 3 2 0 3 3 6 calculate_turnaroundtime 8 10 1 3 1 0 3 9 10 4 this function calculates the average of the waiting turnaround times prints average waiting time average turn around time calculate_average_times 0 3 5 0 3 6 10 1 4 average waiting time 2 00000 average turn around time 5 0 calculate_average_times 2 3 3 6 2 average waiting time 2 50000 average turn around time 4 5 calculate_average_times 10 4 3 2 7 6 3 average waiting time 5 66667 average turn around time 5 0 printing the dataframe
from __future__ import annotations import pandas as pd def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: remaining_time = [0] * no_of_processes waiting_time = [0] * no_of_processes for i in range(no_of_processes): remaining_time[i] = burst_time[i] complete = 0 increment_time = 0 minm = 999999999 short = 0 check = False while complete != no_of_processes: for j in range(no_of_processes): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: minm = remaining_time[j] short = j check = True if not check: increment_time += 1 continue remaining_time[short] -= 1 minm = remaining_time[short] if minm == 0: minm = 999999999 if remaining_time[short] == 0: complete += 1 check = False finish_time = increment_time + 1 finar = finish_time - arrival_time[short] waiting_time[short] = finar - burst_time[short] if waiting_time[short] < 0: waiting_time[short] = 0 increment_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time def calculate_average_times( waiting_time: list[int], turn_around_time: list[int], no_of_processes: int ) -> None: total_waiting_time = 0 total_turn_around_time = 0 for i in range(no_of_processes): total_waiting_time = total_waiting_time + waiting_time[i] total_turn_around_time = total_turn_around_time + turn_around_time[i] print(f"Average waiting time = {total_waiting_time / no_of_processes:.5f}") print("Average turn around time =", total_turn_around_time / no_of_processes) if __name__ == "__main__": print("Enter how many process you want to analyze") no_of_processes = int(input()) burst_time = [0] * no_of_processes arrival_time = [0] * no_of_processes processes = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print("Enter the arrival time and burst time for process:--" + str(i + 1)) arrival_time[i], burst_time[i] = map(int, input().split()) waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) bt = burst_time n = no_of_processes wt = waiting_time turn_around_time = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) fcfs = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ "Process", "BurstTime", "ArrivalTime", "WaitingTime", "TurnAroundTime", ], ) pd.set_option("display.max_rows", fcfs.shape[0] + 1) print(fcfs)
usrbinenv python3 usr bin env python3 type ignore
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths filepaths = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" upper_files = [file for file in filepaths if file != file.lower()] if upper_files: print(f"{len(upper_files)} files contain uppercase characters:") print("\n".join(upper_files) + "\n") space_files = [file for file in filepaths if " " in file] if space_files: print(f"{len(space_files)} files contain space characters:") print("\n".join(space_files) + "\n") hyphen_files = [file for file in filepaths if "-" in file] if hyphen_files: print(f"{len(hyphen_files)} files contain hyphen characters:") print("\n".join(hyphen_files) + "\n") nodir_files = [file for file in filepaths if os.sep not in file] if nodir_files: print(f"{len(nodir_files)} files are not in a directory:") print("\n".join(nodir_files) + "\n") bad_files = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
usrbinenv python3 converts a file path to a python module spec importlib util specfromfilelocationfilepath name strfilepath module importlib util modulefromspecspec type ignore spec loader execmodulemodule type ignore return module def allsolutionfilepaths listpathlib path return the pull request number which triggered this action with openos environgithubeventpath as file event json loadfile return eventpullrequesturl files def addedsolutionfilepath listpathlib path solutionfilepaths headers accept applicationvnd github v3json ization token os environgithubtoken files requests getgetfilesurl headersheaders json for file in files filepath pathlib path cwd joinpathfilefilename if filepath suffix py or filepath name startswith test or not filepath name startswithsol continue solutionfilepaths appendfilepath return solutionfilepaths def collectsolutionfilepaths listpathlib path if os environ getci and os environ getgithubeventname pullrequest return only if there are any otherwise default to all solutions if filepaths addedsolutionfilepath return filepaths return allsolutionfilepaths pytest mark parametrize solutionpath collectsolutionfilepaths idslambda path fpath parent namepath name def testprojecteulersolutionpath pathlib path none problemextract this part and pad it with zeroes for width 3 usr bin env python3 converts a file path to a python module type ignore type ignore collects all the solution file path in the project euler directory return the pull request number which triggered this action 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 return only if there are any otherwise default to all solutions testing for all project euler solutions problem_ extract this part and pad it with zeroes for width 3 type ignore
import hashlib import importlib.util import json import os import pathlib from types import ModuleType import pytest import requests 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) spec.loader.exec_module(module) 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 = requests.get(get_files_url(), headers=headers).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]: if os.environ.get("CI") and os.environ.get("GITHUB_EVENT_NAME") == "pull_request": if 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_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}"
usrbinenv python3 pure python implementations of binary search algorithms for doctests run the following command python3 m doctest v binarysearch py for manual testing run python3 binarysearch py 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 org3librarybisect htmlbisect bisectleft param sortedcollection some ascending sorted collection with comparable items param item item to bisect param lo lowest index to consider as in sortedcollectionlo hi param hi past the highest index to consider as in sortedcollectionlo hi return index i such that all values in sortedcollectionlo i are item and all values in sortedcollectioni hi are item examples bisectleft0 5 7 10 15 0 0 bisectleft0 5 7 10 15 6 2 bisectleft0 5 7 10 15 20 5 bisectleft0 5 7 10 15 15 1 3 3 bisectleft0 5 7 10 15 6 2 2 locates the first element in a sorted array that is larger than a given value it has the same interface as https docs python org3librarybisect htmlbisect bisectright param sortedcollection some ascending sorted collection with comparable items param item item to bisect param lo lowest index to consider as in sortedcollectionlo hi param hi past the highest index to consider as in sortedcollectionlo hi return index i such that all values in sortedcollectionlo i are item and all values in sortedcollectioni hi are item examples bisectright0 5 7 10 15 0 1 bisectright0 5 7 10 15 15 5 bisectright0 5 7 10 15 6 2 bisectright0 5 7 10 15 15 1 3 3 bisectright0 5 7 10 15 6 2 2 inserts a given value into a sorted array before other values with the same value it has the same interface as https docs python org3librarybisect htmlbisect insortleft param sortedcollection some ascending sorted collection with comparable items param item item to insert param lo lowest index to consider as in sortedcollectionlo hi param hi past the highest index to consider as in sortedcollectionlo hi examples sortedcollection 0 5 7 10 15 insortleftsortedcollection 6 sortedcollection 0 5 6 7 10 15 sortedcollection 0 0 5 5 7 7 10 10 15 15 item 5 5 insortleftsortedcollection item sortedcollection 0 0 5 5 5 5 7 7 10 10 15 15 item is sortedcollection1 true item is sortedcollection2 false sortedcollection 0 5 7 10 15 insortleftsortedcollection 20 sortedcollection 0 5 7 10 15 20 sortedcollection 0 5 7 10 15 insortleftsortedcollection 15 1 3 sortedcollection 0 5 7 15 10 15 inserts a given value into a sorted array after other values with the same value it has the same interface as https docs python org3librarybisect htmlbisect insortright param sortedcollection some ascending sorted collection with comparable items param item item to insert param lo lowest index to consider as in sortedcollectionlo hi param hi past the highest index to consider as in sortedcollectionlo hi examples sortedcollection 0 5 7 10 15 insortrightsortedcollection 6 sortedcollection 0 5 6 7 10 15 sortedcollection 0 0 5 5 7 7 10 10 15 15 item 5 5 insortrightsortedcollection item sortedcollection 0 0 5 5 5 5 7 7 10 10 15 15 item is sortedcollection1 false item is sortedcollection2 true sortedcollection 0 5 7 10 15 insortrightsortedcollection 20 sortedcollection 0 5 7 10 15 20 sortedcollection 0 5 7 10 15 insortrightsortedcollection 15 1 3 sortedcollection 0 5 7 15 10 15 pure implementation of a binary search algorithm in python be careful collection must be ascending sorted otherwise the result will be unpredictable param sortedcollection 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 binarysearch0 5 7 10 15 0 0 binarysearch0 5 7 10 15 15 4 binarysearch0 5 7 10 15 5 1 binarysearch0 5 7 10 15 6 1 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 sortedcollection 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 binarysearchstdlib0 5 7 10 15 0 0 binarysearchstdlib0 5 7 10 15 15 4 binarysearchstdlib0 5 7 10 15 5 1 binarysearchstdlib0 5 7 10 15 6 1 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 left0 and rightlensortedcollection1 param sortedcollection 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 binarysearchbyrecursion0 5 7 10 15 0 0 4 0 binarysearchbyrecursion0 5 7 10 15 15 0 4 4 binarysearchbyrecursion0 5 7 10 15 5 0 4 1 binarysearchbyrecursion0 5 7 10 15 6 0 4 1 pure implementation of an exponential search algorithm in python resources used https en wikipedia orgwikiexponentialsearch be careful collection must be ascending sorted otherwise result will be unpredictable param sortedcollection 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 olg i where i is index position of item if exist examples exponentialsearch0 5 7 10 15 0 0 exponentialsearch0 5 7 10 15 15 4 exponentialsearch0 5 7 10 15 5 1 exponentialsearch0 5 7 10 15 6 1 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 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 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 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 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 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 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 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 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 fastest to slowest type ignore operator
from __future__ import annotations import bisect 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 list(sorted_collection) != sorted(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_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 = ( 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) = }") 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}.")
this is pure python implementation of tree traversal algorithms root treenode1 treenode2 treenode2 treenode3 treenode3 treenode4 treenode4 treenode5 treenode5 treenode6 treenode6 treenode7 treenode7 root left root right treenode2 treenode3 treenode2 left treenode2 right treenode4 treenode5 treenode3 left treenode3 right treenode6 treenode7 preorderroot 1 2 4 5 3 6 7 root treenode1 treenode2 treenode2 treenode3 treenode3 treenode4 treenode4 treenode5 treenode5 treenode6 treenode6 treenode7 treenode7 root left root right treenode2 treenode3 treenode2 left treenode2 right treenode4 treenode5 treenode3 left treenode3 right treenode6 treenode7 inorderroot 4 2 5 1 6 3 7 root treenode1 treenode2 treenode2 treenode3 treenode3 treenode4 treenode4 treenode5 treenode5 treenode6 treenode6 treenode7 treenode7 root left root right treenode2 treenode3 treenode2 left treenode2 right treenode4 treenode5 treenode3 left treenode3 right treenode6 treenode7 postorderroot 4 5 2 6 7 3 1 root treenode1 treenode2 treenode2 treenode3 treenode3 treenode4 treenode4 treenode5 treenode5 treenode6 treenode6 treenode7 treenode7 root left root right treenode2 treenode3 treenode2 left treenode2 right treenode4 treenode5 treenode3 left treenode3 right treenode6 treenode7 levelorderroot 1 2 3 4 5 6 7 root treenode1 treenode2 treenode2 treenode3 treenode3 treenode4 treenode4 treenode5 treenode5 treenode6 treenode6 treenode7 treenode7 root left root right treenode2 treenode3 treenode2 left treenode2 right treenode4 treenode5 treenode3 left treenode3 right treenode6 treenode7 levelorderactualroot 1 2 3 4 5 6 7 iteration version root treenode1 treenode2 treenode2 treenode3 treenode3 treenode4 treenode4 treenode5 treenode5 treenode6 treenode6 treenode7 treenode7 root left root right treenode2 treenode3 treenode2 left treenode2 right treenode4 treenode5 treenode3 left treenode3 right treenode6 treenode7 preorderiterroot 1 2 4 5 3 6 7 end of while means current node doesn t have left child start to traverse its right child root treenode1 treenode2 treenode2 treenode3 treenode3 treenode4 treenode4 treenode5 treenode5 treenode6 treenode6 treenode7 treenode7 root left root right treenode2 treenode3 treenode2 left treenode2 right treenode4 treenode5 treenode3 left treenode3 right treenode6 treenode7 inorderiterroot 4 2 5 1 6 3 7 root treenode1 treenode2 treenode2 treenode3 treenode3 treenode4 treenode4 treenode5 treenode5 treenode6 treenode6 treenode7 treenode7 root left root right treenode2 treenode3 treenode2 left treenode2 right treenode4 treenode5 treenode3 left treenode3 right treenode6 treenode7 postorderiterroot 4 5 2 6 7 3 1 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 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 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 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 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 iteration version 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 start from root node find its left child end of while means current node doesn t have left child start to traverse its right child 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 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 to find the reversed order of post order store it in stack2 pop up from stack2 will be the post order
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 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 node in list_: q.put(node) 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: print(n.data, end=",") stack.append(n) n = n.left n = stack.pop() 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: n = stack1.pop() if n.left: stack1.append(n.left) if n.right: stack1.append(n.right) stack2.append(n) while stack2: 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())
iterate through the array from both sides to find the index of searchitem param array the array to be searched param searchitem the item to be searched return the index of searchitem if searchitem is in array else 1 examples doublelinearsearch1 5 5 10 1 0 doublelinearsearch1 5 5 10 5 1 doublelinearsearch1 5 5 10 100 1 doublelinearsearch1 5 5 10 10 3 define the start and end index of the given array returns 1 if searchitem is not found in array iterate through the array from both sides to find the index of search_item param array the array to be searched param search_item the item to be searched return the index of search_item if search_item is in array else 1 examples double_linear_search 1 5 5 10 1 0 double_linear_search 1 5 5 10 5 1 double_linear_search 1 5 5 10 100 1 double_linear_search 1 5 5 10 10 3 define the start and end index of the given array returns 1 if search_item is not found in array
from __future__ import annotations def double_linear_search(array: list[int], search_item: int) -> int: start_ind, end_ind = 0, len(array) - 1 while start_ind <= end_ind: if array[start_ind] == search_item: return start_ind elif array[end_ind] == search_item: return end_ind else: start_ind += 1 end_ind -= 1 return -1 if __name__ == "__main__": print(double_linear_search(list(range(100)), 40))
iterate through the array to find the index of key using recursion param listdata the list to be searched param key the key to be searched param left the index of first element param right the index of last element return the index of key value if found 1 otherwise searchlistrange0 11 5 5 search1 2 4 5 3 4 2 search1 2 4 5 3 6 1 search5 5 0 search 1 1 iterate through the array to find the index of key using recursion param list_data the list to be searched param key the key to be searched param left the index of first element param right the index of last element return the index of key value if found 1 otherwise search list range 0 11 5 5 search 1 2 4 5 3 4 2 search 1 2 4 5 3 6 1 search 5 5 0 search 1 1
def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int: right = right or len(list_data) - 1 if left > right: return -1 elif list_data[left] == key: return left elif list_data[right] == key: return right else: return search(list_data, key, left + 1, right - 1) if __name__ == "__main__": import doctest doctest.testmod()
this is pure python implementation of fibonacci search resources used https en wikipedia orgwikifibonaccisearchtechnique for doctests run following command python3 m doctest v fibonaccisearch py for manual testing run python3 fibonaccisearch py finds fibonacci number in index k parameters k index of fibonacci returns int fibonacci number in position k fibonacci0 0 fibonacci2 1 fibonacci5 5 fibonacci15 610 fibonacci a traceback most recent call last typeerror k must be an integer fibonacci5 traceback most recent call last valueerror k integer must be greater or equal to zero 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 fibonaccisearch4 5 6 7 4 0 fibonaccisearch4 5 6 7 10 1 fibonaccisearch18 2 18 0 fibonaccisearch5 5 0 fibonaccisearch a c d c 1 fibonaccisearch a c d f 1 fibonaccisearch 1 1 fibonaccisearch 1 4 7 4 1 fibonaccisearch 9 1 fibonaccisearchlistrange100 63 63 fibonaccisearchlistrange100 99 99 fibonaccisearchlistrange100 100 3 97 1 fibonaccisearchlistrange100 100 3 0 1 fibonaccisearchlistrange100 100 5 0 20 fibonaccisearchlistrange100 100 5 95 39 find m such that fm n where fi is the ith fibonacci number 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 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 find m such that f_m n where f_i is the i_th fibonacci number prevent out of range
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) 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 ) item_k_1 = arr[index_k] if item_k_1 == val: return index_k elif val < item_k_1: fibb_k -= 1 elif val > item_k_1: offset += fibonacci(fibb_k - 1) fibb_k -= 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
https en wikipedia orgwikihillclimbing an interface to define search problems the interface will be illustrated using the example of mathematical function the constructor of the search problem x the x coordinate of the current search state y the y coordinate of the current search state stepsize size of the step to take when looking for neighbors functiontooptimize a function to optimize having the signature fx y returns the output of the function called with current x and y coordinates def testfunctionx y return x y searchproblem0 0 1 testfunction score 0 0 0 0 searchproblem5 7 1 testfunction score 5 7 12 12 returns a list of coordinates of neighbors adjacent to the current coordinates neighbors 0 1 2 3 4 5 6 7 hash the string representation of the current search state check if the 2 objects are equal string representation of the current search state strsearchproblem0 0 1 none x 0 y 0 strsearchproblem2 5 1 none x 2 y 5 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 searchprob the search state at the start findmax if true the algorithm should find the maximum else the minimum maxx minx maxy miny the maximum and minimum bounds of x and y visualization if true a matplotlib graph is displayed maxiter number of times to run the iteration returns a search state having the maximum or minimum score going to direction with greatest ascent to direction with greatest descent we found at least one neighbor which improved the current state since we have no neighbor that improves the solution we stop the search starting the problem with initial coordinates 3 4 starting the problem with initial coordinates 12 47 https en wikipedia org wiki hill_climbing an interface to define search problems the interface will be illustrated using the example of mathematical function 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 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 returns a list of coordinates of neighbors adjacent to the current coordinates neighbors 0 1 2 3 _ 4 5 6 7 hash the string representation of the current search state check if the 2 objects are equal 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 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 list to store the current score at each iteration to hold the next best neighbor do not want to visit the same state again neighbor outside our bounds finding max going to direction with greatest ascent finding min to direction with greatest descent we found at least one neighbor which improved the current state since we have no neighbor that improves the solution we stop the search starting the problem with initial coordinates 3 4 starting the problem with initial coordinates 12 47
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 = [] 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 for neighbor in neighbors: if neighbor in visited: continue if ( neighbor.x > max_x or neighbor.x < min_x or neighbor.y > max_y or neighbor.y < min_y ): continue change = neighbor.score() - current_score if find_max: if change > max_change and change > 0: max_change = change next_state = neighbor else: if change < min_change and change < 0: min_change = change next_state = neighbor if next_state is not None: current_state = next_state else: 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) 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()}" ) 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()}" )
this is pure python implementation of interpolation search algorithm pure implementation of interpolation search algorithm in python be careful collection must be ascending sorted otherwise result will be unpredictable param sortedcollection some ascending sorted collection with comparable items param item item value to search return index of found item or none if item is not found avoid divided by 0 during interpolation out of range check 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 left0 and rightlensortedcollection1 param sortedcollection some ascending sorted collection with comparable items param item item value to search return index of found item or none if item is not found avoid divided by 0 during interpolation out of range check check if collection is ascending sorted if not raises py class valueerror param collection collection return true if collection is ascending sorted raise py class valueerror if collection is not ascending sorted examples assertsorted0 1 2 4 true assertsorted10 1 5 traceback most recent call last valueerror collection must be ascending sorted userinput input enter numbers separated by comma n strip collection intitem for item in userinput split try assertsortedcollection except valueerror sys exit sequence must be ascending sorted to apply interpolation search targetinput input enter a single number to be found in the list n target inttargetinput pure implementation of interpolation search algorithm in python 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 found item or none if item is not found avoid divided by 0 during interpolation out of range check 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 param sorted_collection some ascending sorted collection with comparable items param item item value to search return index of found item or none if item is not found avoid divided by 0 during interpolation out of range check check if collection is ascending sorted if not raises py class valueerror param collection collection return true if collection is ascending sorted raise py class valueerror if collection is not ascending sorted examples __assert_sorted 0 1 2 4 true __assert_sorted 10 1 5 traceback most recent call last valueerror collection must be ascending sorted user_input input enter numbers separated by comma n strip collection int item for item in user_input split try __assert_sorted collection except valueerror sys exit sequence must be ascending sorted to apply interpolation search target_input input enter a single number to be found in the list n target int target_input
def interpolation_search(sorted_collection, item): left = 0 right = len(sorted_collection) - 1 while left <= right: if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None point = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) if point < 0 or point >= len(sorted_collection): return None current_item = sorted_collection[point] if current_item == item: return point else: if point < left: right = left left = point elif point > right: left = right right = point else: if item < current_item: right = point - 1 else: left = point + 1 return None def interpolation_search_by_recursion(sorted_collection, item, left, right): if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None point = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) if point < 0 or point >= len(sorted_collection): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(sorted_collection, item, point, left) elif point > right: return interpolation_search_by_recursion(sorted_collection, item, right, left) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( sorted_collection, item, left, point - 1 ) else: return interpolation_search_by_recursion( sorted_collection, item, point + 1, right ) def __assert_sorted(collection): if collection != sorted(collection): raise ValueError("Collection must be ascending sorted") return True if __name__ == "__main__": import sys debug = 0 if debug == 1: collection = [10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("Sequence must be ascending sorted to apply interpolation search") target = 67 result = interpolation_search(collection, target) if result is not None: print(f"{target} found at positions: {result}") else: print("Not found")
pure python implementation of the jump search algorithm this algorithm iterates through a sorted collection with a step of n12 until the element compared is bigger than the one searched it will then perform a linear search until it matches the wanted number if not found it returns 1 https en wikipedia orgwikijumpsearch python implementation of the jump search algorithm return the index if the item is found otherwise return 1 examples jumpsearch0 1 2 3 4 5 3 3 jumpsearch5 2 1 1 2 jumpsearch0 5 10 20 8 1 jumpsearch0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 55 10 jumpsearchaa bb cc dd ee ff ee 4 python implementation of the jump search algorithm return the index if the item is found otherwise return 1 examples jump_search 0 1 2 3 4 5 3 3 jump_search 5 2 1 1 2 jump_search 0 5 10 20 8 1 jump_search 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 55 10 jump_search aa bb cc dd ee ff ee 4
import math from collections.abc import Sequence from typing import Any, Protocol, TypeVar class Comparable(Protocol): def __lt__(self, other: Any, /) -> bool: ... T = TypeVar("T", bound=Comparable) def jump_search(arr: Sequence[T], item: T) -> int: arr_size = len(arr) block_size = int(math.sqrt(arr_size)) prev = 0 step = block_size while arr[min(step, arr_size) - 1] < item: prev = step step += block_size if prev >= arr_size: return -1 while arr[prev] < item: prev += 1 if prev == min(step, arr_size): return -1 if arr[prev] == item: return prev return -1 if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() array = [int(item) for item in user_input.split(",")] x = int(input("Enter the number to be searched:\n")) res = jump_search(array, x) if res == -1: print("Number not found!") else: print(f"Number {x} is at index {res}")
this is pure python implementation of linear search algorithm for doctests run following command python3 m doctest v linearsearch py for manual testing run python3 linearsearch py a pure python implementation of a linear search algorithm param sequence a collection with comparable items as sorted items not required in linear search param target item value to search return index of found item or 1 if item is not found examples linearsearch0 5 7 10 15 0 0 linearsearch0 5 7 10 15 15 4 linearsearch0 5 7 10 15 5 1 linearsearch0 5 7 10 15 6 1 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 reclinearsearch0 30 500 100 700 0 4 0 0 reclinearsearch0 30 500 100 700 0 4 700 4 reclinearsearch0 30 500 100 700 0 4 30 1 reclinearsearch0 30 500 100 700 0 4 6 1 a pure python implementation of a linear search algorithm param sequence a collection with comparable items as sorted items not required in 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 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
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}")
a python implementation of the median of medians algorithm to select pivots for quickselect 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 on at any rank deterministically https en wikipedia orgwikimedianofmedians return the median of the input list param arr array to find median of return median of arr medianoffive2 4 5 7 899 5 medianoffive5 7 899 54 32 32 medianoffive5 4 3 2 4 medianoffive3 5 7 10 2 5 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 medianofmedians2 4 5 7 899 54 32 54 medianofmedians5 7 899 54 32 32 medianofmedians5 4 3 2 4 medianofmedians3 5 7 10 2 12 12 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 quickselect2 4 5 7 899 54 32 5 32 quickselect2 4 5 7 899 54 32 1 2 quickselect5 4 3 2 2 3 quickselect3 5 7 10 2 12 3 5 invalid input x is the estimated pivot by median of medians algorithm 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 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 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 x is the estimated pivot by median of medians algorithm
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: if target > len(arr): return -1 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]))
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 orgwikiquickselect 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 quickselect2 4 5 7 899 54 32 5 54 quickselect2 4 5 7 899 54 32 1 4 quickselect5 4 3 2 2 4 quickselect3 5 7 10 2 12 3 7 index lenitems 2 when trying to find the median value of index when items is sorted invalid input index is the pivot must be in smaller must be in larger 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 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 invalid input index is the pivot must be in smaller must be in larger
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): 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) if m <= index < m + count: return pivot elif m > index: return quick_select(smaller, index) else: return quick_select(larger, index - (m + count))
this is pure python implementation of sentinel linear search algorithm for doctests run following command python m doctest v sentinellinearsearch py or python3 m doctest v sentinellinearsearch py for manual testing run python sentinellinearsearch py 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 sentinellinearsearch0 5 7 10 15 0 0 sentinellinearsearch0 5 7 10 15 15 4 sentinellinearsearch0 5 7 10 15 5 1 sentinellinearsearch0 5 7 10 15 6 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
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")
pure python implementation of a binary search algorithm for doctests run following command python3 m doctest v simplebinarysearch py for manual testing run python3 simplebinarysearch py testlist 0 1 2 8 13 17 19 32 42 binarysearchtestlist 3 false binarysearchtestlist 13 true binarysearch4 4 5 6 7 4 true binarysearch4 4 5 6 7 10 false binarysearch18 2 18 true binarysearch5 5 true binarysearch a c d c true binarysearch a c d f false binarysearch 1 false binarysearch 1 1 8 1 true binarysearchrange5000 5000 10 80 true binarysearchrange5000 5000 10 1255 false binarysearchrange0 10000 5 2 false 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
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}")
https en wikipedia orgwikisimulatedannealing implementation of the simulated annealing algorithm we start with a given state find all its neighbors pick a random neighbor if that neighbor improves the solution we move in that direction if that neighbor does not improve the solution we generate a random real number between 0 and 1 if the number is within a certain range calculated using temperature we move in that direction else we pick another neighbor randomly and repeat the process args searchprob the search state at the start findmax if true the algorithm should find the minimum else the minimum maxx minx maxy miny the maximum and minimum bounds of x and y visualization if true a matplotlib graph is displayed starttemperate the initial temperate of the system when the program starts rateofdecrease the rate at which the temperate decreases in each iteration thresholdtemp the threshold temperature below which we end the search returns a search state having the maximum or minimum score temperature below threshold or could not find a suitable neighbor starting the problem with initial coordinates 12 47 starting the problem with initial coordinates 12 47 https en wikipedia org wiki simulated_annealing implementation of the simulated annealing algorithm we start with a given state find all its neighbors pick a random neighbor if that neighbor improves the solution we move in that direction if that neighbor does not improve the solution we generate a random real number between 0 and 1 if the number is within a certain range calculated using temperature we move in that direction else we pick another neighbor randomly and repeat the process args search_prob the search state at the start find_max if true the algorithm should find the minimum 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 start_temperate the initial temperate of the system when the program starts rate_of_decrease the rate at which the temperate decreases in each iteration threshold_temp the threshold temperature below which we end the search returns a search state having the maximum or minimum score till we do not find a neighbor that we can move to picking a random neighbor neighbor outside our bounds in case we are finding minimum improves the solution probability generation function random number within probability temperature below threshold or could not find a suitable neighbor starting the problem with initial coordinates 12 47 starting the problem with initial coordinates 12 47
import math import random from typing import Any from .hill_climbing import SearchProblem def simulated_annealing( 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, start_temperate: float = 100, rate_of_decrease: float = 0.01, threshold_temp: float = 1, ) -> Any: search_end = False current_state = search_prob current_temp = start_temperate scores = [] iterations = 0 best_state = None while not search_end: current_score = current_state.score() if best_state is None or current_score > best_state.score(): best_state = current_state scores.append(current_score) iterations += 1 next_state = None neighbors = current_state.get_neighbors() while ( next_state is None and neighbors ): index = random.randint(0, len(neighbors) - 1) picked_neighbor = neighbors.pop(index) change = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue if not find_max: change = change * -1 if change > 0: next_state = picked_neighbor else: probability = (math.e) ** ( change / current_temp ) if random.random() < probability: next_state = picked_neighbor current_temp = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: search_end = True else: current_state = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(iterations), scores) plt.xlabel("Iterations") plt.ylabel("Function values") plt.show() return best_state if __name__ == "__main__": def test_f1(x, y): return (x**2) + (y**2) prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1) local_min = simulated_annealing( 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()}" ) prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1) local_min = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The maximum 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 = simulated_annealing(prob, find_max=False, visualization=True) print( "The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " f"{local_min.score()}" ) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = simulated_annealing(prob, find_max=True, visualization=True) print( "The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " f"{local_min.score()}" )
this is pure python implementation of tabu search algorithm for a travelling salesman problem that the distances between the cities are symmetric the distance between city a and city b is the same between city b and city a the tsp can be represented into a graph the cities are represented by nodes and the distance between them is represented by the weight of the ark between the nodes the txt file with the graph has the form node1 node2 distancebetweennode1andnode2 node1 node3 distancebetweennode1andnode3 be careful node1 node2 and the distance between them must exist only once this means in the txt file should not exist node1 node2 distancebetweennode1andnode2 node2 node1 distancebetweennode2andnode1 for pytests run following command pytest for manual testing run python tabusearch py f yourfilename txt numberofiterationsoftabusearch s sizeoftabusearch e g python tabusearch py f tabudata2 txt i 4 s 3 pure implementation of generating a dictionary of neighbors and the cost with each neighbor given a path file that includes a graph param path the path to the txt file that includes the graph e g tabudata2 txt return dictofneighbours dictionary with key each node and value a list of lists with the neighbors of the node and the cost distance for each neighbor example of dictofneighbours dictofneighboursa b 20 c 18 d 22 e 26 this indicates the neighbors of node city a which has neighbor the node b with distance 20 the node c with distance 18 the node d with distance 22 and the node e with distance 26 pure implementation of generating the first solution for the tabu search to start with the redundant resolution strategy that means that we start from the starting node e g node a then we go to the city nearest lowest distance to this node let s assume is node c then we go to the nearest city of the node c etc till we have visited all cities and return to the starting node param path the path to the txt file that includes the graph e g tabudata2 txt param dictofneighbours dictionary with key each node and value a list of lists with the neighbors of the node and the cost distance for each neighbor return firstsolution the solution for the first iteration of tabu search using the redundant resolution strategy in a list return distanceoffirstsolution the total distance that travelling salesman will travel if he follows the path in firstsolution pure implementation of generating the neighborhood sorted by total distance of each solution from lowest to highest of a solution with 11 exchange method that means we exchange each node in a solution with each other node and generating a number of solution named neighborhood param solution the solution in which we want to find the neighborhood param dictofneighbours dictionary with key each node and value a list of lists with the neighbors of the node and the cost distance for each neighbor return neighborhoodofsolution a list that includes the solutions and the total distance of each solution in form of list that are produced with 11 exchange from the solution that the method took as an input example findneighborhood a c b d e a a b 20 c 18 d 22 e 26 c a 18 b 10 d 23 e 24 b a 20 c 10 d 11 e 12 e a 26 b 12 c 24 d 40 d a 22 b 11 c 23 e 40 doctest normalizewhitespace a e b d c a 90 a c d b e a 90 a d b c e a 93 a c b e d a 102 a c e d b a 113 a b c d e a 119 pure implementation of tabu search algorithm for a travelling salesman problem in python param firstsolution the solution for the first iteration of tabu search using the redundant resolution strategy in a list param distanceoffirstsolution the total distance that travelling salesman will travel if he follows the path in firstsolution param dictofneighbours dictionary with key each node and value a list of lists with the neighbors of the node and the cost distance for each neighbor param iters the number of iterations that tabu search will execute param size the size of tabu list return bestsolutionever the solution with the lowest distance that occurred during the execution of tabu search return bestcost the total distance that travelling salesman will travel if he follows the path in bestsolution ever pass the arguments to main method pure implementation of generating a dictionary of neighbors and the cost with each neighbor given a path file that includes a graph param path the path to the txt file that includes the graph e g tabudata2 txt return dict_of_neighbours dictionary with key each node and value a list of lists with the neighbors of the node and the cost distance for each neighbor example of dict_of_neighbours dict_of_neighbours a b 20 c 18 d 22 e 26 this indicates the neighbors of node city a which has neighbor the node b with distance 20 the node c with distance 18 the node d with distance 22 and the node e with distance 26 pure implementation of generating the first solution for the tabu search to start with the redundant resolution strategy that means that we start from the starting node e g node a then we go to the city nearest lowest distance to this node let s assume is node c then we go to the nearest city of the node c etc till we have visited all cities and return to the starting node param path the path to the txt file that includes the graph e g tabudata2 txt param dict_of_neighbours dictionary with key each node and value a list of lists with the neighbors of the node and the cost distance for each neighbor return first_solution the solution for the first iteration of tabu search using the redundant resolution strategy in a list return distance_of_first_solution the total distance that travelling salesman will travel if he follows the path in first_solution pure implementation of generating the neighborhood sorted by total distance of each solution from lowest to highest of a solution with 1 1 exchange method that means we exchange each node in a solution with each other node and generating a number of solution named neighborhood param solution the solution in which we want to find the neighborhood param dict_of_neighbours dictionary with key each node and value a list of lists with the neighbors of the node and the cost distance for each neighbor return neighborhood_of_solution a list that includes the solutions and the total distance of each solution in form of list that are produced with 1 1 exchange from the solution that the method took as an input example find_neighborhood a c b d e a a b 20 c 18 d 22 e 26 c a 18 b 10 d 23 e 24 b a 20 c 10 d 11 e 12 e a 26 b 12 c 24 d 40 d a 22 b 11 c 23 e 40 doctest normalize_whitespace a e b d c a 90 a c d b e a 90 a d b c e a 93 a c b e d a 102 a c e d b a 113 a b c d e a 119 pure implementation of tabu search algorithm for a travelling salesman problem in python param first_solution the solution for the first iteration of tabu search using the redundant resolution strategy in a list param distance_of_first_solution the total distance that travelling salesman will travel if he follows the path in first_solution param dict_of_neighbours dictionary with key each node and value a list of lists with the neighbors of the node and the cost distance for each neighbor param iters the number of iterations that tabu search will execute param size the size of tabu list return best_solution_ever the solution with the lowest distance that occurred during the execution of tabu search return best_cost the total distance that travelling salesman will travel if he follows the path in best_solution ever pass the arguments to main method
import argparse import copy def generate_neighbours(path): dict_of_neighbours = {} with open(path) as f: for line in f: if line.split()[0] not in dict_of_neighbours: _list = [] _list.append([line.split()[1], line.split()[2]]) dict_of_neighbours[line.split()[0]] = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: _list = [] _list.append([line.split()[0], line.split()[2]]) dict_of_neighbours[line.split()[1]] = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def generate_first_solution(path, dict_of_neighbours): with open(path) as f: start_node = f.read(1) end_node = start_node first_solution = [] visiting = start_node distance_of_first_solution = 0 while visiting not in first_solution: minim = 10000 for k in dict_of_neighbours[visiting]: if int(k[1]) < int(minim) and k[0] not in first_solution: minim = k[1] best_node = k[0] first_solution.append(visiting) distance_of_first_solution = distance_of_first_solution + int(minim) visiting = best_node first_solution.append(end_node) position = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 distance_of_first_solution = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1]) - 10000 ) return first_solution, distance_of_first_solution def find_neighborhood(solution, dict_of_neighbours): neighborhood_of_solution = [] for n in solution[1:-1]: idx1 = solution.index(n) for kn in solution[1:-1]: idx2 = solution.index(kn) if n == kn: continue _tmp = copy.deepcopy(solution) _tmp[idx1] = kn _tmp[idx2] = n distance = 0 for k in _tmp[:-1]: next_node = _tmp[_tmp.index(k) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: distance = distance + int(i[1]) _tmp.append(distance) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp) index_of_last_item_in_the_list = len(neighborhood_of_solution[0]) - 1 neighborhood_of_solution.sort(key=lambda x: x[index_of_last_item_in_the_list]) return neighborhood_of_solution def tabu_search( first_solution, distance_of_first_solution, dict_of_neighbours, iters, size ): count = 1 solution = first_solution tabu_list = [] best_cost = distance_of_first_solution best_solution_ever = solution while count <= iters: neighborhood = find_neighborhood(solution, dict_of_neighbours) index_of_best_solution = 0 best_solution = neighborhood[index_of_best_solution] best_cost_index = len(best_solution) - 1 found = False while not found: i = 0 while i < len(best_solution): if best_solution[i] != solution[i]: first_exchange_node = best_solution[i] second_exchange_node = solution[i] break i = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node]) found = True solution = best_solution[:-1] cost = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: best_cost = cost best_solution_ever = solution else: index_of_best_solution = index_of_best_solution + 1 best_solution = neighborhood[index_of_best_solution] if len(tabu_list) >= size: tabu_list.pop(0) count = count + 1 return best_solution_ever, best_cost def main(args=None): dict_of_neighbours = generate_neighbours(args.File) first_solution, distance_of_first_solution = generate_first_solution( args.File, dict_of_neighbours ) best_sol, best_cost = tabu_search( first_solution, distance_of_first_solution, dict_of_neighbours, args.Iterations, args.Size, ) print(f"Best solution: {best_sol}, with total distance: {best_cost}.") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Tabu Search") parser.add_argument( "-f", "--File", type=str, help="Path to the file containing the data", required=True, ) parser.add_argument( "-i", "--Iterations", type=int, help="How many iterations the algorithm should perform", required=True, ) parser.add_argument( "-s", "--Size", type=int, help="Size of the tabu list", required=True ) main(parser.parse_args())
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 olog3 n space complexity o1 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 this is the linear search that will occur after the search space has become smaller perform linear search in list returns 1 if element is not found parameters left int left index bound right int right index bound array listint list of elements to be searched on target int element that is searched returns int index of element that is looked for examples linsearch0 4 4 5 6 7 7 3 linsearch0 3 4 5 6 7 7 1 linsearch0 2 18 2 18 0 linsearch0 1 5 5 0 linsearch0 3 a c d c 1 linsearch0 3 1 4 1 1 0 linsearch0 3 1 4 1 1 2 iterative method of the ternary search algorithm testlist 0 1 2 8 13 17 19 32 42 iteternarysearchtestlist 3 1 iteternarysearchtestlist 13 4 iteternarysearch4 5 6 7 4 0 iteternarysearch4 5 6 7 10 1 iteternarysearch18 2 18 0 iteternarysearch5 5 0 iteternarysearch a c d c 1 iteternarysearch a c d f 1 iteternarysearch 1 1 iteternarysearch 1 4 1 1 0 recursive method of the ternary search algorithm testlist 0 1 2 8 13 17 19 32 42 recternarysearch0 lentestlist testlist 3 1 recternarysearch4 lentestlist testlist 42 8 recternarysearch0 2 4 5 6 7 4 0 recternarysearch0 3 4 5 6 7 10 1 recternarysearch0 1 18 2 18 0 recternarysearch0 1 5 5 0 recternarysearch0 2 a c d c 1 recternarysearch0 2 a c d f 1 recternarysearch0 0 1 1 recternarysearch0 3 1 4 1 1 0 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 this is the linear search that will occur after the search space has become smaller 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 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 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
from __future__ import annotations precision = 10 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 else: 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")
bead sort only works for sequences of nonnegative integers https en wikipedia orgwikibeadsort beadsort6 11 12 4 1 5 1 4 5 6 11 12 beadsort9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 beadsort5 0 4 3 0 3 4 5 beadsort8 2 1 1 2 8 beadsort1 9 0 0 0 1 9 traceback most recent call last typeerror sequence must be list of nonnegative integers beadsorthello world traceback most recent call last typeerror sequence must be list of nonnegative integers bead_sort 6 11 12 4 1 5 1 4 5 6 11 12 bead_sort 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 bead_sort 5 0 4 3 0 3 4 5 bead_sort 8 2 1 1 2 8 bead_sort 1 9 0 0 0 1 9 traceback most recent call last typeerror sequence must be list of non negative integers bead_sort hello world traceback most recent call last typeerror sequence must be list of non negative integers
def bead_sort(sequence: list) -> list: if any(not isinstance(x, int) or x < 0 for x in sequence): raise TypeError("Sequence must be list of non-negative integers") for _ in range(len(sequence)): for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
this is a pure python implementation of the binary insertion sort algorithm for doctests run following command python m doctest v binaryinsertionsort py or python3 m doctest v binaryinsertionsort py for manual testing run python binaryinsertionsort py sorts a list using the binary insertion sort algorithm param collection a mutable ordered collection with comparable items return the same collection ordered in ascending order examples binaryinsertionsort0 4 1234 4 1 0 1 4 4 1234 binaryinsertionsort sorted true binaryinsertionsort1 2 3 sorted1 2 3 true lst d a b e c binaryinsertionsortlst sortedlst true import random collection random samplerange50 50 100 binaryinsertionsortcollection sortedcollection true import string collection random choicesstring asciiletters string digits k100 binaryinsertionsortcollection sortedcollection true sorts a list using the binary insertion sort algorithm param collection a mutable ordered collection with comparable items return the same collection ordered in ascending order examples binary_insertion_sort 0 4 1234 4 1 0 1 4 4 1234 binary_insertion_sort sorted true binary_insertion_sort 1 2 3 sorted 1 2 3 true lst d a b e c binary_insertion_sort lst sorted lst true import random collection random sample range 50 50 100 binary_insertion_sort collection sorted collection true import string collection random choices string ascii_letters string digits k 100 binary_insertion_sort collection sorted collection true
def binary_insertion_sort(collection: list) -> list: n = len(collection) for i in range(1, n): value_to_insert = collection[i] low = 0 high = i - 1 while low <= high: mid = (low + high) // 2 if value_to_insert < collection[mid]: high = mid - 1 else: low = mid + 1 for j in range(i, low, -1): collection[j] = collection[j - 1] collection[low] = value_to_insert return collection if __name__ == "__main": user_input = input("Enter numbers separated by a comma:\n").strip() try: unsorted = [int(item) for item in user_input.split(",")] except ValueError: print("Invalid input. Please enter valid integers separated by commas.") raise print(f"{binary_insertion_sort(unsorted) = }")
python program for bitonic sort note that this program works only when size of input is a power of 2 compare the value at given index1 and index2 of the array and swap them as per the given direction the parameter direction indicates the sorting direction ascending1 or descending0 if ai aj agrees with the direction then ai and aj are interchanged arr 12 42 21 1 compandswaparr 1 2 1 arr 12 21 42 1 compandswaparr 1 2 0 arr 12 42 21 1 compandswaparr 0 3 1 arr 1 42 21 12 compandswaparr 0 3 0 arr 12 42 21 1 it recursively sorts a bitonic sequence in ascending order if direction 1 and in descending if direction 0 the sequence to be sorted starts at index position low the parameter length is the number of elements to be sorted arr 12 42 21 1 bitonicmergearr 0 4 1 arr 21 1 12 42 bitonicmergearr 0 4 0 arr 42 12 1 21 this function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders and then calls bitonicmerge to make them in the same order arr 12 34 92 23 0 121 167 145 bitonicsortarr 0 8 1 arr 167 121 23 0 12 34 92 145 bitonicsortarr 0 8 0 arr 145 92 34 12 0 23 121 167 compare the value at given index1 and index2 of the array and swap them as per the given direction the parameter direction indicates the sorting direction ascending 1 or descending 0 if a i a j agrees with the direction then a i and a j are interchanged arr 12 42 21 1 comp_and_swap arr 1 2 1 arr 12 21 42 1 comp_and_swap arr 1 2 0 arr 12 42 21 1 comp_and_swap arr 0 3 1 arr 1 42 21 12 comp_and_swap arr 0 3 0 arr 12 42 21 1 it recursively sorts a bitonic sequence in ascending order if direction 1 and in descending if direction 0 the sequence to be sorted starts at index position low the parameter length is the number of elements to be sorted arr 12 42 21 1 bitonic_merge arr 0 4 1 arr 21 1 12 42 bitonic_merge arr 0 4 0 arr 42 12 1 21 this function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders and then calls bitonic_merge to make them in the same order arr 12 34 92 23 0 121 167 145 bitonic_sort arr 0 8 1 arr 167 121 23 0 12 34 92 145 bitonic_sort arr 0 8 0 arr 145 92 34 12 0 23 121 167
from __future__ import annotations def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> None: if (direction == 1 and array[index1] > array[index2]) or ( direction == 0 and array[index1] < array[index2] ): array[index1], array[index2] = array[index2], array[index1] def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> None: if length > 1: middle = int(length / 2) for i in range(low, low + middle): comp_and_swap(array, i, i + middle, direction) bitonic_merge(array, low, middle, direction) bitonic_merge(array, low + middle, middle, direction) def bitonic_sort(array: list[int], low: int, length: int, direction: int) -> None: if length > 1: middle = int(length / 2) bitonic_sort(array, low, middle, 1) bitonic_sort(array, low + middle, middle, 0) bitonic_merge(array, low, length, direction) if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item.strip()) for item in user_input.split(",")] bitonic_sort(unsorted, 0, len(unsorted), 1) print("\nSorted array in ascending order is: ", end="") print(*unsorted, sep=", ") bitonic_merge(unsorted, 0, len(unsorted), 0) print("Sorted array in descending order is: ", end="") print(*unsorted, sep=", ")
this is a pure python implementation of the bogosort algorithm also known as permutation sort stupid sort slowsort shotgun sort or monkey sort bogosort generates random permutations until it guesses the correct one more info on https en wikipedia orgwikibogosort for doctests run following command python m doctest v bogosort py or python3 m doctest v bogosort py for manual testing run python bogosort py pure implementation of the bogosort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples bogosort0 5 3 2 2 0 2 2 3 5 bogosort bogosort2 5 45 45 5 2 pure implementation of the bogosort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples bogo_sort 0 5 3 2 2 0 2 2 3 5 bogo_sort bogo_sort 2 5 45 45 5 2
import random def bogo_sort(collection): def is_sorted(collection): for i in range(len(collection) - 1): if collection[i] > collection[i + 1]: return False return True while not is_sorted(collection): random.shuffle(collection) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(bogo_sort(unsorted))
pure implementation of bubble sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples bubblesortiterative0 5 2 3 2 0 2 2 3 5 bubblesortiterative bubblesortiterative2 45 5 45 5 2 bubblesortiterative23 0 6 4 34 23 4 0 6 34 bubblesortiterative0 5 2 3 2 sorted0 5 2 3 2 true bubblesortiterative sorted true bubblesortiterative2 45 5 sorted2 45 5 true bubblesortiterative23 0 6 4 34 sorted23 0 6 4 34 true bubblesortiterative d a b e sorted d a b e true bubblesortiterative z a y b x c a b c x y z bubblesortiterative1 1 3 3 5 5 7 7 2 2 4 4 6 6 1 1 2 2 3 3 4 4 5 5 6 6 7 7 bubblesortiterative1 3 3 5 7 7 2 4 4 6 1 2 3 3 4 4 5 6 7 7 import random collectionarg random samplerange50 50 100 bubblesortiterativecollectionarg sortedcollectionarg true import string collectionarg random choicesstring asciiletters string digits k100 bubblesortiterativecollectionarg sortedcollectionarg true it is similar iterative bubble sort but recursive param collection mutable ordered sequence of elements return the same list in ascending order examples bubblesortrecursive0 5 2 3 2 0 2 2 3 5 bubblesortiterative bubblesortrecursive2 45 5 45 5 2 bubblesortrecursive23 0 6 4 34 23 4 0 6 34 bubblesortrecursive0 5 2 3 2 sorted0 5 2 3 2 true bubblesortrecursive sorted true bubblesortrecursive2 45 5 sorted2 45 5 true bubblesortrecursive23 0 6 4 34 sorted23 0 6 4 34 true bubblesortrecursive d a b e sorted d a b e true bubblesortrecursive z a y b x c a b c x y z bubblesortrecursive1 1 3 3 5 5 7 7 2 2 4 4 6 6 1 1 2 2 3 3 4 4 5 5 6 6 7 7 bubblesortrecursive1 3 3 5 7 7 2 4 4 6 1 2 3 3 4 4 5 6 7 7 import random collectionarg random samplerange50 50 100 bubblesortrecursivecollectionarg sortedcollectionarg true import string collectionarg random choicesstring asciiletters string digits k100 bubblesortrecursivecollectionarg sortedcollectionarg true benchmark iterative seems slightly faster than recursive pure implementation of bubble sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples bubble_sort_iterative 0 5 2 3 2 0 2 2 3 5 bubble_sort_iterative bubble_sort_iterative 2 45 5 45 5 2 bubble_sort_iterative 23 0 6 4 34 23 4 0 6 34 bubble_sort_iterative 0 5 2 3 2 sorted 0 5 2 3 2 true bubble_sort_iterative sorted true bubble_sort_iterative 2 45 5 sorted 2 45 5 true bubble_sort_iterative 23 0 6 4 34 sorted 23 0 6 4 34 true bubble_sort_iterative d a b e sorted d a b e true bubble_sort_iterative z a y b x c a b c x y z bubble_sort_iterative 1 1 3 3 5 5 7 7 2 2 4 4 6 6 1 1 2 2 3 3 4 4 5 5 6 6 7 7 bubble_sort_iterative 1 3 3 5 7 7 2 4 4 6 1 2 3 3 4 4 5 6 7 7 import random collection_arg random sample range 50 50 100 bubble_sort_iterative collection_arg sorted collection_arg true import string collection_arg random choices string ascii_letters string digits k 100 bubble_sort_iterative collection_arg sorted collection_arg true stop iteration if the collection is sorted it is similar iterative bubble sort but recursive param collection mutable ordered sequence of elements return the same list in ascending order examples bubble_sort_recursive 0 5 2 3 2 0 2 2 3 5 bubble_sort_iterative bubble_sort_recursive 2 45 5 45 5 2 bubble_sort_recursive 23 0 6 4 34 23 4 0 6 34 bubble_sort_recursive 0 5 2 3 2 sorted 0 5 2 3 2 true bubble_sort_recursive sorted true bubble_sort_recursive 2 45 5 sorted 2 45 5 true bubble_sort_recursive 23 0 6 4 34 sorted 23 0 6 4 34 true bubble_sort_recursive d a b e sorted d a b e true bubble_sort_recursive z a y b x c a b c x y z bubble_sort_recursive 1 1 3 3 5 5 7 7 2 2 4 4 6 6 1 1 2 2 3 3 4 4 5 5 6 6 7 7 bubble_sort_recursive 1 3 3 5 7 7 2 4 4 6 1 2 3 3 4 4 5 6 7 7 import random collection_arg random sample range 50 50 100 bubble_sort_recursive collection_arg sorted collection_arg true import string collection_arg random choices string ascii_letters string digits k 100 bubble_sort_recursive collection_arg sorted collection_arg true benchmark iterative seems slightly faster than recursive
from typing import Any def bubble_sort_iterative(collection: list[Any]) -> list[Any]: length = len(collection) for i in reversed(range(length)): swapped = False for j in range(i): if collection[j] > collection[j + 1]: swapped = True collection[j], collection[j + 1] = collection[j + 1], collection[j] if not swapped: break return collection def bubble_sort_recursive(collection: list[Any]) -> list[Any]: length = len(collection) swapped = False for i in range(length - 1): if collection[i] > collection[i + 1]: collection[i], collection[i + 1] = collection[i + 1], collection[i] swapped = True return collection if not swapped else bubble_sort_recursive(collection) if __name__ == "__main__": import doctest from random import sample from timeit import timeit doctest.testmod() num_runs = 10_000 unsorted = sample(range(-50, 50), 100) timer_iterative = timeit( "bubble_sort_iterative(unsorted[:])", globals=globals(), number=num_runs ) print("\nIterative bubble sort:") print(*bubble_sort_iterative(unsorted), sep=",") print(f"Processing time (iterative): {timer_iterative:.5f}s for {num_runs:,} runs") unsorted = sample(range(-50, 50), 100) timer_recursive = timeit( "bubble_sort_recursive(unsorted[:])", globals=globals(), number=num_runs ) print("\nRecursive bubble sort:") print(*bubble_sort_recursive(unsorted), sep=",") print(f"Processing time (recursive): {timer_recursive:.5f}s for {num_runs:,} runs")
usrbinenv python3 illustrate how to implement bucket sort algorithm 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 on log n because of timsort average case on n2k k where k is the number of buckets if k on time complexity is on source https en wikipedia orgwikibucketsort data 1 2 5 0 bucketsortdata sorteddata true data 9 8 7 6 12 bucketsortdata sorteddata true data 4 1 2 1 2 9 bucketsortdata sorteddata true bucketsort sorted true data 1e10 1e10 bucketsortdata sorteddata true import random collection random samplerange50 50 50 bucketsortcollection sortedcollection true usr bin env python3 illustrate how to implement bucket sort algorithm 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 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
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) 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]
this is a python implementation of the circle sort algorithm for doctests run following command python3 m doctest v circlesort py for manual testing run python3 circlesort py a pure python implementation of circle sort algorithm param collection a mutable collection of comparable items in any order return the same collection in ascending order examples circlesort0 5 3 2 2 0 2 2 3 5 circlesort circlesort2 5 0 45 45 2 0 5 collections 0 5 3 2 2 2 5 0 45 allsortedcollection circlesortcollection for collection in collections true arr 5 4 3 2 1 circlesortutillst 0 2 true arr 3 4 5 2 1 a pure python implementation of circle sort algorithm param collection a mutable collection of comparable items in any order return the same collection in ascending order examples circle_sort 0 5 3 2 2 0 2 2 3 5 circle_sort circle_sort 2 5 0 45 45 2 0 5 collections 0 5 3 2 2 2 5 0 45 all sorted collection circle_sort collection for collection in collections true arr 5 4 3 2 1 circle_sort_util lst 0 2 true arr 3 4 5 2 1
def circle_sort(collection: list) -> list: if len(collection) < 2: return collection def circle_sort_util(collection: list, low: int, high: int) -> bool: swapped = False if low == high: return swapped left = low right = high while left < right: if collection[left] > collection[right]: collection[left], collection[right] = ( collection[right], collection[left], ) swapped = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: collection[left], collection[right + 1] = ( collection[right + 1], collection[left], ) swapped = True mid = low + int((high - low) / 2) left_swap = circle_sort_util(collection, low, mid) right_swap = circle_sort_util(collection, mid + 1, high) return swapped or left_swap or right_swap is_not_sorted = True while is_not_sorted is True: is_not_sorted = circle_sort_util(collection, 0, len(collection) - 1) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(circle_sort(unsorted))
an implementation of the cocktail shaker sort algorithm in pure python https en wikipedia orgwikicocktailshakersort sorts a list using the cocktail shaker sort algorithm param arr list of elements to be sorted return sorted list cocktailshakersort4 5 2 1 2 1 2 2 4 5 cocktailshakersort4 5 0 1 2 11 4 0 1 2 5 11 cocktailshakersort0 1 2 4 4 4 2 2 2 4 0 1 2 2 4 4 cocktailshakersort1 2 3 4 5 1 2 3 4 5 cocktailshakersort4 5 24 7 11 24 11 7 5 4 cocktailshakersortelderberry banana date apple cherry apple banana cherry date elderberry cocktailshakersort4 5 24 7 11 traceback most recent call last typeerror tuple object does not support item assignment pass from left to right pass from right to left sorts a list using the cocktail shaker sort algorithm param arr list of elements to be sorted return sorted list cocktail_shaker_sort 4 5 2 1 2 1 2 2 4 5 cocktail_shaker_sort 4 5 0 1 2 11 4 0 1 2 5 11 cocktail_shaker_sort 0 1 2 4 4 4 2 2 2 4 0 1 2 2 4 4 cocktail_shaker_sort 1 2 3 4 5 1 2 3 4 5 cocktail_shaker_sort 4 5 24 7 11 24 11 7 5 4 cocktail_shaker_sort elderberry banana date apple cherry apple banana cherry date elderberry cocktail_shaker_sort 4 5 24 7 11 traceback most recent call last typeerror tuple object does not support item assignment pass from left to right decrease the end pointer after each pass pass from right to left increase the start pointer after each pass
def cocktail_shaker_sort(arr: list[int]) -> list[int]: start, end = 0, len(arr) - 1 while start < end: swapped = False for i in range(start, end): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] swapped = True if not swapped: break end -= 1 for i in range(end, start, -1): if arr[i] < arr[i - 1]: arr[i], arr[i - 1] = arr[i - 1], arr[i] swapped = True if not swapped: break start += 1 return arr if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{cocktail_shaker_sort(unsorted) = }")
this is pure python implementation of comb sort algorithm comb sort is a relatively simple sorting algorithm originally designed by wlodzimierz dobosiewicz in 1980 it was rediscovered by stephen lacey and richard box in 1991 comb sort improves on bubble sort algorithm in bubble sort distance or gap between two compared elements is always one comb sort improvement is that gap can be much more than 1 in order to prevent slowing down by small values at the end of a list more info on https en wikipedia orgwikicombsort for doctests run following command python m doctest v combsort py or python3 m doctest v combsort py for manual testing run python combsort py pure implementation of comb sort algorithm in python param data mutable collection with comparable items return the same collection in ascending order examples combsort0 5 3 2 2 0 2 2 3 5 combsort combsort99 45 7 8 2 0 15 3 15 7 0 2 3 8 45 99 update the gap value for a next comb swap values pure implementation of comb sort algorithm in python param data mutable collection with comparable items return the same collection in ascending order examples comb_sort 0 5 3 2 2 0 2 2 3 5 comb_sort comb_sort 99 45 7 8 2 0 15 3 15 7 0 2 3 8 45 99 update the gap value for a next comb swap values
def comb_sort(data: list) -> list: shrink_factor = 1.3 gap = len(data) completed = False while not completed: gap = int(gap / shrink_factor) if gap <= 1: completed = True index = 0 while index + gap < len(data): if data[index] > data[index + gap]: data[index], data[index + gap] = data[index + gap], data[index] completed = False index += 1 return data if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(comb_sort(unsorted))
this is pure python implementation of counting sort algorithm for doctests run following command python m doctest v countingsort py or python3 m doctest v countingsort py for manual testing run python countingsort py pure implementation of counting sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples countingsort0 5 3 2 2 0 2 2 3 5 countingsort countingsort2 5 45 45 5 2 if the collection is empty returns empty get some information about the collection create the counting array count how much a number appears in the collection sum each position with it s predecessors now countingarri tells us how many elements i has in the collection create the output collection place the elements in the output respecting the original order stable sort from end to begin updating countingarr countingsortstringthisisthestring eghhiiinrsssttt test string sort pure implementation of counting sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples counting_sort 0 5 3 2 2 0 2 2 3 5 counting_sort counting_sort 2 5 45 45 5 2 if the collection is empty returns empty get some information about the collection create the counting array count how much a number appears in the collection sum each position with it s predecessors now counting_arr i tells us how many elements i has in the collection create the output collection place the elements in the output respecting the original order stable sort from end to begin updating counting_arr counting_sort_string thisisthestring eghhiiinrsssttt test string sort
def counting_sort(collection): if collection == []: return [] coll_len = len(collection) coll_max = max(collection) coll_min = min(collection) counting_arr_length = coll_max + 1 - coll_min counting_arr = [0] * counting_arr_length for number in collection: counting_arr[number - coll_min] += 1 for i in range(1, counting_arr_length): counting_arr[i] = counting_arr[i] + counting_arr[i - 1] ordered = [0] * coll_len for i in reversed(range(coll_len)): ordered[counting_arr[collection[i] - coll_min] - 1] = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def counting_sort_string(string): return "".join([chr(i) for i in counting_sort([ord(c) for c in string])]) if __name__ == "__main__": assert counting_sort_string("thisisthestring") == "eghhiiinrsssttt" user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(counting_sort(unsorted))
code contributed by honey sharma source https en wikipedia orgwikicyclesort cyclesort4 3 2 1 1 2 3 4 cyclesort4 20 0 50 100 1 50 4 1 0 20 100 cyclesort 1 2 1 3 8 0 8 0 2 0 1 1 3 cyclesort cycle_sort 4 3 2 1 1 2 3 4 cycle_sort 4 20 0 50 100 1 50 4 1 0 20 100 cycle_sort 1 2 1 3 8 0 8 0 2 0 1 1 3 cycle_sort
def cycle_sort(array: list) -> list: array_len = len(array) for cycle_start in range(array_len - 1): item = array[cycle_start] pos = cycle_start for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 if pos == cycle_start: continue while item == array[pos]: pos += 1 array[pos], item = item, array[pos] while pos != cycle_start: pos = cycle_start for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 while item == array[pos]: pos += 1 array[pos], item = item, array[pos] return array if __name__ == "__main__": assert cycle_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert cycle_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
this sorting algorithm sorts an array using the principle of bubble sort but does it both from left to right and right to left hence it s called double sort param collection mutable ordered sequence of elements return the same collection in ascending order examples doublesort1 2 3 4 5 6 7 7 6 5 4 3 2 1 doublesort doublesort1 2 3 4 5 6 6 5 4 3 2 1 doublesort3 10 16 42 29 sorted3 10 16 42 29 true apply the bubble sort algorithm from left to right or forwards apply the bubble sort algorithm from right to left or backwards allow the user to input the elements of the list on one line this sorting algorithm sorts an array using the principle of bubble sort but does it both from left to right and right to left hence it s called double sort param collection mutable ordered sequence of elements return the same collection in ascending order examples double_sort 1 2 3 4 5 6 7 7 6 5 4 3 2 1 double_sort double_sort 1 2 3 4 5 6 6 5 4 3 2 1 double_sort 3 10 16 42 29 sorted 3 10 16 42 29 true we don t need to traverse to end of list as apply the bubble sort algorithm from left to right or forwards apply the bubble sort algorithm from right to left or backwards allow the user to input the elements of the list on one line
from typing import Any def double_sort(collection: list[Any]) -> list[Any]: no_of_elements = len(collection) for _ in range( int(((no_of_elements - 1) / 2) + 1) ): for j in range(no_of_elements - 1): if collection[j + 1] < collection[j]: collection[j], collection[j + 1] = collection[j + 1], collection[j] if collection[no_of_elements - 1 - j] < collection[no_of_elements - 2 - j]: ( collection[no_of_elements - 1 - j], collection[no_of_elements - 2 - j], ) = ( collection[no_of_elements - 2 - j], collection[no_of_elements - 1 - j], ) return collection if __name__ == "__main__": unsorted = [int(x) for x in input("Enter the list to be sorted: ").split() if x] print("the sorted list is") print(f"{double_sort(unsorted) = }")
a pure implementation of dutch national flag dnf sort algorithm in python dutch national flag algorithm is an algorithm originally designed by edsger dijkstra it is the most optimal sort for 3 unique values eg 0 1 2 in a sequence dnf can sort a sequence of n size with 0 ai 2 at guaranteed on complexity in a single pass the flag of the netherlands consists of three colors white red and blue the task is to randomly arrange balls of white red and blue in such a way that balls of the same color are placed together dnf sorts a sequence of 0 1 and 2 s in linear time that does not consume any extra space this algorithm can be implemented only on a sequence that contains three unique elements 1 time complexity is on 2 space complexity is o1 more info on https en wikipedia orgwikidutchnationalflagproblem for doctests run following command python3 m doctest v dutchnationalflagsort py for manual testing run python dnfsort py python program to sort a sequence containing only 0 1 and 2 in a single pass a pure python implementation of dutch national flag sort algorithm param data 3 unique integer values e g 0 1 2 in an sequence return the same collection in ascending order dutchnationalflagsort dutchnationalflagsort0 0 dutchnationalflagsort2 1 0 0 1 2 0 0 1 1 2 2 dutchnationalflagsort0 1 1 0 1 2 1 2 0 0 0 1 0 0 0 0 0 1 1 1 1 1 2 2 dutchnationalflagsortabacab traceback most recent call last valueerror the elements inside the sequence must contains only 0 1 2 values dutchnationalflagsortabacab traceback most recent call last valueerror the elements inside the sequence must contains only 0 1 2 values dutchnationalflagsort3 2 3 1 3 0 3 traceback most recent call last valueerror the elements inside the sequence must contains only 0 1 2 values dutchnationalflagsort1 2 1 1 1 0 1 traceback most recent call last valueerror the elements inside the sequence must contains only 0 1 2 values dutchnationalflagsort1 1 2 1 1 1 1 1 0 1 1 traceback most recent call last valueerror the elements inside the sequence must contains only 0 1 2 values python program to sort a sequence containing only 0 1 and 2 in a single pass the first color of the flag the second color of the flag the third color of the flag a pure python implementation of dutch national flag sort algorithm param data 3 unique integer values e g 0 1 2 in an sequence return the same collection in ascending order dutch_national_flag_sort dutch_national_flag_sort 0 0 dutch_national_flag_sort 2 1 0 0 1 2 0 0 1 1 2 2 dutch_national_flag_sort 0 1 1 0 1 2 1 2 0 0 0 1 0 0 0 0 0 1 1 1 1 1 2 2 dutch_national_flag_sort abacab traceback most recent call last valueerror the elements inside the sequence must contains only 0 1 2 values dutch_national_flag_sort abacab traceback most recent call last valueerror the elements inside the sequence must contains only 0 1 2 values dutch_national_flag_sort 3 2 3 1 3 0 3 traceback most recent call last valueerror the elements inside the sequence must contains only 0 1 2 values dutch_national_flag_sort 1 2 1 1 1 0 1 traceback most recent call last valueerror the elements inside the sequence must contains only 0 1 2 values dutch_national_flag_sort 1 1 2 1 1 1 1 1 0 1 1 traceback most recent call last valueerror the elements inside the sequence must contains only 0 1 2 values
red = 0 white = 1 blue = 2 colors = (red, white, blue) def dutch_national_flag_sort(sequence: list) -> list: if not sequence: return [] if len(sequence) == 1: return list(sequence) low = 0 high = len(sequence) - 1 mid = 0 while mid <= high: if sequence[mid] == colors[0]: sequence[low], sequence[mid] = sequence[mid], sequence[low] low += 1 mid += 1 elif sequence[mid] == colors[1]: mid += 1 elif sequence[mid] == colors[2]: sequence[mid], sequence[high] = sequence[high], sequence[mid] high -= 1 else: msg = f"The elements inside the sequence must contains only {colors} values" raise ValueError(msg) return sequence if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by commas:\n").strip() unsorted = [int(item.strip()) for item in user_input.split(",")] print(f"{dutch_national_flag_sort(unsorted)}")
uses exchange sort to sort a list of numbers source https en wikipedia orgwikisortingalgorithmexchangesort exchangesort5 4 3 2 1 1 2 3 4 5 exchangesort1 2 3 3 2 1 exchangesort1 2 3 4 5 1 2 3 4 5 exchangesort0 10 2 5 3 2 0 3 5 10 exchangesort uses exchange sort to sort a list of numbers source https en wikipedia org wiki sorting_algorithm exchange_sort exchange_sort 5 4 3 2 1 1 2 3 4 5 exchange_sort 1 2 3 3 2 1 exchange_sort 1 2 3 4 5 1 2 3 4 5 exchange_sort 0 10 2 5 3 2 0 3 5 10 exchange_sort
def exchange_sort(numbers: list[int]) -> list[int]: numbers_length = len(numbers) for i in range(numbers_length): for j in range(i + 1, numbers_length): if numbers[j] < numbers[i]: numbers[i], numbers[j] = numbers[j], numbers[i] return numbers if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(exchange_sort(unsorted))
usrbinenv python sort large text files in a minimum amount of memory usr bin env python sort large text files in a minimum amount of memory noqa up015
import argparse import os class FileSplitter: BLOCK_FILENAME_FORMAT = "block_{0}.dat" def __init__(self, filename): self.filename = filename self.block_filenames = [] def write_block(self, data, block_number): filename = self.BLOCK_FILENAME_FORMAT.format(block_number) with open(filename, "w") as file: file.write(data) self.block_filenames.append(filename) def get_block_filenames(self): return self.block_filenames def split(self, block_size, sort_key=None): i = 0 with open(self.filename) as file: while True: lines = file.readlines(block_size) if lines == []: break if sort_key is None: lines.sort() else: lines.sort(key=sort_key) self.write_block("".join(lines), i) i += 1 def cleanup(self): map(os.remove, self.block_filenames) class NWayMerge: def select(self, choices): min_index = -1 min_str = None for i in range(len(choices)): if min_str is None or choices[i] < min_str: min_index = i return min_index class FilesArray: def __init__(self, files): self.files = files self.empty = set() self.num_buffers = len(files) self.buffers = {i: None for i in range(self.num_buffers)} def get_dict(self): return { i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty } def refresh(self): for i in range(self.num_buffers): if self.buffers[i] is None and i not in self.empty: self.buffers[i] = self.files[i].readline() if self.buffers[i] == "": self.empty.add(i) self.files[i].close() if len(self.empty) == self.num_buffers: return False return True def unshift(self, index): value = self.buffers[index] self.buffers[index] = None return value class FileMerger: def __init__(self, merge_strategy): self.merge_strategy = merge_strategy def merge(self, filenames, outfilename, buffer_size): buffers = FilesArray(self.get_file_handles(filenames, buffer_size)) with open(outfilename, "w", buffer_size) as outfile: while buffers.refresh(): min_index = self.merge_strategy.select(buffers.get_dict()) outfile.write(buffers.unshift(min_index)) def get_file_handles(self, filenames, buffer_size): files = {} for i in range(len(filenames)): files[i] = open(filenames[i], "r", buffer_size) return files class ExternalSort: def __init__(self, block_size): self.block_size = block_size def sort(self, filename, sort_key=None): num_blocks = self.get_number_blocks(filename, self.block_size) splitter = FileSplitter(filename) splitter.split(self.block_size, sort_key) merger = FileMerger(NWayMerge()) buffer_size = self.block_size / (num_blocks + 1) merger.merge(splitter.get_block_filenames(), filename + ".out", buffer_size) splitter.cleanup() def get_number_blocks(self, filename, block_size): return (os.stat(filename).st_size / block_size) + 1 def parse_memory(string): if string[-1].lower() == "k": return int(string[:-1]) * 1024 elif string[-1].lower() == "m": return int(string[:-1]) * 1024 * 1024 elif string[-1].lower() == "g": return int(string[:-1]) * 1024 * 1024 * 1024 else: return int(string) def main(): parser = argparse.ArgumentParser() parser.add_argument( "-m", "--mem", help="amount of memory to use for sorting", default="100M" ) parser.add_argument( "filename", metavar="<filename>", nargs=1, help="name of file to sort" ) args = parser.parse_args() sorter = ExternalSort(parse_memory(args.mem)) sorter.sort(args.filename[0]) if __name__ == "__main__": main()
gnome sort algorithm a k a stupid sort this algorithm iterates over a list comparing an element with the previous one if order is not respected it swaps element backward until order is respected with previous element it resumes the initial iteration from element new position for doctests run following command python3 m doctest v gnomesort py for manual testing run python3 gnomesort py pure implementation of the gnome sort algorithm in python take some mutable ordered collection with heterogeneous comparable items inside as arguments return the same collection ordered by ascending examples gnomesort0 5 3 2 2 0 2 2 3 5 gnomesort gnomesort2 5 45 45 5 2 joingnomesortlistsetgnomes are stupid gadeimnoprstu pure implementation of the gnome sort algorithm in python take some mutable ordered collection with heterogeneous comparable items inside as arguments return the same collection ordered by ascending examples gnome_sort 0 5 3 2 2 0 2 2 3 5 gnome_sort gnome_sort 2 5 45 45 5 2 join gnome_sort list set gnomes are stupid gadeimnoprstu
def gnome_sort(lst: list) -> list: if len(lst) <= 1: return lst i = 1 while i < len(lst): if lst[i - 1] <= lst[i]: i += 1 else: lst[i - 1], lst[i] = lst[i], lst[i - 1] i -= 1 if i == 0: i = 1 return lst if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(gnome_sort(unsorted))
this is a pure python implementation of the heap sort algorithm for doctests run following command python m doctest v heapsort py or python3 m doctest v heapsort py for manual testing run python heapsort py pure implementation of the heap sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples heapsort0 5 3 2 2 0 2 2 3 5 heapsort heapsort2 5 45 45 5 2 pure implementation of the heap sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples heap_sort 0 5 3 2 2 0 2 2 3 5 heap_sort heap_sort 2 5 45 45 5 2
def heapify(unsorted, index, heap_size): largest = index left_index = 2 * index + 1 right_index = 2 * index + 2 if left_index < heap_size and unsorted[left_index] > unsorted[largest]: largest = left_index if right_index < heap_size and unsorted[right_index] > unsorted[largest]: largest = right_index if largest != index: unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest] heapify(unsorted, largest, heap_size) def heap_sort(unsorted): n = len(unsorted) for i in range(n // 2 - 1, -1, -1): heapify(unsorted, i, n) for i in range(n - 1, 0, -1): unsorted[0], unsorted[i] = unsorted[i], unsorted[0] heapify(unsorted, 0, i) return unsorted if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(heap_sort(unsorted))
a pure python implementation of the insertion sort algorithm this algorithm sorts a collection by comparing adjacent elements when it finds that order is not respected it moves the element compared backward until the order is correct it then goes back directly to the element s initial position resuming forward comparison for doctests run following command python3 m doctest v insertionsort py for manual testing run python3 insertionsort py a pure python implementation of the insertion sort algorithm param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples insertionsort0 5 3 2 2 0 2 2 3 5 insertionsort sorted true insertionsort2 5 45 sorted2 5 45 true insertionsort d a b e c sorted d a b e c true import random collection random samplerange50 50 100 insertionsortcollection sortedcollection true import string collection random choicesstring asciiletters string digits k100 insertionsortcollection sortedcollection true a pure python implementation of the insertion sort algorithm param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples insertion_sort 0 5 3 2 2 0 2 2 3 5 insertion_sort sorted true insertion_sort 2 5 45 sorted 2 5 45 true insertion_sort d a b e c sorted d a b e c true import random collection random sample range 50 50 100 insertion_sort collection sorted collection true import string collection random choices string ascii_letters string digits k 100 insertion_sort collection sorted collection true
from collections.abc import MutableSequence from typing import Any, Protocol, TypeVar class Comparable(Protocol): def __lt__(self, other: Any, /) -> bool: ... T = TypeVar("T", bound=Comparable) def insertion_sort(collection: MutableSequence[T]) -> MutableSequence[T]: for insert_index in range(1, len(collection)): insert_value = collection[insert_index] while insert_index > 0 and insert_value < collection[insert_index - 1]: collection[insert_index] = collection[insert_index - 1] insert_index -= 1 collection[insert_index] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(f"{insertion_sort(unsorted) = }")
introspective sort is a hybrid sort quick sort heap sort insertion sort if the size of the list is under 16 use insertion sort https en wikipedia orgwikiintrosort array 4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 insertionsortarray 0 lenarray 1 2 4 6 7 8 8 12 14 14 22 23 27 45 56 79 array 21 15 11 45 2 11 46 insertionsortarray 0 lenarray 11 2 11 15 21 45 46 array 2 0 89 11 48 79 12 insertionsortarray 0 lenarray 2 0 11 12 48 79 89 array a z d p v l o o insertionsortarray 0 lenarray a d l o o p v z array 73 568 73 56 45 03 1 7 0 89 45 insertionsortarray 0 lenarray 45 03 0 1 7 73 56 73 568 89 45 array 4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 heapifyarray lenarray 2 lenarray heapsort4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 1 2 4 6 7 8 8 12 14 14 22 23 27 45 56 79 heapsort2 11 0 0 0 87 45 69 78 12 10 103 89 52 69 11 2 0 0 0 10 12 45 52 78 87 89 103 heapsort b d e f g p x z b s e u v b b d e e f g p s u v x z heapsort6 2 45 54 8465 20 758 56 457 0 0 1 2 879 1 7 11 7 457 0 45 54 0 1 1 7 2 879 6 2 11 7 758 56 8465 2 array 4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 medianof3array 0 lenarray 0 2 1 lenarray 1 12 array 13 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 medianof3array 0 lenarray 0 2 1 lenarray 1 13 array 4 2 6 8 1 7 8 22 15 14 27 79 23 45 14 16 medianof3array 0 lenarray 0 2 1 lenarray 1 14 array 4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 partitionarray 0 lenarray 12 8 array 21 15 11 45 2 11 46 partitionarray 0 lenarray 15 3 array a z d p v l o o partitionarray 0 lenarray p 5 array 6 2 45 54 8465 20 758 56 457 0 0 1 2 879 1 7 11 7 partitionarray 0 lenarray 2 879 6 param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples sort4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 1 2 4 6 7 8 8 12 14 14 22 23 27 45 56 79 sort1 5 3 13 44 44 13 5 3 1 sort sort5 5 sort3 0 7 6 23 34 34 7 3 0 6 23 sort1 7 1 0 3 3 2 1 0 3 0 3 1 0 1 7 2 1 3 3 sort d a b e c a b c d e array 4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 maxdepth 2 math ceilmath log2lenarray introsortarray 0 lenarray 16 maxdepth 1 2 4 6 7 8 8 12 14 14 22 23 27 45 56 79 array 4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 insertion_sort array 0 len array 1 2 4 6 7 8 8 12 14 14 22 23 27 45 56 79 array 21 15 11 45 2 11 46 insertion_sort array 0 len array 11 2 11 15 21 45 46 array 2 0 89 11 48 79 12 insertion_sort array 0 len array 2 0 11 12 48 79 89 array a z d p v l o o insertion_sort array 0 len array a d l o o p v z array 73 568 73 56 45 03 1 7 0 89 45 insertion_sort array 0 len array 45 03 0 1 7 73 56 73 568 89 45 max heap array 4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 heapify array len array 2 len array left node right node heap_sort 4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 1 2 4 6 7 8 8 12 14 14 22 23 27 45 56 79 heap_sort 2 11 0 0 0 87 45 69 78 12 10 103 89 52 69 11 2 0 0 0 10 12 45 52 78 87 89 103 heap_sort b d e f g p x z b s e u v b b d e e f g p s u v x z heap_sort 6 2 45 54 8465 20 758 56 457 0 0 1 2 879 1 7 11 7 457 0 45 54 0 1 1 7 2 879 6 2 11 7 758 56 8465 2 array 4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 median_of_3 array 0 len array 0 2 1 len array 1 12 array 13 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 median_of_3 array 0 len array 0 2 1 len array 1 13 array 4 2 6 8 1 7 8 22 15 14 27 79 23 45 14 16 median_of_3 array 0 len array 0 2 1 len array 1 14 array 4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 partition array 0 len array 12 8 array 21 15 11 45 2 11 46 partition array 0 len array 15 3 array a z d p v l o o partition array 0 len array p 5 array 6 2 45 54 8465 20 758 56 457 0 0 1 2 879 1 7 11 7 partition array 0 len array 2 879 6 param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples sort 4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 1 2 4 6 7 8 8 12 14 14 22 23 27 45 56 79 sort 1 5 3 13 44 44 13 5 3 1 sort sort 5 5 sort 3 0 7 6 23 34 34 7 3 0 6 23 sort 1 7 1 0 3 3 2 1 0 3 0 3 1 0 1 7 2 1 3 3 sort d a b e c a b c d e array 4 2 6 8 1 7 8 22 14 56 27 79 23 45 14 12 max_depth 2 math ceil math log2 len array intro_sort array 0 len array 16 max_depth 1 2 4 6 7 8 8 12 14 14 22 23 27 45 56 79
import math def insertion_sort(array: list, start: int = 0, end: int = 0) -> list: end = end or len(array) for i in range(start, end): temp_index = i temp_index_value = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: array[temp_index] = array[temp_index - 1] temp_index -= 1 array[temp_index] = temp_index_value return array def heapify(array: list, index: int, heap_size: int) -> None: largest = index left_index = 2 * index + 1 right_index = 2 * index + 2 if left_index < heap_size and array[largest] < array[left_index]: largest = left_index if right_index < heap_size and array[largest] < array[right_index]: largest = right_index if largest != index: array[index], array[largest] = array[largest], array[index] heapify(array, largest, heap_size) def heap_sort(array: list) -> list: n = len(array) for i in range(n // 2, -1, -1): heapify(array, i, n) for i in range(n - 1, 0, -1): array[i], array[0] = array[0], array[i] heapify(array, 0, i) return array def median_of_3( array: list, first_index: int, middle_index: int, last_index: int ) -> int: if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def partition(array: list, low: int, high: int, pivot: int) -> int: i = low j = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i array[i], array[j] = array[j], array[i] i += 1 def sort(array: list) -> list: if len(array) == 0: return array max_depth = 2 * math.ceil(math.log2(len(array))) size_threshold = 16 return intro_sort(array, 0, len(array), size_threshold, max_depth) def intro_sort( array: list, start: int, end: int, size_threshold: int, max_depth: int ) -> list: while end - start > size_threshold: if max_depth == 0: return heap_sort(array) max_depth -= 1 pivot = median_of_3(array, start, start + ((end - start) // 2) + 1, end - 1) p = partition(array, start, end, pivot) intro_sort(array, p, end, size_threshold, max_depth) end = p return insertion_sort(array, start, end) if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by a comma : ").strip() unsorted = [float(item) for item in user_input.split(",")] print(f"{sort(unsorted) = }")
implementation of iterative merge sort in python aman gupta for doctests run following command python3 m doctest v iterativemergesort py for manual testing run python3 iterativemergesort py sorting lefthalf and righthalf individually then merging them into result iteration over the unsorted list return a sorted copy of the input list itermergesort5 9 8 7 1 2 7 1 2 5 7 7 8 9 itermergesort1 1 itermergesort2 1 1 2 itermergesort2 1 3 1 2 3 itermergesort4 3 2 1 1 2 3 4 itermergesort5 4 3 2 1 1 2 3 4 5 itermergesort c b a a b c itermergesort0 3 0 2 0 1 0 1 0 2 0 3 itermergesort dep dang trai dang dep trai itermergesort6 6 itermergesort itermergesort2 9 1 4 9 4 2 1 itermergesort1 1 1 0 0 1 1 1 1 1 1 0 0 1 1 1 itermergesort c b a a b c itermergesort cba a b c iteration for twoway merging getting low high and middle value for mergesort of single list final merge of last two parts sorting left half and right half individually then merging them into result iteration over the unsorted list return a sorted copy of the input list iter_merge_sort 5 9 8 7 1 2 7 1 2 5 7 7 8 9 iter_merge_sort 1 1 iter_merge_sort 2 1 1 2 iter_merge_sort 2 1 3 1 2 3 iter_merge_sort 4 3 2 1 1 2 3 4 iter_merge_sort 5 4 3 2 1 1 2 3 4 5 iter_merge_sort c b a a b c iter_merge_sort 0 3 0 2 0 1 0 1 0 2 0 3 iter_merge_sort dep dang trai dang dep trai iter_merge_sort 6 6 iter_merge_sort iter_merge_sort 2 9 1 4 9 4 2 1 iter_merge_sort 1 1 1 0 0 1 1 1 1 1 1 0 0 1 1 1 iter_merge_sort c b a a b c iter_merge_sort cba a b c iteration for two way merging getting low high and middle value for merge sort of single list final merge of last two parts
from __future__ import annotations def merge(input_list: list, low: int, mid: int, high: int) -> list: result = [] left, right = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0)) input_list[low : high + 1] = result + left + right return input_list def iter_merge_sort(input_list: list) -> list: if len(input_list) <= 1: return input_list input_list = list(input_list) p = 2 while p <= len(input_list): for i in range(0, len(input_list), p): low = i high = i + p - 1 mid = (low + high + 1) // 2 input_list = merge(input_list, low, mid, high) if p * 2 >= len(input_list): mid = i input_list = merge(input_list, 0, mid, len(input_list) - 1) break p *= 2 return input_list if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() if user_input == "": unsorted = [] else: unsorted = [int(item.strip()) for item in user_input.split(",")] print(iter_merge_sort(unsorted))
this is a pure python implementation of the mergeinsertion sort algorithm source https en wikipedia orgwikimergeinsertionsort for doctests run following command python3 m doctest v mergeinsertionsort py or python m doctest v mergeinsertionsort py for manual testing run python3 mergeinsertionsort py binarysearchinsertion1 2 7 9 10 4 1 2 4 7 9 10 merge1 6 9 10 2 3 4 5 7 8 1 6 2 3 4 5 7 8 9 10 sortlist2d9 10 1 6 7 8 2 3 4 5 1 6 2 3 4 5 7 8 9 10 pure implementation of mergeinsertion sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples mergeinsertionsort0 5 3 2 2 0 2 2 3 5 mergeinsertionsort99 99 mergeinsertionsort2 5 45 45 5 2 testing with all permutations on range0 5 import itertools permutations listitertools permutations0 1 2 3 4 allmergeinsertionsortp 0 1 2 3 4 for p in permutations true group the items into two pairs and leave one element if there is a last odd item example 999 100 75 40 10000 999 100 75 40 leave 10000 sort twopairs in each groups example 999 100 75 40 100 999 40 75 sort twopairedlist example 100 999 40 75 40 75 100 999 40 100 is sure because it has already been sorted generate the sortedlist of them so that you can avoid unnecessary comparison example group0 group1 40 100 75 999 group0 group1 40 100 75 999 100 999 is sure because it has already been sorted put 999 in last of the sortedlist so that you can avoid unnecessary comparison example group0 group1 40 100 75 999 group0 group1 40 100 999 75 insert the last odd item left if there is example group0 group1 40 100 999 75 group0 group1 40 100 999 10000 75 insert the remaining items in this case 40 75 is sure because it has already been sorted therefore you only need to insert 75 into 100 999 10000 so that you can avoid unnecessary comparison example group0 group1 40 100 999 10000 you don t need to compare with this as 40 75 is already sure 75 40 75 100 999 10000 if lastodditem is inserted before the item s index you should forward index one more binary_search_insertion 1 2 7 9 10 4 1 2 4 7 9 10 merge 1 6 9 10 2 3 4 5 7 8 1 6 2 3 4 5 7 8 9 10 sortlist_2d 9 10 1 6 7 8 2 3 4 5 1 6 2 3 4 5 7 8 9 10 pure implementation of merge insertion sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples merge_insertion_sort 0 5 3 2 2 0 2 2 3 5 merge_insertion_sort 99 99 merge_insertion_sort 2 5 45 45 5 2 testing with all permutations on range 0 5 import itertools permutations list itertools permutations 0 1 2 3 4 all merge_insertion_sort p 0 1 2 3 4 for p in permutations true group the items into two pairs and leave one element if there is a last odd item example 999 100 75 40 10000 999 100 75 40 leave 10000 sort two pairs in each groups example 999 100 75 40 100 999 40 75 sort two_paired_list example 100 999 40 75 40 75 100 999 40 100 is sure because it has already been sorted generate the sorted_list of them so that you can avoid unnecessary comparison example group0 group1 40 100 75 999 group0 group1 40 100 75 999 100 999 is sure because it has already been sorted put 999 in last of the sorted_list so that you can avoid unnecessary comparison example group0 group1 40 100 75 999 group0 group1 40 100 999 75 insert the last odd item left if there is example group0 group1 40 100 999 75 group0 group1 40 100 999 10000 75 insert the remaining items in this case 40 75 is sure because it has already been sorted therefore you only need to insert 75 into 100 999 10000 so that you can avoid unnecessary comparison example group0 group1 40 100 999 10000 you don t need to compare with this as 40 75 is already sure 75 40 75 100 999 10000 if last_odd_item is inserted before the item s index you should forward index one more
from __future__ import annotations def binary_search_insertion(sorted_list, item): left = 0 right = len(sorted_list) - 1 while left <= right: middle = (left + right) // 2 if left == right: if sorted_list[middle] < item: left = middle + 1 break elif sorted_list[middle] < item: left = middle + 1 else: right = middle - 1 sorted_list.insert(left, item) return sorted_list def merge(left, right): result = [] while left and right: if left[0][0] < right[0][0]: result.append(left.pop(0)) else: result.append(right.pop(0)) return result + left + right def sortlist_2d(list_2d): length = len(list_2d) if length <= 1: return list_2d middle = length // 2 return merge(sortlist_2d(list_2d[:middle]), sortlist_2d(list_2d[middle:])) def merge_insertion_sort(collection: list[int]) -> list[int]: if len(collection) <= 1: return collection two_paired_list = [] has_last_odd_item = False for i in range(0, len(collection), 2): if i == len(collection) - 1: has_last_odd_item = True else: if collection[i] < collection[i + 1]: two_paired_list.append([collection[i], collection[i + 1]]) else: two_paired_list.append([collection[i + 1], collection[i]]) sorted_list_2d = sortlist_2d(two_paired_list) result = [i[0] for i in sorted_list_2d] result.append(sorted_list_2d[-1][1]) if has_last_odd_item: pivot = collection[-1] result = binary_search_insertion(result, pivot) is_last_odd_item_inserted_before_this_index = False for i in range(len(sorted_list_2d) - 1): if result[i] == collection[-1] and has_last_odd_item: is_last_odd_item_inserted_before_this_index = True pivot = sorted_list_2d[i][1] if is_last_odd_item_inserted_before_this_index: result = result[: i + 2] + binary_search_insertion(result[i + 2 :], pivot) else: result = result[: i + 1] + binary_search_insertion(result[i + 1 :], pivot) return result if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(merge_insertion_sort(unsorted))
this is a pure python implementation of the merge sort algorithm for doctests run following command python m doctest v mergesort py or python3 m doctest v mergesort py for manual testing run python mergesort py sorts a list using the merge sort algorithm param collection a mutable ordered collection with comparable items return the same collection ordered in ascending order time complexity on log n examples mergesort0 5 3 2 2 0 2 2 3 5 mergesort mergesort2 5 45 45 5 2 merge two sorted lists into a single sorted list param left left collection param right right collection return merged result sorts a list using the merge sort algorithm param collection a mutable ordered collection with comparable items return the same collection ordered in ascending order time complexity o n log n examples merge_sort 0 5 3 2 2 0 2 2 3 5 merge_sort merge_sort 2 5 45 45 5 2 merge two sorted lists into a single sorted list param left left collection param right right collection return merged result
def merge_sort(collection: list) -> list: def merge(left: list, right: list) -> list: result = [] while left and right: result.append(left.pop(0) if left[0] <= right[0] else right.pop(0)) result.extend(left) result.extend(right) return result if len(collection) <= 1: return collection mid_index = len(collection) // 2 return merge(merge_sort(collection[:mid_index]), merge_sort(collection[mid_index:])) if __name__ == "__main__": import doctest doctest.testmod() try: user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] sorted_list = merge_sort(unsorted) print(*sorted_list, sep=",") except ValueError: print("Invalid input. Please enter valid integers separated by commas.")
python implementation of the msd radix sort algorithm it used the binary representation of the integers to sort them https en wikipedia orgwikiradixsort implementation of the msd radix sort algorithm only works with positive integers param listofints a list of integers return returns the sorted list msdradixsort40 12 1 100 4 1 4 12 40 100 msdradixsort msdradixsort123 345 123 80 80 123 123 345 msdradixsort1209 834598 1 540402 45 1 45 1209 540402 834598 msdradixsort1 34 45 traceback most recent call last valueerror all numbers must be positive sort the given list based on the bit at bitposition numbers with a 0 at that position will be at the start of the list numbers with a 1 at the end param listofints a list of integers param bitposition the position of the bit that gets compared return returns a partially sorted list msdradixsort45 2 32 1 2 32 45 msdradixsort10 4 12 2 4 12 10 split numbers based on bit at bitposition from the right number has a one at bit bitposition number has a zero at bit bitposition recursively split both lists further recombine lists inplace implementation of the msd radix sort algorithm sorts based on the binary representation of the integers lst 1 345 23 89 0 3 msdradixsortinplacelst lst sortedlst true lst 1 43 0 0 0 24 3 3 msdradixsortinplacelst lst sortedlst true lst msdradixsortinplacelst lst true lst 1 34 23 4 42 msdradixsortinplacelst traceback most recent call last valueerror all numbers must be positive sort the given list based on the bit at bitposition numbers with a 0 at that position will be at the start of the list numbers with a 1 at the end lst 45 2 32 24 534 2932 msdradixsortinplacelst 1 0 3 lst 32 2 45 24 534 2932 true lst 0 2 1 3 12 10 4 90 54 2323 756 msdradixsortinplacelst 2 4 7 lst 0 2 1 3 12 4 10 90 54 2323 756 true found zero at the beginning found one at the end implementation of the msd radix sort algorithm only works with positive integers param list_of_ints a list of integers return returns the sorted list msd_radix_sort 40 12 1 100 4 1 4 12 40 100 msd_radix_sort msd_radix_sort 123 345 123 80 80 123 123 345 msd_radix_sort 1209 834598 1 540402 45 1 45 1209 540402 834598 msd_radix_sort 1 34 45 traceback most recent call last valueerror all numbers must be positive sort the given list based on the bit at bit_position numbers with a 0 at that position will be at the start of the list numbers with a 1 at the end param list_of_ints a list of integers param bit_position the position of the bit that gets compared return returns a partially sorted list _msd_radix_sort 45 2 32 1 2 32 45 _msd_radix_sort 10 4 12 2 4 12 10 split numbers based on bit at bit_position from the right number has a one at bit bit_position number has a zero at bit bit_position recursively split both lists further recombine lists inplace implementation of the msd radix sort algorithm sorts based on the binary representation of the integers lst 1 345 23 89 0 3 msd_radix_sort_inplace lst lst sorted lst true lst 1 43 0 0 0 24 3 3 msd_radix_sort_inplace lst lst sorted lst true lst msd_radix_sort_inplace lst lst true lst 1 34 23 4 42 msd_radix_sort_inplace lst traceback most recent call last valueerror all numbers must be positive sort the given list based on the bit at bit_position numbers with a 0 at that position will be at the start of the list numbers with a 1 at the end lst 45 2 32 24 534 2932 _msd_radix_sort_inplace lst 1 0 3 lst 32 2 45 24 534 2932 true lst 0 2 1 3 12 10 4 90 54 2323 756 _msd_radix_sort_inplace lst 2 4 7 lst 0 2 1 3 12 4 10 90 54 2323 756 true found zero at the beginning found one at the end
from __future__ import annotations def msd_radix_sort(list_of_ints: list[int]) -> list[int]: if not list_of_ints: return [] if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) return _msd_radix_sort(list_of_ints, most_bits) def _msd_radix_sort(list_of_ints: list[int], bit_position: int) -> list[int]: if bit_position == 0 or len(list_of_ints) in [0, 1]: return list_of_ints zeros = [] ones = [] for number in list_of_ints: if (number >> (bit_position - 1)) & 1: ones.append(number) else: zeros.append(number) zeros = _msd_radix_sort(zeros, bit_position - 1) ones = _msd_radix_sort(ones, bit_position - 1) res = zeros res.extend(ones) return res def msd_radix_sort_inplace(list_of_ints: list[int]): length = len(list_of_ints) if not list_of_ints or length == 1: return if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) _msd_radix_sort_inplace(list_of_ints, most_bits, 0, length) def _msd_radix_sort_inplace( list_of_ints: list[int], bit_position: int, begin_index: int, end_index: int ): if bit_position == 0 or end_index - begin_index <= 1: return bit_position -= 1 i = begin_index j = end_index - 1 while i <= j: changed = False if not (list_of_ints[i] >> bit_position) & 1: i += 1 changed = True if (list_of_ints[j] >> bit_position) & 1: j -= 1 changed = True if changed: continue list_of_ints[i], list_of_ints[j] = list_of_ints[j], list_of_ints[i] j -= 1 if j != i: i += 1 _msd_radix_sort_inplace(list_of_ints, bit_position, begin_index, i) _msd_radix_sort_inplace(list_of_ints, bit_position, i, end_index) if __name__ == "__main__": import doctest doctest.testmod()