Description
stringlengths
18
161k
Code
stringlengths
15
300k
lightxu file convolve py time 201978 0008 16 13 pads image with the edge values of array im2col turn the ksizeksize pixels into a row and np vstack all rows turn the kernel into shapekk 1 reshape and get the dst image read original image turn image in gray scale value laplace operator lightxu file convolve py time 2019 7 8 0008 下午 16 13 pads image with the edge values of array im2col turn the k_size k_size pixels into a row and np vstack all rows turn the kernel into shape k k 1 reshape and get the dst image read original image turn image in gray scale value laplace operator
from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import array, dot, pad, ravel, uint8, zeros def im2col(image, block_size): rows, cols = image.shape dst_height = cols - block_size[1] + 1 dst_width = rows - block_size[0] + 1 image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0])) row = 0 for i in range(dst_height): for j in range(dst_width): window = ravel(image[i : i + block_size[0], j : j + block_size[1]]) image_array[row, :] = window row += 1 return image_array def img_convolve(image, filter_kernel): height, width = image.shape[0], image.shape[1] k_size = filter_kernel.shape[0] pad_size = k_size // 2 image_tmp = pad(image, pad_size, mode="edge") image_array = im2col(image_tmp, (k_size, k_size)) kernel_array = ravel(filter_kernel) dst = dot(image_array, kernel_array).reshape(height, width) return dst if __name__ == "__main__": img = imread(r"../image_data/lena.jpg") gray = cvtColor(img, COLOR_BGR2GRAY) Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) out = img_convolve(gray, Laplace_kernel).astype(uint8) imshow("Laplacian", out) waitKey(0)
implementation of the gaborfilter https en wikipedia orgwikigaborfilter param ksize the kernelsize of the convolutional filter ksize x ksize param sigma standard deviation of the gaussian bell curve param theta the orientation of the normal to the parallel stripes of gabor function param lambd wavelength of the sinusoidal component param gamma the spatial aspect ratio and specifies the ellipticity of the support of gabor function param psi the phase offset of the sinusoidal function gaborfilterkernel3 8 0 10 0 0 tolist 0 8027212023735046 1 0 0 8027212023735046 0 8027212023735046 1 0 0 8027212023735046 0 8027212023735046 1 0 0 8027212023735046 prepare kernel the kernel size have to be odd each value distance from center degree to radiant get kernel x get kernel y fill kernel read original image turn image in gray scale value apply multiple kernel to detect edges ksize 10 sigma 8 lambd 10 gamma 0 psi 0 implementation of the gaborfilter https en wikipedia org wiki gabor_filter param ksize the kernelsize of the convolutional filter ksize x ksize param sigma standard deviation of the gaussian bell curve param theta the orientation of the normal to the parallel stripes of gabor function param lambd wavelength of the sinusoidal component param gamma the spatial aspect ratio and specifies the ellipticity of the support of gabor function param psi the phase offset of the sinusoidal function gabor_filter_kernel 3 8 0 10 0 0 tolist 0 8027212023735046 1 0 0 8027212023735046 0 8027212023735046 1 0 0 8027212023735046 0 8027212023735046 1 0 0 8027212023735046 prepare kernel the kernel size have to be odd each value distance from center degree to radiant get kernel x get kernel y fill kernel read original image turn image in gray scale value apply multiple kernel to detect edges ksize 10 sigma 8 lambd 10 gamma 0 psi 0
import numpy as np from cv2 import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filter2D, imread, imshow, waitKey def gabor_filter_kernel( ksize: int, sigma: int, theta: int, lambd: int, gamma: int, psi: int ) -> np.ndarray: if (ksize % 2) == 0: ksize = ksize + 1 gabor = np.zeros((ksize, ksize), dtype=np.float32) for y in range(ksize): for x in range(ksize): px = x - ksize // 2 py = y - ksize // 2 _theta = theta / 180 * np.pi cos_theta = np.cos(_theta) sin_theta = np.sin(_theta) _x = cos_theta * px + sin_theta * py _y = -sin_theta * px + cos_theta * py gabor[y, x] = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi) return gabor if __name__ == "__main__": import doctest doctest.testmod() img = imread("../image_data/lena.jpg") gray = cvtColor(img, COLOR_BGR2GRAY) out = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: kernel_10 = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filter2D(gray, CV_8UC3, kernel_10) out = out / out.max() * 255 out = out.astype(np.uint8) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
implementation of gaussian filter algorithm dst image height and width im2col turn the ksizeksize pixels into a row and np vstack all rows turn the kernel into shapekk 1 reshape and get the dst image read original image turn image in gray scale value get values with two different mask size show result images dst image height and width im2col turn the k_size k_size pixels into a row and np vstack all rows turn the kernel into shape k k 1 reshape and get the dst image read original image turn image in gray scale value get values with two different mask size show result images
from itertools import product from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uint8, zeros def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = mgrid[0 - center : k_size - center, 0 - center : k_size - center] g = 1 / (2 * pi * sigma) * exp(-(square(x) + square(y)) / (2 * square(sigma))) return g def gaussian_filter(image, k_size, sigma): height, width = image.shape[0], image.shape[1] dst_height = height - k_size + 1 dst_width = width - k_size + 1 image_array = zeros((dst_height * dst_width, k_size * k_size)) row = 0 for i, j in product(range(dst_height), range(dst_width)): window = ravel(image[i : i + k_size, j : j + k_size]) image_array[row, :] = window row += 1 gaussian_kernel = gen_gaussian_kernel(k_size, sigma) filter_array = ravel(gaussian_kernel) dst = dot(image_array, filter_array).reshape(dst_height, dst_width).astype(uint8) return dst if __name__ == "__main__": img = imread(r"../image_data/lena.jpg") gray = cvtColor(img, COLOR_BGR2GRAY) gaussian3x3 = gaussian_filter(gray, 3, sigma=1) gaussian5x5 = gaussian_filter(gray, 5, sigma=0.8) imshow("gaussian filter with 3x3 mask", gaussian3x3) imshow("gaussian filter with 5x5 mask", gaussian5x5) waitKey()
ojaswani file laplacianfilter py date 10042023 param src the source image which should be a grayscale or color image param ksize the size of the kernel used to compute the laplacian filter which can be 1 3 5 or 7 mylaplaciansrcnp array ksize0 traceback most recent call last valueerror ksize must be in 1 3 5 7 apply the laplacian kernel using convolution read original image turn image in gray scale value applying gaussian filter apply multiple kernel to detect edges ojas wani file laplacian_filter py date 10 04 2023 param src the source image which should be a grayscale or color image param ksize the size of the kernel used to compute the laplacian filter which can be 1 3 5 or 7 my_laplacian src np array ksize 0 traceback most recent call last valueerror ksize must be in 1 3 5 7 apply the laplacian kernel using convolution read original image turn image in gray scale value applying gaussian filter apply multiple kernel to detect edges
import numpy as np from cv2 import ( BORDER_DEFAULT, COLOR_BGR2GRAY, CV_64F, cvtColor, filter2D, imread, imshow, waitKey, ) from digital_image_processing.filters.gaussian_filter import gaussian_filter def my_laplacian(src: np.ndarray, ksize: int) -> np.ndarray: kernels = { 1: np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]), 3: np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]), 5: np.array( [ [0, 0, -1, 0, 0], [0, -1, -2, -1, 0], [-1, -2, 16, -2, -1], [0, -1, -2, -1, 0], [0, 0, -1, 0, 0], ] ), 7: np.array( [ [0, 0, 0, -1, 0, 0, 0], [0, 0, -2, -3, -2, 0, 0], [0, -2, -7, -10, -7, -2, 0], [-1, -3, -10, 68, -10, -3, -1], [0, -2, -7, -10, -7, -2, 0], [0, 0, -2, -3, -2, 0, 0], [0, 0, 0, -1, 0, 0, 0], ] ), } if ksize not in kernels: msg = f"ksize must be in {tuple(kernels)}" raise ValueError(msg) return filter2D( src, CV_64F, kernels[ksize], 0, borderType=BORDER_DEFAULT, anchor=(0, 0) ) if __name__ == "__main__": img = imread(r"../image_data/lena.jpg") gray = cvtColor(img, COLOR_BGR2GRAY) blur_image = gaussian_filter(gray, 3, sigma=1) laplacian_image = my_laplacian(ksize=3, src=blur_image) imshow("Original image", img) imshow("Detected edges using laplacian filter", laplacian_image) waitKey(0)
comparing local neighborhood pixel value with threshold value of centre pixel exception is required when neighborhood value of a center pixel value is null i e values present at boundaries param image the image we re working with param xcoordinate xcoordinate of the pixel param ycoordinate the y coordinate of the pixel param center center pixel value return the value of the pixel is being returned it takes an image an x and y coordinate and returns the decimal value of the local binary patternof the pixel at that coordinate param image the image to be processed param xcoordinate x coordinate of the pixel param ycoordinate the y coordinate of the pixel return the decimal value of the binary value of the pixels around the center pixel skip getneighborspixel if center is null starting from the top right assigning value to pixels clockwise converting the binary value to decimal reading the image and converting it to grayscale create a numpy array as the same height and width of read image iterating through the image and calculating the local binary pattern value for each pixel comparing local neighborhood pixel value with threshold value of centre pixel exception is required when neighborhood value of a center pixel value is null i e values present at boundaries param image the image we re working with param x_coordinate x coordinate of the pixel param y_coordinate the y coordinate of the pixel param center center pixel value return the value of the pixel is being returned it takes an image an x and y coordinate and returns the decimal value of the local binary patternof the pixel at that coordinate param image the image to be processed param x_coordinate x coordinate of the pixel param y_coordinate the y coordinate of the pixel return the decimal value of the binary value of the pixels around the center pixel skip get_neighbors_pixel if center is null starting from the top right assigning value to pixels clockwise converting the binary value to decimal reading the image and converting it to grayscale create a numpy array as the same height and width of read image iterating through the image and calculating the local binary pattern value for each pixel
import cv2 import numpy as np def get_neighbors_pixel( image: np.ndarray, x_coordinate: int, y_coordinate: int, center: int ) -> int: try: return int(image[x_coordinate][y_coordinate] >= center) except (IndexError, TypeError): return 0 def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int) -> int: center = image[x_coordinate][y_coordinate] powers = [1, 2, 4, 8, 16, 32, 64, 128] if center is None: return 0 binary_values = [ get_neighbors_pixel(image, x_coordinate - 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate + 1, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate, center), get_neighbors_pixel(image, x_coordinate + 1, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate, y_coordinate - 1, center), get_neighbors_pixel(image, x_coordinate - 1, y_coordinate - 1, center), ] return sum( binary_value * power for binary_value, power in zip(binary_values, powers) ) if __name__ == "__main__": image = cv2.imread( "digital_image_processing/image_data/lena.jpg", cv2.IMREAD_GRAYSCALE ) lbp_image = np.zeros((image.shape[0], image.shape[1])) for i in range(image.shape[0]): for j in range(image.shape[1]): lbp_image[i][j] = local_binary_value(image, i, j) cv2.imshow("local binary pattern", lbp_image) cv2.waitKey(0) cv2.destroyAllWindows()
implementation of median filter algorithm param grayimg gray image param mask mask size return image with median filter set image borders copy image size get mask according with mask calculate mask median read original image turn image in gray scale value get values with two different mask size show result images param gray_img gray image param mask mask size return image with median filter set image borders copy image size get mask according with mask calculate mask median read original image turn image in gray scale value get values with two different mask size show result images
from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import divide, int8, multiply, ravel, sort, zeros_like def median_filter(gray_img, mask=3): bd = int(mask / 2) median_img = zeros_like(gray_img) for i in range(bd, gray_img.shape[0] - bd): for j in range(bd, gray_img.shape[1] - bd): kernel = ravel(gray_img[i - bd : i + bd + 1, j - bd : j + bd + 1]) median = sort(kernel)[int8(divide((multiply(mask, mask)), 2) + 1)] median_img[i, j] = median return median_img if __name__ == "__main__": img = imread("../image_data/lena.jpg") gray = cvtColor(img, COLOR_BGR2GRAY) median3x3 = median_filter(gray, 3) median5x5 = median_filter(gray, 5) imshow("median filter with 3x3 mask", median3x3) imshow("median filter with 5x5 mask", median5x5) waitKey(0)
lightxu file sobelfilter py time 201978 0008 16 26 modify the pix within 0 255 read original image turn image in gray scale value show result images lightxu file sobel_filter py time 2019 7 8 0008 下午 16 26 modify the pix within 0 255 read original image turn image in gray scale value show result images
import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from digital_image_processing.filters.convolve import img_convolve def sobel_filter(image): kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) dst_x = np.abs(img_convolve(image, kernel_x)) dst_y = np.abs(img_convolve(image, kernel_y)) dst_x = dst_x * 255 / np.max(dst_x) dst_y = dst_y * 255 / np.max(dst_y) dst_xy = np.sqrt((np.square(dst_x)) + (np.square(dst_y))) dst_xy = dst_xy * 255 / np.max(dst_xy) dst = dst_xy.astype(np.uint8) theta = np.arctan2(dst_y, dst_x) return dst, theta if __name__ == "__main__": img = imread("../image_data/lena.jpg") gray = cvtColor(img, COLOR_BGR2GRAY) sobel_grad, sobel_theta = sobel_filter(gray) imshow("sobel filter", sobel_grad) imshow("sobel theta", sobel_theta) waitKey(0)
created on fri sep 28 15 22 29 2018 binish125
import copy import os import cv2 import numpy as np from matplotlib import pyplot as plt class ConstantStretch: def __init__(self): self.img = "" self.original_image = "" self.last_list = [] self.rem = 0 self.L = 256 self.sk = 0 self.k = 0 self.number_of_rows = 0 self.number_of_cols = 0 def stretch(self, input_image): self.img = cv2.imread(input_image, 0) self.original_image = copy.deepcopy(self.img) x, _, _ = plt.hist(self.img.ravel(), 256, [0, 256], label="x") self.k = np.sum(x) for i in range(len(x)): prk = x[i] / self.k self.sk += prk last = (self.L - 1) * self.sk if self.rem != 0: self.rem = int(last % last) last = int(last + 1 if self.rem >= 0.5 else last) self.last_list.append(last) self.number_of_rows = int(np.ma.count(self.img) / self.img[1].size) self.number_of_cols = self.img[1].size for i in range(self.number_of_cols): for j in range(self.number_of_rows): num = self.img[j][i] if num != self.last_list[num]: self.img[j][i] = self.last_list[num] cv2.imwrite("output_data/output.jpg", self.img) def plot_histogram(self): plt.hist(self.img.ravel(), 256, [0, 256]) def show_image(self): cv2.imshow("Output-Image", self.img) cv2.imshow("Input-Image", self.original_image) cv2.waitKey(5000) cv2.destroyAllWindows() if __name__ == "__main__": file_path = os.path.join(os.path.basename(__file__), "image_data/input.jpg") stretcher = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
joo gustavo a amorim email joaogustavoamorimgmail com coding date jan 2019 pythonblack true imports class implemented to calculus the index class summary this algorithm consists in calculating vegetation indices these indices can be used for precision agriculture for example or remote sensing there are functions to define the data and to calculate the implemented indices vegetation index https en wikipedia orgwikivegetationindex a vegetation index vi is a spectral transformation of two or more bands designed to enhance the contribution of vegetation properties and allow reliable spatial and temporal intercomparisons of terrestrial photosynthetic activity and canopy structural variations information about channels wavelength range for each nir nearinfrared https www malvernpanalytical combrproductstechnologynearinfraredspectroscopy wavelength range 700 nm to 2500 nm red edge https en wikipedia orgwikirededge wavelength range 680 nm to 730 nm red https en wikipedia orgwikicolor wavelength range 635 nm to 700 nm blue https en wikipedia orgwikicolor wavelength range 450 nm to 490 nm green https en wikipedia orgwikicolor wavelength range 520 nm to 560 nm implemented index list abbreviationofindexname list of channels used arvi2 red nir ccci red rededge nir cvi red green nir gli red green blue ndvi red nir bndvi blue nir rededgendvi red rededge gndvi green nir gbndvi green blue nir grndvi red green nir rbndvi red blue nir pndvi red green blue nir atsavi red nir bwdrvi blue nir cigreen green nir cirededge rededge nir ci red blue ctvi red nir gdvi green nir evi red blue nir gemi red nir gosavi green nir gsavi green nir hue red green blue ivi red nir ipvi red nir i red green blue rvi red nir mrvi red nir msavi red nir normg red green nir normnir red green nir normr red green nir ngrdi red green ri red green s red green blue if red green blue dvi red nir tvi red nir ndre rededge nir list of all index implemented allindex arvi2 ccci cvi gli ndvi bndvi rededgendvi gndvi gbndvi grndvi rbndvi pndvi atsavi bwdrvi cigreen cirededge ci ctvi gdvi evi gemi gosavi gsavi hue ivi ipvi i rvi mrvi msavi normg normnir normr ngrdi ri s if dvi tvi ndre list of index with not blue channel notblueindex arvi2 ccci cvi ndvi rededgendvi gndvi grndvi atsavi cigreen cirededge ctvi gdvi gemi gosavi gsavi ivi ipvi rvi mrvi msavi normg normnir normr ngrdi ri dvi tvi ndre list of index just with rgb channels rgbindex gli ci hue i ngrdi ri s if performs the calculation of the index with the values instantiated in the class str index abbreviation of index name to perform atmospherically resistant vegetation index 2 https www indexdatabase dedbisingle php id396 return index 0 181 17self nirself redself nirself red canopy chlorophyll content index https www indexdatabase dedbisingle php id224 return index chlorophyll vegetation index https www indexdatabase dedbisingle php id391 return index self green leaf index https www indexdatabase dedbisingle php id375 return index normalized difference self nirself red normalized difference vegetation index calibrated ndvi cdvi https www indexdatabase dedbisingle php id58 return index normalized difference self nirself blue self bluenormalized difference vegetation index https www indexdatabase dedbisingle php id135 return index normalized difference self rededgeself red https www indexdatabase dedbisingle php id235 return index normalized difference self nirself green self green ndvi https www indexdatabase dedbisingle php id401 return index self greenself blue ndvi https www indexdatabase dedbisingle php id186 return index self greenself red ndvi https www indexdatabase dedbisingle php id185 return index self redself blue ndvi https www indexdatabase dedbisingle php id187 return index pan ndvi https www indexdatabase dedbisingle php id188 return index adjusted transformed soiladjusted vi https www indexdatabase dedbisingle php id209 return index self bluewide dynamic range vegetation index https www indexdatabase dedbisingle php id136 return index chlorophyll index self green https www indexdatabase dedbisingle php id128 return index chlorophyll index self rededge https www indexdatabase dedbisingle php id131 return index coloration index https www indexdatabase dedbisingle php id11 return index corrected transformed vegetation index https www indexdatabase dedbisingle php id244 return index difference self nirself green self green difference vegetation index https www indexdatabase dedbisingle php id27 return index enhanced vegetation index https www indexdatabase dedbisingle php id16 return index global environment monitoring index https www indexdatabase dedbisingle php id25 return index self green optimized soil adjusted vegetation index https www indexdatabase dedbisingle php id29 mit y 0 16 return index self green soil adjusted vegetation index https www indexdatabase dedbisingle php id31 mit n 0 5 return index hue https www indexdatabase dedbisingle php id34 return index ideal vegetation index https www indexdatabase dedbisingle php id276 bintercept of vegetation line asoil line slope return index infraself red percentage vegetation index https www indexdatabase dedbisingle php id35 return index intensity https www indexdatabase dedbisingle php id36 return index ratiovegetationindex http www seosproject eumodulesremotesensingremotesensingc03s01p01 html return index modified normalized difference vegetation index rvi https www indexdatabase dedbisingle php id275 return index modified soil adjusted vegetation index https www indexdatabase dedbisingle php id44 return index norm g https www indexdatabase dedbisingle php id50 return index norm self nir https www indexdatabase dedbisingle php id51 return index norm r https www indexdatabase dedbisingle php id52 return index normalized difference self greenself red normalized self green self red difference index visible atmospherically resistant indices self green viself green https www indexdatabase dedbisingle php id390 return index normalized difference self redself green self redness index https www indexdatabase dedbisingle php id74 return index saturation https www indexdatabase dedbisingle php id77 return index shape index https www indexdatabase dedbisingle php id79 return index simple ratio self nirself red difference vegetation index vegetation index number vin https www indexdatabase dedbisingle php id12 return index transformed vegetation index https www indexdatabase dedbisingle php id98 return index genering a random matrices to test this class red np ones1000 1000 1 dtypefloat64 46787 green np ones1000 1000 1 dtypefloat64 23487 blue np ones1000 1000 1 dtypefloat64 14578 rededge np ones1000 1000 1 dtypefloat64 51045 nir np ones1000 1000 1 dtypefloat64 52200 examples of how to use the class instantiating the class cl indexcalculation instantiating the class with the values cl indexcalculationredred greengreen blueblue rededgerededge nirnir how set the values after instantiate the class cl for update the data or when don t instantiating the class with the values cl setmatricesredred greengreen blueblue rededgerededge nirnir calculating the indices for the instantiated values in the class note the ccci index can be changed to any index implemented in the class indexvalueform1 cl calculationccci redred greengreen blueblue rededgerededge nirnir astypenp float64 indexvalueform2 cl ccci calculating the index with the values directly you can set just the values preferred note the calculation function performs the function setmatrices indexvalueform3 cl calculationccci redred greengreen blueblue rededgerededge nirnir astypenp float64 printform 1 np array2stringindexvalueform1 precision20 separator floatmode maxprecequal printform 2 np array2stringindexvalueform2 precision20 separator floatmode maxprecequal printform 3 np array2stringindexvalueform3 precision20 separator floatmode maxprecequal a list of examples results for different type of data at ndvi float16 0 31567383 ndvi red 50 nir 100 float32 0 31578946 ndvi red 50 nir 100 float64 0 3157894736842105 ndvi red 50 nir 100 longdouble 0 3157894736842105 ndvi red 50 nir 100 joão gustavo a amorim email joaogustavoamorim gmail com coding date jan 2019 python black true imports class implemented to calculus the index class summary this algorithm consists in calculating vegetation indices these indices can be used for precision agriculture for example or remote sensing there are functions to define the data and to calculate the implemented indices vegetation index https en wikipedia org wiki vegetation_index a vegetation index vi is a spectral transformation of two or more bands designed to enhance the contribution of vegetation properties and allow reliable spatial and temporal inter comparisons of terrestrial photosynthetic activity and canopy structural variations information about channels wavelength range for each nir near infrared https www malvernpanalytical com br products technology near infrared spectroscopy wavelength range 700 nm to 2500 nm red edge https en wikipedia org wiki red_edge wavelength range 680 nm to 730 nm red https en wikipedia org wiki color wavelength range 635 nm to 700 nm blue https en wikipedia org wiki color wavelength range 450 nm to 490 nm green https en wikipedia org wiki color wavelength range 520 nm to 560 nm implemented index list abbreviationofindexname list of channels used arvi2 red nir ccci red rededge nir cvi red green nir gli red green blue ndvi red nir bndvi blue nir rededgendvi red rededge gndvi green nir gbndvi green blue nir grndvi red green nir rbndvi red blue nir pndvi red green blue nir atsavi red nir bwdrvi blue nir cigreen green nir cirededge rededge nir ci red blue ctvi red nir gdvi green nir evi red blue nir gemi red nir gosavi green nir gsavi green nir hue red green blue ivi red nir ipvi red nir i red green blue rvi red nir mrvi red nir msavi red nir normg red green nir normnir red green nir normr red green nir ngrdi red green ri red green s red green blue if red green blue dvi red nir tvi red nir ndre rededge nir list of all index implemented allindex arvi2 ccci cvi gli ndvi bndvi rededgendvi gndvi gbndvi grndvi rbndvi pndvi atsavi bwdrvi cigreen cirededge ci ctvi gdvi evi gemi gosavi gsavi hue ivi ipvi i rvi mrvi msavi normg normnir normr ngrdi ri s if dvi tvi ndre list of index with not blue channel notblueindex arvi2 ccci cvi ndvi rededgendvi gndvi grndvi atsavi cigreen cirededge ctvi gdvi gemi gosavi gsavi ivi ipvi rvi mrvi msavi normg normnir normr ngrdi ri dvi tvi ndre list of index just with rgb channels rgbindex gli ci hue i ngrdi ri s if performs the calculation of the index with the values instantiated in the class str index abbreviation of index name to perform atmospherically resistant vegetation index 2 https www indexdatabase de db i single php id 396 return index 0 18 1 17 self nir self red self nir self red canopy chlorophyll content index https www indexdatabase de db i single php id 224 return index chlorophyll vegetation index https www indexdatabase de db i single php id 391 return index self green leaf index https www indexdatabase de db i single php id 375 return index normalized difference self nir self red normalized difference vegetation index calibrated ndvi cdvi https www indexdatabase de db i single php id 58 return index normalized difference self nir self blue self blue normalized difference vegetation index https www indexdatabase de db i single php id 135 return index normalized difference self rededge self red https www indexdatabase de db i single php id 235 return index normalized difference self nir self green self green ndvi https www indexdatabase de db i single php id 401 return index self green self blue ndvi https www indexdatabase de db i single php id 186 return index self green self red ndvi https www indexdatabase de db i single php id 185 return index self red self blue ndvi https www indexdatabase de db i single php id 187 return index pan ndvi https www indexdatabase de db i single php id 188 return index adjusted transformed soil adjusted vi https www indexdatabase de db i single php id 209 return index self blue wide dynamic range vegetation index https www indexdatabase de db i single php id 136 return index chlorophyll index self green https www indexdatabase de db i single php id 128 return index chlorophyll index self rededge https www indexdatabase de db i single php id 131 return index coloration index https www indexdatabase de db i single php id 11 return index corrected transformed vegetation index https www indexdatabase de db i single php id 244 return index difference self nir self green self green difference vegetation index https www indexdatabase de db i single php id 27 return index enhanced vegetation index https www indexdatabase de db i single php id 16 return index global environment monitoring index https www indexdatabase de db i single php id 25 return index self green optimized soil adjusted vegetation index https www indexdatabase de db i single php id 29 mit y 0 16 return index self green soil adjusted vegetation index https www indexdatabase de db i single php id 31 mit n 0 5 return index hue https www indexdatabase de db i single php id 34 return index ideal vegetation index https www indexdatabase de db i single php id 276 b intercept of vegetation line a soil line slope return index infraself red percentage vegetation index https www indexdatabase de db i single php id 35 return index intensity https www indexdatabase de db i single php id 36 return index ratio vegetation index http www seos project eu modules remotesensing remotesensing c03 s01 p01 html return index modified normalized difference vegetation index rvi https www indexdatabase de db i single php id 275 return index modified soil adjusted vegetation index https www indexdatabase de db i single php id 44 return index norm g https www indexdatabase de db i single php id 50 return index norm self nir https www indexdatabase de db i single php id 51 return index norm r https www indexdatabase de db i single php id 52 return index normalized difference self green self red normalized self green self red difference index visible atmospherically resistant indices self green viself green https www indexdatabase de db i single php id 390 return index normalized difference self red self green self redness index https www indexdatabase de db i single php id 74 return index saturation https www indexdatabase de db i single php id 77 return index shape index https www indexdatabase de db i single php id 79 return index simple ratio self nir self red difference vegetation index vegetation index number vin https www indexdatabase de db i single php id 12 return index transformed vegetation index https www indexdatabase de db i single php id 98 return index genering a random matrices to test this class red np ones 1000 1000 1 dtype float64 46787 green np ones 1000 1000 1 dtype float64 23487 blue np ones 1000 1000 1 dtype float64 14578 rededge np ones 1000 1000 1 dtype float64 51045 nir np ones 1000 1000 1 dtype float64 52200 examples of how to use the class instantiating the class cl indexcalculation instantiating the class with the values cl indexcalculation red red green green blue blue rededge rededge nir nir how set the values after instantiate the class cl for update the data or when don t instantiating the class with the values cl setmatrices red red green green blue blue rededge rededge nir nir calculating the indices for the instantiated values in the class note the ccci index can be changed to any index implemented in the class indexvalue_form1 cl calculation ccci red red green green blue blue rededge rededge nir nir astype np float64 indexvalue_form2 cl ccci calculating the index with the values directly you can set just the values preferred note the calculation function performs the function setmatrices indexvalue_form3 cl calculation ccci red red green green blue blue rededge rededge nir nir astype np float64 print form 1 np array2string indexvalue_form1 precision 20 separator floatmode maxprec_equal print form 2 np array2string indexvalue_form2 precision 20 separator floatmode maxprec_equal print form 3 np array2string indexvalue_form3 precision 20 separator floatmode maxprec_equal a list of examples results for different type of data at ndvi float16 0 31567383 ndvi red 50 nir 100 float32 0 31578946 ndvi red 50 nir 100 float64 0 3157894736842105 ndvi red 50 nir 100 longdouble 0 3157894736842105 ndvi red 50 nir 100
import numpy as np class IndexCalculation: def __init__(self, red=None, green=None, blue=None, red_edge=None, nir=None): self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) def set_matricies(self, red=None, green=None, blue=None, red_edge=None, nir=None): if red is not None: self.red = red if green is not None: self.green = green if blue is not None: self.blue = blue if red_edge is not None: self.redEdge = red_edge if nir is not None: self.nir = nir return True def calculation( self, index="", red=None, green=None, blue=None, red_edge=None, nir=None ): self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) funcs = { "ARVI2": self.arv12, "CCCI": self.ccci, "CVI": self.cvi, "GLI": self.gli, "NDVI": self.ndvi, "BNDVI": self.bndvi, "redEdgeNDVI": self.red_edge_ndvi, "GNDVI": self.gndvi, "GBNDVI": self.gbndvi, "GRNDVI": self.grndvi, "RBNDVI": self.rbndvi, "PNDVI": self.pndvi, "ATSAVI": self.atsavi, "BWDRVI": self.bwdrvi, "CIgreen": self.ci_green, "CIrededge": self.ci_rededge, "CI": self.ci, "CTVI": self.ctvi, "GDVI": self.gdvi, "EVI": self.evi, "GEMI": self.gemi, "GOSAVI": self.gosavi, "GSAVI": self.gsavi, "Hue": self.hue, "IVI": self.ivi, "IPVI": self.ipvi, "I": self.i, "RVI": self.rvi, "MRVI": self.mrvi, "MSAVI": self.m_savi, "NormG": self.norm_g, "NormNIR": self.norm_nir, "NormR": self.norm_r, "NGRDI": self.ngrdi, "RI": self.ri, "S": self.s, "IF": self._if, "DVI": self.dvi, "TVI": self.tvi, "NDRE": self.ndre, } try: return funcs[index]() except KeyError: print("Index not in the list!") return False def arv12(self): return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red))) def ccci(self): return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def cvi(self): return self.nir * (self.red / (self.green**2)) def gli(self): return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def ndvi(self): return (self.nir - self.red) / (self.nir + self.red) def bndvi(self): return (self.nir - self.blue) / (self.nir + self.blue) def red_edge_ndvi(self): return (self.redEdge - self.red) / (self.redEdge + self.red) def gndvi(self): return (self.nir - self.green) / (self.nir + self.green) def gbndvi(self): return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def grndvi(self): return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def rbndvi(self): return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def pndvi(self): return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def atsavi(self, x=0.08, a=1.22, b=0.03): return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def bwdrvi(self): return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def ci_green(self): return (self.nir / self.green) - 1 def ci_rededge(self): return (self.nir / self.redEdge) - 1 def ci(self): return (self.red - self.blue) / self.red def ctvi(self): ndvi = self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5))) * (abs(ndvi + 0.5) ** (1 / 2)) def gdvi(self): return self.nir - self.green def evi(self): return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def gemi(self): n = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red) def gosavi(self, y=0.16): return (self.nir - self.green) / (self.nir + self.green + y) def gsavi(self, n=0.5): return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def hue(self): return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def ivi(self, a=None, b=None): return (self.nir - b) / (a * self.red) def ipvi(self): return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def i(self): return (self.red + self.green + self.blue) / 30.5 def rvi(self): return self.nir / self.red def mrvi(self): return (self.rvi() - 1) / (self.rvi() + 1) def m_savi(self): return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def norm_g(self): return self.green / (self.nir + self.red + self.green) def norm_nir(self): return self.nir / (self.nir + self.red + self.green) def norm_r(self): return self.red / (self.nir + self.red + self.green) def ngrdi(self): return (self.green - self.red) / (self.green + self.red) def ri(self): return (self.red - self.green) / (self.red + self.green) def s(self): max_value = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) min_value = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) return (max_value - min_value) / max_value def _if(self): return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def dvi(self): return self.nir / self.red def tvi(self): return (self.ndvi() + 0.5) ** (1 / 2) def ndre(self): return (self.nir - self.redEdge) / (self.nir + self.redEdge)
return gray image from rgb image rgbtograynp array127 255 0 array187 6453 rgbtograynp array0 0 0 array0 rgbtograynp array2 4 1 array3 0598 rgbtograynp array26 255 14 5 147 20 1 200 0 array159 0524 90 0635 117 6989 return binary image from gray image graytobinarynp array127 255 0 arrayfalse true false graytobinarynp array0 arrayfalse graytobinarynp array26 2409 4 9315 1 4729 arrayfalse false false graytobinarynp array26 255 14 5 147 20 1 200 0 arrayfalse true false false true false false true false return dilated image dilationnp arraytrue false true np array0 1 0 arrayfalse false false dilationnp arrayfalse false true np array1 0 1 arrayfalse false false copy image to padded image iterate over image apply kernel read original image kernel to be applied save the output image return gray image from rgb image rgb_to_gray np array 127 255 0 array 187 6453 rgb_to_gray np array 0 0 0 array 0 rgb_to_gray np array 2 4 1 array 3 0598 rgb_to_gray np array 26 255 14 5 147 20 1 200 0 array 159 0524 90 0635 117 6989 return binary image from gray image gray_to_binary np array 127 255 0 array false true false gray_to_binary np array 0 array false gray_to_binary np array 26 2409 4 9315 1 4729 array false false false gray_to_binary np array 26 255 14 5 147 20 1 200 0 array false true false false true false false true false return dilated image dilation np array true false true np array 0 1 0 array false false false dilation np array false false true np array 1 0 1 array false false false copy image to padded image iterate over image apply kernel read original image kernel to be applied save the output image
from pathlib import Path import numpy as np from PIL import Image def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray_to_binary(gray: np.ndarray) -> np.ndarray: return (gray > 127) & (gray <= 255) def dilation(image: np.ndarray, kernel: np.ndarray) -> np.ndarray: output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation > 0) return output if __name__ == "__main__": lena_path = Path(__file__).resolve().parent / "image_data" / "lena.jpg" lena = np.array(Image.open(lena_path)) structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) output = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
return gray image from rgb image rgbtograynp array127 255 0 array187 6453 rgbtograynp array0 0 0 array0 rgbtograynp array2 4 1 array3 0598 rgbtograynp array26 255 14 5 147 20 1 200 0 array159 0524 90 0635 117 6989 return binary image from gray image graytobinarynp array127 255 0 arrayfalse true false graytobinarynp array0 arrayfalse graytobinarynp array26 2409 4 9315 1 4729 arrayfalse false false graytobinarynp array26 255 14 5 147 20 1 200 0 arrayfalse true false false true false false true false return eroded image erosionnp arraytrue true false np array0 1 0 arrayfalse false false erosionnp arraytrue false false np array1 1 0 arrayfalse false false copy image to padded image iterate over image apply kernel read original image kernel to be applied apply erosion operation to a binary image save the output image return gray image from rgb image rgb_to_gray np array 127 255 0 array 187 6453 rgb_to_gray np array 0 0 0 array 0 rgb_to_gray np array 2 4 1 array 3 0598 rgb_to_gray np array 26 255 14 5 147 20 1 200 0 array 159 0524 90 0635 117 6989 return binary image from gray image gray_to_binary np array 127 255 0 array false true false gray_to_binary np array 0 array false gray_to_binary np array 26 2409 4 9315 1 4729 array false false false gray_to_binary np array 26 255 14 5 147 20 1 200 0 array false true false false true false false true false return eroded image erosion np array true true false np array 0 1 0 array false false false erosion np array true false false np array 1 1 0 array false false false copy image to padded image iterate over image apply kernel read original image kernel to be applied apply erosion operation to a binary image save the output image
from pathlib import Path import numpy as np from PIL import Image def rgb_to_gray(rgb: np.ndarray) -> np.ndarray: r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray_to_binary(gray: np.ndarray) -> np.ndarray: return (gray > 127) & (gray <= 255) def erosion(image: np.ndarray, kernel: np.ndarray) -> np.ndarray: output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation == 5) return output if __name__ == "__main__": lena_path = Path(__file__).resolve().parent / "image_data" / "lena.jpg" lena = np.array(Image.open(lena_path)) structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) output = erosion(gray_to_binary(rgb_to_gray(lena)), structuring_element) pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_erosion.png")
multiple image resizing techniques import numpy as np from cv2 import destroyallwindows imread imshow waitkey class nearestneighbour def initself img dstwidth int dstheight int if dstwidth 0 or dstheight 0 raise valueerrordestination widthheight should be 0 self img img self srcw img shape1 self srch img shape0 self dstw dstwidth self dsth dstheight self ratiox self srcw self dstw self ratioy self srch self dsth self output self outputimg np onesself dsth self dstw 3 np uint8 255 def processself for i in rangeself dsth for j in rangeself dstw self outputij self imgself getyiself getxj def getxself x int int return intself ratiox x def getyself y int int return intself ratioy y if name main dstw dsth 800 600 im imreadimagedatalena jpg 1 n nearestneighbourim dstw dsth n process imshow fimage resized from im shape1xim shape0 to dstwxdsth n output waitkey0 destroyallwindows simplest and fastest version of image resizing source https en wikipedia org wiki nearest neighbor_interpolation get parent x coordinate for destination x param x destination x coordinate return parent x coordinate based on x ratio nn nearestneighbour imread digital_image_processing image_data lena jpg 1 100 100 nn ratio_x 0 5 nn get_x 4 2 get parent y coordinate for destination y param y destination x coordinate return parent x coordinate based on y ratio nn nearestneighbour imread digital_image_processing image_data lena jpg 1 100 100 nn ratio_y 0 5 nn get_y 4 2
import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class NearestNeighbour: def __init__(self, img, dst_width: int, dst_height: int): if dst_width < 0 or dst_height < 0: raise ValueError("Destination width/height should be > 0") self.img = img self.src_w = img.shape[1] self.src_h = img.shape[0] self.dst_w = dst_width self.dst_h = dst_height self.ratio_x = self.src_w / self.dst_w self.ratio_y = self.src_h / self.dst_h self.output = self.output_img = ( np.ones((self.dst_h, self.dst_w, 3), np.uint8) * 255 ) def process(self): for i in range(self.dst_h): for j in range(self.dst_w): self.output[i][j] = self.img[self.get_y(i)][self.get_x(j)] def get_x(self, x: int) -> int: return int(self.ratio_x * x) def get_y(self, y: int) -> int: return int(self.ratio_y * y) if __name__ == "__main__": dst_w, dst_h = 800, 600 im = imread("image_data/lena.jpg", 1) n = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( f"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output ) waitKey(0) destroyAllWindows()
get image rotation param img np ndarray param pt1 3x2 list param pt2 3x2 list param rows columns image shape param cols rows image shape return np ndarray read original image turn image in gray scale value get image shape set different points to rotate image add all rotated images in a list plot different image rotations get image rotation param img np ndarray param pt1 3x2 list param pt2 3x2 list param rows columns image shape param cols rows image shape return np ndarray read original image turn image in gray scale value get image shape set different points to rotate image add all rotated images in a list plot different image rotations
from pathlib import Path import cv2 import numpy as np from matplotlib import pyplot as plt def get_rotation( img: np.ndarray, pt1: np.ndarray, pt2: np.ndarray, rows: int, cols: int ) -> np.ndarray: matrix = cv2.getAffineTransform(pt1, pt2) return cv2.warpAffine(img, matrix, (rows, cols)) if __name__ == "__main__": image = cv2.imread( str(Path(__file__).resolve().parent.parent / "image_data" / "lena.jpg") ) gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) img_rows, img_cols = gray_img.shape pts1 = np.array([[50, 50], [200, 50], [50, 200]], np.float32) pts2 = np.array([[10, 100], [200, 50], [100, 250]], np.float32) pts3 = np.array([[50, 50], [150, 50], [120, 200]], np.float32) pts4 = np.array([[10, 100], [80, 50], [180, 250]], np.float32) images = [ gray_img, get_rotation(gray_img, pts1, pts2, img_rows, img_cols), get_rotation(gray_img, pts2, pts3, img_rows, img_cols), get_rotation(gray_img, pts2, pts4, img_rows, img_cols), ] fig = plt.figure(1) titles = ["Original", "Rotation 1", "Rotation 2", "Rotation 3"] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, "gray") plt.title(titles[i]) plt.axis("off") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
implemented an algorithm using opencv to tone an image with sepia technique function create sepia tone source https en wikipedia orgwikisepiacolor helper function to create pixel s greyscale representation src https pl wikipedia orgwikiyuv helper function to normalize rgb value return 255 if value 255 return minvalue 255 for i in rangepixelh for j in rangepixelv greyscale inttograyscaleimgij imgij normalizegreyscale normalizegreyscale factor normalizegreyscale 2 factor return img if name main read original image images percentage imreadimagedatalena jpg 1 for percentage in 10 20 30 40 for percentage img in images items makesepiaimg percentage for percentage img in images items imshowforiginal image with sepia factor percentage img waitkey0 destroyallwindows function create sepia tone source https en wikipedia org wiki sepia_ color helper function to create pixel s greyscale representation src https pl wikipedia org wiki yuv helper function to normalize r g b value return 255 if value 255 read original image
from cv2 import destroyAllWindows, imread, imshow, waitKey def make_sepia(img, factor: int): pixel_h, pixel_v = img.shape[0], img.shape[1] def to_grayscale(blue, green, red): return 0.2126 * red + 0.587 * green + 0.114 * blue def normalize(value): return min(value, 255) for i in range(pixel_h): for j in range(pixel_v): greyscale = int(to_grayscale(*img[i][j])) img[i][j] = [ normalize(greyscale), normalize(greyscale + factor), normalize(greyscale + 2 * factor), ] return img if __name__ == "__main__": images = { percentage: imread("image_data/lena.jpg", 1) for percentage in (10, 20, 30, 40) } for percentage, img in images.items(): make_sepia(img, percentage) for percentage, img in images.items(): imshow(f"Original image with sepia (factor: {percentage})", img) waitKey(0) destroyAllWindows()
pytest s for digital image processing test converttonegative assert negativeimg array for at least one true test changecontrast work around assertion for response canny gengaussiankernel assert ambiguous array canny py assert ambiguous array for all true assert canny array for at least one true filtersgaussianfilter py laplace diagonals pull request 10161 before digitalimageprocessingimagedatalena jpg after digitalimageprocessingimagedatalenasmall jpg reading the image and converting it to grayscale test for getneighborspixel function return not none test for localbinarypattern function create a numpy array as the same height and width of read image iterating through the image and calculating the local binary pattern value for each pixel test convert_to_negative assert negative_img array for at least one true test change_contrast work around assertion for response canny gen_gaussian_kernel assert ambiguous array canny py assert ambiguous array for all true assert canny array for at least one true filters gaussian_filter py laplace diagonals pull request 10161 before digital_image_processing image_data lena jpg after digital_image_processing image_data lena_small jpg speed up our continuous integration tests reading the image and converting it to grayscale test for get_neighbors_pixel function return not none test for local_binary_pattern function create a numpy array as the same height and width of read image iterating through the image and calculating the local binary pattern value for each pixel
import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uint8 from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs img = imread(r"digital_image_processing/image_data/lena_small.jpg") gray = cvtColor(img, COLOR_BGR2GRAY) def test_convert_to_negative(): negative_img = cn.convert_to_negative(img) assert negative_img.any() def test_change_contrast(): with Image.open("digital_image_processing/image_data/lena_small.jpg") as img: assert str(cc.change_contrast(img, 110)).startswith( "<PIL.Image.Image image mode=RGB size=100x100 at" ) def test_gen_gaussian_kernel(): resp = canny.gen_gaussian_kernel(9, sigma=1.4) assert resp.all() def test_canny(): canny_img = imread("digital_image_processing/image_data/lena_small.jpg", 0) assert canny_img.all() canny_array = canny.canny(canny_img) assert canny_array.any() def test_gen_gaussian_kernel_filter(): assert gg.gaussian_filter(gray, 5, sigma=0.9).all() def test_convolve_filter(): laplace = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]]) res = conv.img_convolve(gray, laplace).astype(uint8) assert res.any() def test_median_filter(): assert med.median_filter(gray, 3).any() def test_sobel_filter(): grad, theta = sob.sobel_filter(gray) assert grad.any() assert theta.any() def test_sepia(): sepia = sp.make_sepia(img, 20) assert sepia.all() def test_burkes(file_path: str = "digital_image_processing/image_data/lena_small.jpg"): burkes = bs.Burkes(imread(file_path, 1), 120) burkes.process() assert burkes.output_img.any() def test_nearest_neighbour( file_path: str = "digital_image_processing/image_data/lena_small.jpg", ): nn = rs.NearestNeighbour(imread(file_path, 1), 400, 200) nn.process() assert nn.output.any() def test_local_binary_pattern(): from os import getenv file_name = "lena_small.jpg" if getenv("CI") else "lena.jpg" file_path = f"digital_image_processing/image_data/{file_name}" image = imread(file_path, 0) x_coordinate = 0 y_coordinate = 0 center = image[x_coordinate][y_coordinate] neighbors_pixels = lbp.get_neighbors_pixel( image, x_coordinate, y_coordinate, center ) assert neighbors_pixels is not None lbp_image = np.zeros((image.shape[0], image.shape[1])) for i in range(image.shape[0]): for j in range(image.shape[1]): lbp_image[i][j] = lbp.local_binary_value(image, i, j) assert lbp_image.any()
the algorithm finds distance between closest pair of points in the given n points approach used divide and conquer the points are sorted based on xcoords and then based on ycoords separately and by applying divide and conquer approach minimum distance is obtained recursively closest points can lie on different sides of partition this case handled by forming a strip of points whose xcoords distance is less than closestpairdis from midpoint s xcoords points sorted based on ycoords are used in this step to reduce sorting time closest pair distance is found in the strip of points closestinstrip minclosestpairdis closestinstrip would be the final answer time complexity on log n euclideandistancesqr1 2 2 4 5 columnbasedsort5 1 4 2 3 0 1 3 0 5 1 4 2 brute force approach to find distance between closest pair points parameters points pointscount mindis listtupleint int int int returns mindis float distance between closest pair of points disbetweenclosestpair1 2 2 4 5 7 8 9 11 0 5 5 closest pair of points in strip parameters points pointscount mindis listtupleint int int int returns mindis float distance btw closest pair of points in the strip mindis disbetweenclosestinstrip1 2 2 4 5 7 8 9 11 0 5 85 divide and conquer approach parameters points pointscount listtupleint int int returns float distance btw closest pair of points closestpairofpointssqr1 2 3 4 5 6 7 8 2 8 base case recursion crossstrip contains the points whose xcoords are at a distance closestpairdis from mid s xcoord closestpairofpoints2 3 12 30 len2 3 12 30 28 792360097775937 euclidean_distance_sqr 1 2 2 4 5 column_based_sort 5 1 4 2 3 0 1 3 0 5 1 4 2 brute force approach to find distance between closest pair points parameters points points_count min_dis list tuple int int int int returns min_dis float distance between closest pair of points dis_between_closest_pair 1 2 2 4 5 7 8 9 11 0 5 5 closest pair of points in strip parameters points points_count min_dis list tuple int int int int returns min_dis float distance btw closest pair of points in the strip min_dis dis_between_closest_in_strip 1 2 2 4 5 7 8 9 11 0 5 85 divide and conquer approach parameters points points_count list tuple int int int returns float distance btw closest pair of points closest_pair_of_points_sqr 1 2 3 4 5 6 7 8 2 8 base case recursion cross_strip contains the points whose xcoords are at a distance closest_pair_dis from mid s xcoord closest_pair_of_points 2 3 12 30 len 2 3 12 30 28 792360097775937
def euclidean_distance_sqr(point1, point2): return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 def column_based_sort(array, column=0): return sorted(array, key=lambda x: x[column]) def dis_between_closest_pair(points, points_counts, min_dis=float("inf")): for i in range(points_counts - 1): for j in range(i + 1, points_counts): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")): for i in range(min(6, points_counts - 1), points_counts): for j in range(max(0, i - 6), i): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts): if points_counts <= 3: return dis_between_closest_pair(points_sorted_on_x, points_counts) mid = points_counts // 2 closest_in_left = closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y[:mid], mid ) closest_in_right = closest_pair_of_points_sqr( points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid ) closest_pair_dis = min(closest_in_left, closest_in_right) cross_strip = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis: cross_strip.append(point) closest_in_strip = dis_between_closest_in_strip( cross_strip, len(cross_strip), closest_pair_dis ) return min(closest_pair_dis, closest_in_strip) def closest_pair_of_points(points, points_counts): points_sorted_on_x = column_based_sort(points, column=0) points_sorted_on_y = column_based_sort(points, column=1) return ( closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y, points_counts ) ) ** 0.5 if __name__ == "__main__": points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
the convex hull problem is problem of finding all the vertices of convex polygon p of a set of points in a plane such that all the points are either on the vertices of p or inside p th convex hull problem has several applications in geometrical problems computer graphics and game development two algorithms have been implemented for the convex hull problem here 1 a bruteforce algorithm which runs in on3 2 a divideandconquer algorithm which runs in on logn there are other several other algorithms for the convex hull problem which have not been implemented here yet defines a 2d point for use by all convexhull algorithms parameters x an int or a float the xcoordinate of the 2d point y an int or a float the ycoordinate of the 2d point examples point1 2 1 0 2 0 point1 2 1 0 2 0 point1 2 point0 1 true point1 1 point1 1 true point0 5 1 point0 5 1 false pointpi e traceback most recent call last valueerror could not convert string to float pi constructs a list of points from an arraylike object of numbers arguments listoftuples arraylike object of type numbers acceptable types so far are lists tuples and sets returns points a list where each item is of type point this contains only objects which can be converted into a point examples constructpoints1 1 2 1 0 3 4 1 0 1 0 2 0 1 0 0 3 4 0 constructpoints1 2 ignoring deformed point 1 all points must have at least 2 coordinates ignoring deformed point 2 all points must have at least 2 coordinates constructpoints constructpointsnone validates an input instance before a convexhull algorithms uses it parameters points arraylike the 2d points to validate before using with a convexhull algorithm the elements of points must be either lists tuples or points returns points arraylike an iterable of all welldefined points constructed passed in exception valueerror if points is empty or none or if a wrong data structure like a scalar is passed typeerror if an iterable but nonindexable object eg dictionary is passed the exception to this a set which we ll convert to a list before using examples validateinput1 2 1 0 2 0 validateinput1 2 1 0 2 0 validateinputpoint2 1 point1 2 2 0 1 0 1 0 2 0 validateinput traceback most recent call last valueerror expecting a list of points but got validateinput1 traceback most recent call last valueerror expecting an iterable object but got an noniterable type 1 computes the sign perpendicular distance of a 2d point c from a line segment ab the sign indicates the direction of c relative to ab a positive value means c is above ab to the left while a negative value means c is below ab to the right 0 means all three points are on a straight line as a side note 0 5 absdet is the area of triangle abc parameters a point the point on the left end of line segment ab b point the point on the right end of line segment ab c point the point for which the direction and location is desired returns det float absdet is the distance of c from ab the sign indicates which side of line segment ab c is det is computed as axby cxay bxcy aybx cyax bycx examples detpoint1 1 point1 2 point1 5 0 0 detpoint0 0 point10 0 point0 10 100 0 detpoint0 0 point10 0 point0 10 100 0 constructs the convex hull of a set of 2d points using a brute force algorithm the algorithm basically considers all combinations of points i j and uses the definition of convexity to determine whether i j is part of the convex hull or not i j is part of the convex hull if and only iff there are no points on both sides of the line segment connecting the ij and there is no point k such that k is on either end of the ij runtime on3 definitely horrible parameters points arraylike of object of points lists or tuples the set of 2d points for which the convexhull is needed returns convexset list the convexhull of points sorted in nondecreasing order see also convexhullrecursive examples convexhullbf0 0 1 0 10 1 0 0 0 0 1 0 0 0 10 0 1 0 convexhullbf0 0 1 0 10 0 0 0 0 0 10 0 0 0 convexhullbf1 1 1 1 0 0 0 5 0 5 1 1 1 1 0 75 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 convexhullbf0 3 2 2 1 1 2 1 3 0 0 0 3 3 2 1 2 4 1 3 0 0 0 0 0 0 3 0 1 0 3 0 2 0 4 0 3 0 0 0 3 0 3 0 pointi pointj pointk all lie on a straight line if pointk is to the left of pointi or it s to the right of pointj then pointi pointj cannot be part of the convex hull of a constructs the convex hull of a set of 2d points using a divideandconquer strategy the algorithm exploits the geometric properties of the problem by repeatedly partitioning the set of points into smaller hulls and finding the convex hull of these smaller hulls the union of the convex hull from smaller hulls is the solution to the convex hull of the larger problem parameter points arraylike of object of points lists or tuples the set of 2d points for which the convexhull is needed runtime on log n returns convexset list the convexhull of points sorted in nondecreasing order examples convexhullrecursive0 0 1 0 10 1 0 0 0 0 1 0 0 0 10 0 1 0 convexhullrecursive0 0 1 0 10 0 0 0 0 0 10 0 0 0 convexhullrecursive1 1 1 1 0 0 0 5 0 5 1 1 1 1 0 75 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 convexhullrecursive0 3 2 2 1 1 2 1 3 0 0 0 3 3 2 1 2 4 1 3 0 0 0 0 0 0 3 0 1 0 3 0 2 0 4 0 3 0 0 0 3 0 3 0 divide all the points into an upper hull and a lower hull the left most point and the right most point are definitely members of the convex hull by definition use these two anchors to divide all the points into two hulls an upper hull and a lower hull all points to the left above the line joining the extreme points belong to the upper hull all points to the right below the line joining the extreme points below to the lower hull ignore all points on the line joining the extreme points since they cannot be part of the convex hull parameters points list or none the hull of points from which to choose the next convexhull point left point the point to the left of line segment joining left and right right the point to the right of the line segment joining left and right convexset set the current convexhull the state of convexset gets updated by this function note for the line segment ab a is on the left and b on the right but the reverse is true for the line segment ba returns nothing only updates the state of convexset constructs the convex hull of a set of 2d points using the melkman algorithm the algorithm works by iteratively inserting points of a simple polygonal chain meaning that no line segments between two consecutive points cross each other sorting the points yields such a polygonal chain for a detailed description see http cgm cs mcgill caathenscs601melkman html runtime on log n on if points are already sorted in the input parameters points arraylike of object of points lists or tuples the set of 2d points for which the convexhull is needed returns convexset list the convexhull of points sorted in nondecreasing order see also examples convexhullmelkman0 0 1 0 10 1 0 0 0 0 1 0 0 0 10 0 1 0 convexhullmelkman0 0 1 0 10 0 0 0 0 0 10 0 0 0 convexhullmelkman1 1 1 1 0 0 0 5 0 5 1 1 1 1 0 75 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 convexhullmelkman0 3 2 2 1 1 2 1 3 0 0 0 3 3 2 1 2 4 1 3 0 0 0 0 0 0 3 0 1 0 3 0 2 0 4 0 3 0 0 0 3 0 3 0 the point lies within the convex hull convexhull is contains the convex hull in circular order the convex set of points is 0 0 0 3 1 3 2 4 3 0 3 3 defines a 2 d point for use by all convex hull algorithms parameters x an int or a float the x coordinate of the 2 d point y an int or a float the y coordinate of the 2 d point examples point 1 2 1 0 2 0 point 1 2 1 0 2 0 point 1 2 point 0 1 true point 1 1 point 1 1 true point 0 5 1 point 0 5 1 false point pi e traceback most recent call last valueerror could not convert string to float pi constructs a list of points from an array like object of numbers arguments list_of_tuples array like object of type numbers acceptable types so far are lists tuples and sets returns points a list where each item is of type point this contains only objects which can be converted into a point examples _construct_points 1 1 2 1 0 3 4 1 0 1 0 2 0 1 0 0 3 4 0 _construct_points 1 2 ignoring deformed point 1 all points must have at least 2 coordinates ignoring deformed point 2 all points must have at least 2 coordinates _construct_points _construct_points none validates an input instance before a convex hull algorithms uses it parameters points array like the 2d points to validate before using with a convex hull algorithm the elements of points must be either lists tuples or points returns points array_like an iterable of all well defined points constructed passed in exception valueerror if points is empty or none or if a wrong data structure like a scalar is passed typeerror if an iterable but non indexable object eg dictionary is passed the exception to this a set which we ll convert to a list before using examples _validate_input 1 2 1 0 2 0 _validate_input 1 2 1 0 2 0 _validate_input point 2 1 point 1 2 2 0 1 0 1 0 2 0 _validate_input traceback most recent call last valueerror expecting a list of points but got _validate_input 1 traceback most recent call last valueerror expecting an iterable object but got an non iterable type 1 computes the sign perpendicular distance of a 2d point c from a line segment ab the sign indicates the direction of c relative to ab a positive value means c is above ab to the left while a negative value means c is below ab to the right 0 means all three points are on a straight line as a side note 0 5 abs det is the area of triangle abc parameters a point the point on the left end of line segment ab b point the point on the right end of line segment ab c point the point for which the direction and location is desired returns det float abs det is the distance of c from ab the sign indicates which side of line segment ab c is det is computed as a_xb_y c_xa_y b_xc_y a_yb_x c_ya_x b_yc_x examples _det point 1 1 point 1 2 point 1 5 0 0 _det point 0 0 point 10 0 point 0 10 100 0 _det point 0 0 point 10 0 point 0 10 100 0 constructs the convex hull of a set of 2d points using a brute force algorithm the algorithm basically considers all combinations of points i j and uses the definition of convexity to determine whether i j is part of the convex hull or not i j is part of the convex hull if and only iff there are no points on both sides of the line segment connecting the ij and there is no point k such that k is on either end of the ij runtime o n 3 definitely horrible parameters points array like of object of points lists or tuples the set of 2d points for which the convex hull is needed returns convex_set list the convex hull of points sorted in non decreasing order see also convex_hull_recursive examples convex_hull_bf 0 0 1 0 10 1 0 0 0 0 1 0 0 0 10 0 1 0 convex_hull_bf 0 0 1 0 10 0 0 0 0 0 10 0 0 0 convex_hull_bf 1 1 1 1 0 0 0 5 0 5 1 1 1 1 0 75 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 convex_hull_bf 0 3 2 2 1 1 2 1 3 0 0 0 3 3 2 1 2 4 1 3 0 0 0 0 0 0 3 0 1 0 3 0 2 0 4 0 3 0 0 0 3 0 3 0 point i point j point k all lie on a straight line if point k is to the left of point i or it s to the right of point j then point i point j cannot be part of the convex hull of a constructs the convex hull of a set of 2d points using a divide and conquer strategy the algorithm exploits the geometric properties of the problem by repeatedly partitioning the set of points into smaller hulls and finding the convex hull of these smaller hulls the union of the convex hull from smaller hulls is the solution to the convex hull of the larger problem parameter points array like of object of points lists or tuples the set of 2d points for which the convex hull is needed runtime o n log n returns convex_set list the convex hull of points sorted in non decreasing order examples convex_hull_recursive 0 0 1 0 10 1 0 0 0 0 1 0 0 0 10 0 1 0 convex_hull_recursive 0 0 1 0 10 0 0 0 0 0 10 0 0 0 convex_hull_recursive 1 1 1 1 0 0 0 5 0 5 1 1 1 1 0 75 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 convex_hull_recursive 0 3 2 2 1 1 2 1 3 0 0 0 3 3 2 1 2 4 1 3 0 0 0 0 0 0 3 0 1 0 3 0 2 0 4 0 3 0 0 0 3 0 3 0 divide all the points into an upper hull and a lower hull the left most point and the right most point are definitely members of the convex hull by definition use these two anchors to divide all the points into two hulls an upper hull and a lower hull all points to the left above the line joining the extreme points belong to the upper hull all points to the right below the line joining the extreme points below to the lower hull ignore all points on the line joining the extreme points since they cannot be part of the convex hull parameters points list or none the hull of points from which to choose the next convex hull point left point the point to the left of line segment joining left and right right the point to the right of the line segment joining left and right convex_set set the current convex hull the state of convex set gets updated by this function note for the line segment ab a is on the left and b on the right but the reverse is true for the line segment ba returns nothing only updates the state of convex set constructs the convex hull of a set of 2d points using the melkman algorithm the algorithm works by iteratively inserting points of a simple polygonal chain meaning that no line segments between two consecutive points cross each other sorting the points yields such a polygonal chain for a detailed description see http cgm cs mcgill ca athens cs601 melkman html runtime o n log n o n if points are already sorted in the input parameters points array like of object of points lists or tuples the set of 2d points for which the convex hull is needed returns convex_set list the convex hull of points sorted in non decreasing order see also examples convex_hull_melkman 0 0 1 0 10 1 0 0 0 0 1 0 0 0 10 0 1 0 convex_hull_melkman 0 0 1 0 10 0 0 0 0 0 10 0 0 0 convex_hull_melkman 1 1 1 1 0 0 0 5 0 5 1 1 1 1 0 75 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 convex_hull_melkman 0 3 2 2 1 1 2 1 3 0 0 0 3 3 2 1 2 4 1 3 0 0 0 0 0 0 3 0 1 0 3 0 2 0 4 0 3 0 0 0 3 0 3 0 the point lies within the convex hull convex_hull is contains the convex hull in circular order the convex set of points is 0 0 0 3 1 3 2 4 3 0 3 3
from __future__ import annotations from collections.abc import Iterable class Point: def __init__(self, x, y): self.x, self.y = float(x), float(y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return not self == other def __gt__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y > other.y return False def __lt__(self, other): return not self > other def __ge__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y >= other.y return False def __le__(self, other): if self.x < other.x: return True elif self.x == other.x: return self.y <= other.y return False def __repr__(self): return f"({self.x}, {self.y})" def __hash__(self): return hash(self.x) def _construct_points( list_of_tuples: list[Point] | list[list[float]] | Iterable[list[float]], ) -> list[Point]: points: list[Point] = [] if list_of_tuples: for p in list_of_tuples: if isinstance(p, Point): points.append(p) else: try: points.append(Point(p[0], p[1])) except (IndexError, TypeError): print( f"Ignoring deformed point {p}. All points" " must have at least 2 coordinates." ) return points def _validate_input(points: list[Point] | list[list[float]]) -> list[Point]: if not hasattr(points, "__iter__"): msg = f"Expecting an iterable object but got an non-iterable type {points}" raise ValueError(msg) if not points: msg = f"Expecting a list of points but got {points}" raise ValueError(msg) return _construct_points(points) def _det(a: Point, b: Point, c: Point) -> float: det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x) return det def convex_hull_bf(points: list[Point]) -> list[Point]: points = sorted(_validate_input(points)) n = len(points) convex_set = set() for i in range(n - 1): for j in range(i + 1, n): points_left_of_ij = points_right_of_ij = False ij_part_of_convex_hull = True for k in range(n): if k not in {i, j}: det_k = _det(points[i], points[j], points[k]) if det_k > 0: points_left_of_ij = True elif det_k < 0: points_right_of_ij = True else: if points[k] < points[i] or points[k] > points[j]: ij_part_of_convex_hull = False break if points_left_of_ij and points_right_of_ij: ij_part_of_convex_hull = False break if ij_part_of_convex_hull: convex_set.update([points[i], points[j]]) return sorted(convex_set) def convex_hull_recursive(points: list[Point]) -> list[Point]: points = sorted(_validate_input(points)) n = len(points) left_most_point = points[0] right_most_point = points[n - 1] convex_set = {left_most_point, right_most_point} upper_hull = [] lower_hull = [] for i in range(1, n - 1): det = _det(left_most_point, right_most_point, points[i]) if det > 0: upper_hull.append(points[i]) elif det < 0: lower_hull.append(points[i]) _construct_hull(upper_hull, left_most_point, right_most_point, convex_set) _construct_hull(lower_hull, right_most_point, left_most_point, convex_set) return sorted(convex_set) def _construct_hull( points: list[Point], left: Point, right: Point, convex_set: set[Point] ) -> None: if points: extreme_point = None extreme_point_distance = float("-inf") candidate_points = [] for p in points: det = _det(left, right, p) if det > 0: candidate_points.append(p) if det > extreme_point_distance: extreme_point_distance = det extreme_point = p if extreme_point: _construct_hull(candidate_points, left, extreme_point, convex_set) convex_set.add(extreme_point) _construct_hull(candidate_points, extreme_point, right, convex_set) def convex_hull_melkman(points: list[Point]) -> list[Point]: points = sorted(_validate_input(points)) n = len(points) convex_hull = points[:2] for i in range(2, n): det = _det(convex_hull[1], convex_hull[0], points[i]) if det > 0: convex_hull.insert(0, points[i]) break elif det < 0: convex_hull.append(points[i]) break else: convex_hull[1] = points[i] i += 1 for j in range(i, n): if ( _det(convex_hull[0], convex_hull[-1], points[j]) > 0 and _det(convex_hull[-1], convex_hull[0], points[1]) < 0 ): continue convex_hull.insert(0, points[j]) convex_hull.append(points[j]) while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0: del convex_hull[1] while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0: del convex_hull[-2] return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull) def main(): points = [ (0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), (2, -1), (2, -4), (1, -3), ] results_bf = convex_hull_bf(points) results_recursive = convex_hull_recursive(points) assert results_bf == results_recursive results_melkman = convex_hull_melkman(points) assert results_bf == results_melkman print(results_bf) if __name__ == "__main__": main()
heap s algorithm returns the list of all permutations possible from a list it minimizes movement by generating each permutation from the previous one by swapping only two elements more information https en wikipedia orgwikiheap27salgorithm pure python implementation of the heap s algorithm recursive version returning all permutations of a list heaps heaps0 0 heaps1 1 1 1 1 1 heaps1 2 3 1 2 3 2 1 3 3 1 2 1 3 2 2 3 1 3 2 1 from itertools import permutations sortedheaps1 2 3 sortedpermutations1 2 3 true allsortedheapsx sortedpermutationsx for x in 0 1 1 1 2 3 true pure python implementation of the heap s algorithm recursive version returning all permutations of a list heaps heaps 0 0 heaps 1 1 1 1 1 1 heaps 1 2 3 1 2 3 2 1 3 3 1 2 1 3 2 2 3 1 3 2 1 from itertools import permutations sorted heaps 1 2 3 sorted permutations 1 2 3 true all sorted heaps x sorted permutations x for x in 0 1 1 1 2 3 true k is even k is odd
def heaps(arr: list) -> list: if len(arr) <= 1: return [tuple(arr)] res = [] def generate(k: int, arr: list): if k == 1: res.append(tuple(arr[:])) return generate(k - 1, arr) for i in range(k - 1): if k % 2 == 0: arr[i], arr[k - 1] = arr[k - 1], arr[i] else: arr[0], arr[k - 1] = arr[k - 1], arr[0] generate(k - 1, arr) generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
heap s iterative algorithm returns the list of all permutations possible from a list it minimizes movement by generating each permutation from the previous one by swapping only two elements more information https en wikipedia orgwikiheap27salgorithm pure python implementation of the iterative heap s algorithm returning all permutations of a list heaps heaps0 0 heaps1 1 1 1 1 1 heaps1 2 3 1 2 3 2 1 3 3 1 2 1 3 2 2 3 1 3 2 1 from itertools import permutations sortedheaps1 2 3 sortedpermutations1 2 3 true allsortedheapsx sortedpermutationsx for x in 0 1 1 1 2 3 true pure python implementation of the iterative heap s algorithm returning all permutations of a list heaps heaps 0 0 heaps 1 1 1 1 1 1 heaps 1 2 3 1 2 3 2 1 3 3 1 2 1 3 2 2 3 1 3 2 1 from itertools import permutations sorted heaps 1 2 3 sorted permutations 1 2 3 true all sorted heaps x sorted permutations x for x in 0 1 1 1 2 3 true
def heaps(arr: list) -> list: if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
given an arraylike data structure a1 n how many pairs i j for all 1 i j n such that ai aj these pairs are called inversions counting the number of such inversions in an arraylike object is the important among other things counting inversions can help us determine how close a given array is to being sorted in this implementation i provide two algorithms a divideandconquer algorithm which runs in nlogn and the bruteforce n2 algorithm counts the number of inversions using a naive bruteforce algorithm parameters arr arr arraylike the list containing the items for which the number of inversions is desired the elements of arr must be comparable returns numinversions the total number of inversions in arr examples countinversionsbf1 4 2 4 1 4 countinversionsbf1 1 2 4 4 0 countinversionsbf 0 counts the number of inversions using a divideandconquer algorithm parameters arr arraylike the list containing the items for which the number of inversions is desired the elements of arr must be comparable returns c a sorted copy of arr numinversions int the total number of inversions in arr examples countinversionsrecursive1 4 2 4 1 1 1 2 4 4 4 countinversionsrecursive1 1 2 4 4 1 1 2 4 4 0 countinversionsrecursive 0 counts the inversions across two sorted arrays and combine the two arrays into one sorted array for all 1 ilenp and for all 1 j lenq if pi qj then i j is a cross inversion parameters p arraylike sorted in nondecreasing order q arraylike sorted in nondecreasing order returns r arraylike a sorted array of the elements of p and q numinversion int the number of inversions across p and q examples countcrossinversions1 2 3 0 2 5 0 1 2 2 3 5 4 countcrossinversions1 2 3 3 4 5 1 2 3 3 4 5 0 if p1 qj then pk qk for all i k lenp these are all inversions the claim emerges from the property that p is sorted this arr has 8 inversions 10 2 10 1 10 5 10 5 10 2 2 1 5 2 5 2 testing an array with zero inversion a sorted arr1 an empty list should also have zero inversions counts the number of inversions using a naive brute force algorithm parameters arr arr array like the list containing the items for which the number of inversions is desired the elements of arr must be comparable returns num_inversions the total number of inversions in arr examples count_inversions_bf 1 4 2 4 1 4 count_inversions_bf 1 1 2 4 4 0 count_inversions_bf 0 counts the number of inversions using a divide and conquer algorithm parameters arr array like the list containing the items for which the number of inversions is desired the elements of arr must be comparable returns c a sorted copy of arr num_inversions int the total number of inversions in arr examples count_inversions_recursive 1 4 2 4 1 1 1 2 4 4 4 count_inversions_recursive 1 1 2 4 4 1 1 2 4 4 0 count_inversions_recursive 0 counts the inversions across two sorted arrays and combine the two arrays into one sorted array for all 1 i len p and for all 1 j len q if p i q j then i j is a cross inversion parameters p array like sorted in non decreasing order q array like sorted in non decreasing order returns r array like a sorted array of the elements of p and q num_inversion int the number of inversions across p and q examples _count_cross_inversions 1 2 3 0 2 5 0 1 2 2 3 5 4 _count_cross_inversions 1 2 3 3 4 5 1 2 3 3 4 5 0 if p 1 q j then p k q k for all i k len p these are all inversions the claim emerges from the property that p is sorted this arr has 8 inversions 10 2 10 1 10 5 10 5 10 2 2 1 5 2 5 2 testing an array with zero inversion a sorted arr_1 an empty list should also have zero inversions
def count_inversions_bf(arr): num_inversions = 0 n = len(arr) for i in range(n - 1): for j in range(i + 1, n): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def count_inversions_recursive(arr): if len(arr) <= 1: return arr, 0 mid = len(arr) // 2 p = arr[0:mid] q = arr[mid:] a, inversion_p = count_inversions_recursive(p) b, inversions_q = count_inversions_recursive(q) c, cross_inversions = _count_cross_inversions(a, b) num_inversions = inversion_p + inversions_q + cross_inversions return c, num_inversions def _count_cross_inversions(p, q): r = [] i = j = num_inversion = 0 while i < len(p) and j < len(q): if p[i] > q[j]: num_inversion += len(p) - i r.append(q[j]) j += 1 else: r.append(p[i]) i += 1 if i < len(p): r.extend(p[i:]) else: r.extend(q[j:]) return r, num_inversion def main(): arr_1 = [10, 2, 1, 5, 5, 2, 11] num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 8 print("number of inversions = ", num_inversions_bf) arr_1.sort() num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = ", num_inversions_bf) arr_1 = [] num_inversions_bf = count_inversions_bf(arr_1) _, num_inversions_recursive = count_inversions_recursive(arr_1) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = ", num_inversions_bf) if __name__ == "__main__": main()
find the kth smallest element in linear time using divide and conquer recall we can do this trivially in onlogn time sort the list and access kth element in constant time this is a divide and conquer algorithm that can find a solution in on time for more information of this algorithm https web stanford educlassarchivecscs161cs161 1138lectures08small08 pdf choose a random pivot for the list we can use a more sophisticated algorithm here such as the medianofmedians algorithm return the kth smallest number in lst kthnumber2 1 3 4 5 3 3 kthnumber2 1 3 4 5 1 1 kthnumber2 1 3 4 5 5 5 kthnumber3 2 5 6 7 8 2 3 kthnumber25 21 98 100 76 22 43 60 89 87 4 43 pick a pivot and separate into list based on pivot partition based on pivot linear time if we get lucky pivot might be the element we want we can easily see this small elements smaller than k pivot kth element big elements larger than k pivot is in elements bigger than k pivot is in elements smaller than k choose a random pivot for the list we can use a more sophisticated algorithm here such as the median of medians algorithm return the kth smallest number in lst kth_number 2 1 3 4 5 3 3 kth_number 2 1 3 4 5 1 1 kth_number 2 1 3 4 5 5 5 kth_number 3 2 5 6 7 8 2 3 kth_number 25 21 98 100 76 22 43 60 89 87 4 43 pick a pivot and separate into list based on pivot partition based on pivot linear time if we get lucky pivot might be the element we want we can easily see this small elements smaller than k pivot kth element big elements larger than k pivot is in elements bigger than k pivot is in elements smaller than k
from __future__ import annotations from random import choice def random_pivot(lst): return choice(lst) def kth_number(lst: list[int], k: int) -> int: pivot = random_pivot(lst) small = [e for e in lst if e < pivot] big = [e for e in lst if e > pivot] if len(small) == k - 1: return pivot elif len(small) < k - 1: return kth_number(big, k - len(small) - 1) else: return kth_number(small, k) if __name__ == "__main__": import doctest doctest.testmod()
we are given an array a1 n of integers n 1 we want to find a pair of indices i j such that 1 i j n and aj ai is as large as possible explanation https www geeksforgeeks orgmaximumdifferencebetweentwoelements maxdifference5 11 2 1 7 9 0 7 1 9 base case split a into half 2 sub problems 12 of original size get min of first and max of second linear time 3 cases either small1 big1 minfirst maxsecond small2 big2 constant comparisons we are given an array a 1 n of integers n 1 we want to find a pair of indices i j such that 1 i j n and a j a i is as large as possible explanation https www geeksforgeeks org maximum difference between two elements max_difference 5 11 2 1 7 9 0 7 1 9 base case split a into half 2 sub problems 1 2 of original size get min of first and max of second linear time 3 cases either small1 big1 min_first max_second small2 big2 constant comparisons
def max_difference(a: list[int]) -> tuple[int, int]: if len(a) == 1: return a[0], a[0] else: first = a[: len(a) // 2] second = a[len(a) // 2 :] small1, big1 = max_difference(first) small2, big2 = max_difference(second) min_first = min(first) max_second = max(second) if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1: return small2, big2 elif big1 - small1 > max_second - min_first: return small1, big1 else: return min_first, max_second if __name__ == "__main__": import doctest doctest.testmod()
the maximum subarray problem is the task of finding the continuous subarray that has the maximum sum within a given array of numbers for example given the array 2 1 3 4 1 2 1 5 4 the contiguous subarray with the maximum sum is 4 1 2 1 which has a sum of 6 this divideandconquer algorithm finds the maximum subarray in on log n time solves the maximum subarray problem using divide and conquer param arr the given array of numbers param low the start index param high the end index return the start index of the maximum subarray the end index of the maximum subarray and the maximum subarray sum nums 2 1 3 4 1 2 1 5 4 maxsubarraynums 0 lennums 1 3 6 6 nums 2 8 9 maxsubarraynums 0 lennums 1 0 2 19 nums 0 0 maxsubarraynums 0 lennums 1 0 0 0 nums 1 0 0 0 1 0 maxsubarraynums 0 lennums 1 2 2 1 0 nums 2 3 1 4 6 maxsubarraynums 0 lennums 1 2 2 1 maxsubarray 0 0 none none 0 a random simulation of this algorithm solves the maximum subarray problem using divide and conquer param arr the given array of numbers param low the start index param high the end index return the start index of the maximum subarray the end index of the maximum subarray and the maximum subarray sum nums 2 1 3 4 1 2 1 5 4 max_subarray nums 0 len nums 1 3 6 6 nums 2 8 9 max_subarray nums 0 len nums 1 0 2 19 nums 0 0 max_subarray nums 0 len nums 1 0 0 0 nums 1 0 0 0 1 0 max_subarray nums 0 len nums 1 2 2 1 0 nums 2 3 1 4 6 max_subarray nums 0 len nums 1 2 2 1 max_subarray 0 0 none none 0 a random simulation of this algorithm
from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def max_subarray( arr: Sequence[float], low: int, high: int ) -> tuple[int | None, int | None, float]: if not arr: return None, None, 0 if low == high: return low, high, arr[low] mid = (low + high) // 2 left_low, left_high, left_sum = max_subarray(arr, low, mid) right_low, right_high, right_sum = max_subarray(arr, mid + 1, high) cross_left, cross_right, cross_sum = max_cross_sum(arr, low, mid, high) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def max_cross_sum( arr: Sequence[float], low: int, mid: int, high: int ) -> tuple[int, int, float]: left_sum, max_left = float("-inf"), -1 right_sum, max_right = float("-inf"), -1 summ: int | float = 0 for i in range(mid, low - 1, -1): summ += arr[i] if summ > left_sum: left_sum = summ max_left = i summ = 0 for i in range(mid + 1, high + 1): summ += arr[i] if summ > right_sum: right_sum = summ max_right = i return max_left, max_right, (left_sum + right_sum) def time_max_subarray(input_size: int) -> float: arr = [randint(1, input_size) for _ in range(input_size)] start = time.time() max_subarray(arr, 0, input_size - 1) end = time.time() return end - start def plot_runtimes() -> None: input_sizes = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000] runtimes = [time_max_subarray(input_size) for input_size in input_sizes] print("No of Inputs\t\tTime Taken") for input_size, runtime in zip(input_sizes, runtimes): print(input_size, "\t\t", runtime) plt.plot(input_sizes, runtimes) plt.xlabel("Number of Inputs") plt.ylabel("Time taken in seconds") plt.show() if __name__ == "__main__": from doctest import testmod testmod()
helper function for mergesort lefthalf 2 righthalf 1 mergelefthalf righthalf 2 1 lefthalf 1 2 3 righthalf 4 5 6 mergelefthalf righthalf 1 2 3 4 5 6 lefthalf 2 righthalf 1 mergelefthalf righthalf 2 1 lefthalf 12 15 righthalf 13 14 mergelefthalf righthalf 12 13 14 15 lefthalf righthalf mergelefthalf righthalf returns a list of sorted array elements using merge sort from random import shuffle array 2 3 10 11 99 100000 100 200 shufflearray mergesortarray 200 10 2 3 11 99 100 100000 shufflearray mergesortarray 200 10 2 3 11 99 100 100000 array 200 mergesortarray 200 array 2 3 10 11 99 100000 100 200 shufflearray sortedarray mergesortarray true array 2 mergesortarray 2 array mergesortarray array 10000000 1 1111111111 101111111112 9000002 sortedarray mergesortarray true the actual formula to calculate the middle element left right left 2 this avoids integer overflow in case of large n split the array into halves till the array length becomes equal to one merge the arrays of single length returned by mergesort function and pass them into the merge arrays function which merges the array helper function for mergesort left_half 2 right_half 1 merge left_half right_half 2 1 left_half 1 2 3 right_half 4 5 6 merge left_half right_half 1 2 3 4 5 6 left_half 2 right_half 1 merge left_half right_half 2 1 left_half 12 15 right_half 13 14 merge left_half right_half 12 13 14 15 left_half right_half merge left_half right_half pointer to current index for left half pointer to current index for the right half pointer to current index for the sorted array half returns a list of sorted array elements using merge sort from random import shuffle array 2 3 10 11 99 100000 100 200 shuffle array merge_sort array 200 10 2 3 11 99 100 100000 shuffle array merge_sort array 200 10 2 3 11 99 100 100000 array 200 merge_sort array 200 array 2 3 10 11 99 100000 100 200 shuffle array sorted array merge_sort array true array 2 merge_sort array 2 array merge_sort array array 10000000 1 1111111111 101111111112 9000002 sorted array merge_sort array true the actual formula to calculate the middle element left right left 2 this avoids integer overflow in case of large n split the array into halves till the array length becomes equal to one merge the arrays of single length returned by mergesort function and pass them into the merge arrays function which merges the array
from __future__ import annotations def merge(left_half: list, right_half: list) -> list: sorted_array = [None] * (len(right_half) + len(left_half)) pointer1 = 0 pointer2 = 0 index = 0 while pointer1 < len(left_half) and pointer2 < len(right_half): if left_half[pointer1] < right_half[pointer2]: sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 else: sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 while pointer1 < len(left_half): sorted_array[index] = left_half[pointer1] pointer1 += 1 index += 1 while pointer2 < len(right_half): sorted_array[index] = right_half[pointer2] pointer2 += 1 index += 1 return sorted_array def merge_sort(array: list) -> list: if len(array) <= 1: return array middle = 0 + (len(array) - 0) // 2 left_half = array[:middle] right_half = array[middle:] return merge(merge_sort(left_half), merge_sort(right_half)) if __name__ == "__main__": import doctest doctest.testmod()
finding the peak of a unimodal list using divide and conquer a unimodal array is defined as follows array is increasing up to index p then decreasing afterwards for p 1 an obvious solution can be performed in on to find the maximum of the array from kleinberg and tardos algorithm design addison wesley 2006 chapter 5 solved exercise 1 return the peak value of lst peak1 2 3 4 5 4 3 2 1 5 peak1 10 9 8 7 6 5 4 10 peak1 9 8 7 9 peak1 2 3 4 5 6 7 0 7 peak1 2 3 4 3 2 1 0 1 2 4 middle index choose the middle 3 elements if middle element is peak if increasing recurse on right decreasing return the peak value of lst peak 1 2 3 4 5 4 3 2 1 5 peak 1 10 9 8 7 6 5 4 10 peak 1 9 8 7 9 peak 1 2 3 4 5 6 7 0 7 peak 1 2 3 4 3 2 1 0 1 2 4 middle index choose the middle 3 elements if middle element is peak if increasing recurse on right decreasing
from __future__ import annotations def peak(lst: list[int]) -> int: m = len(lst) // 2 three = lst[m - 1 : m + 2] if three[1] > three[0] and three[1] > three[2]: return three[1] elif three[0] < three[2]: if len(lst[:m]) == 2: m -= 1 return peak(lst[m:]) else: if len(lst[:m]) == 2: m += 1 return peak(lst[:m]) if __name__ == "__main__": import doctest doctest.testmod()
function using divide and conquer to calculate ab it only works for integer a b power4 6 4096 power2 3 8 power2 3 8 power2 3 0 125 power2 3 0 125 function using divide and conquer to calculate a b it only works for integer a b power 4 6 4096 power 2 3 8 power 2 3 8 power 2 3 0 125 power 2 3 0 125
def actual_power(a: int, b: int): if b == 0: return 1 if (b % 2) == 0: return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) else: return a * actual_power(a, int(b / 2)) * actual_power(a, int(b / 2)) def power(a: int, b: int) -> float: if b < 0: return 1 / actual_power(a, b) return actual_power(a, b) if __name__ == "__main__": print(power(-2, -3))
multiplication only for 2x2 matrices given an even length matrix returns the topleft topright botleft botright quadrant splitmatrix4 3 2 4 2 3 1 1 6 5 4 3 8 4 1 6 4 3 2 3 2 4 1 1 6 5 8 4 4 3 1 6 splitmatrix 4 3 2 4 4 3 2 4 2 3 1 1 2 3 1 1 6 5 4 3 6 5 4 3 8 4 1 6 8 4 1 6 4 3 2 4 4 3 2 4 2 3 1 1 2 3 1 1 6 5 4 3 6 5 4 3 8 4 1 6 8 4 1 6 doctest normalizewhitespace 4 3 2 4 2 3 1 1 6 5 4 3 8 4 1 6 4 3 2 4 2 3 1 1 6 5 4 3 8 4 1 6 4 3 2 4 2 3 1 1 6 5 4 3 8 4 1 6 4 3 2 4 2 3 1 1 6 5 4 3 8 4 1 6 recursive function to calculate the product of two matrices using the strassen algorithm it only supports square matrices of any size that is a power of 2 construct the new matrix from our 4 quadrants strassen2 1 3 3 4 6 1 4 2 7 6 7 4 2 3 4 2 1 1 1 8 6 4 2 34 23 19 15 68 46 37 28 28 18 15 12 96 62 55 48 strassen3 7 5 6 9 1 5 3 7 8 1 4 4 5 7 2 4 5 2 1 7 5 5 7 8 139 163 121 134 100 121 adding zeros to the matrices to convert them both into square matrices of equal dimensions that are a power of 2 removing the additional zeros multiplication only for 2x2 matrices given an even length matrix returns the top_left top_right bot_left bot_right quadrant split_matrix 4 3 2 4 2 3 1 1 6 5 4 3 8 4 1 6 4 3 2 3 2 4 1 1 6 5 8 4 4 3 1 6 split_matrix 4 3 2 4 4 3 2 4 2 3 1 1 2 3 1 1 6 5 4 3 6 5 4 3 8 4 1 6 8 4 1 6 4 3 2 4 4 3 2 4 2 3 1 1 2 3 1 1 6 5 4 3 6 5 4 3 8 4 1 6 8 4 1 6 doctest normalize_whitespace 4 3 2 4 2 3 1 1 6 5 4 3 8 4 1 6 4 3 2 4 2 3 1 1 6 5 4 3 8 4 1 6 4 3 2 4 2 3 1 1 6 5 4 3 8 4 1 6 4 3 2 4 2 3 1 1 6 5 4 3 8 4 1 6 recursive function to calculate the product of two matrices using the strassen algorithm it only supports square matrices of any size that is a power of 2 construct the new matrix from our 4 quadrants strassen 2 1 3 3 4 6 1 4 2 7 6 7 4 2 3 4 2 1 1 1 8 6 4 2 34 23 19 15 68 46 37 28 28 18 15 12 96 62 55 48 strassen 3 7 5 6 9 1 5 3 7 8 1 4 4 5 7 2 4 5 2 1 7 5 5 7 8 139 163 121 134 100 121 adding zeros to the matrices to convert them both into square matrices of equal dimensions that are a power of 2 removing the additional zeros
from __future__ import annotations import math def default_matrix_multiplication(a: list, b: list) -> list: if len(a) != 2 or len(a[0]) != 2 or len(b) != 2 or len(b[0]) != 2: raise Exception("Matrices are not 2x2") new_matrix = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def matrix_addition(matrix_a: list, matrix_b: list): return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row]))] for row in range(len(matrix_a)) ] def matrix_subtraction(matrix_a: list, matrix_b: list): return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row]))] for row in range(len(matrix_a)) ] def split_matrix(a: list) -> tuple[list, list, list, list]: if len(a) % 2 != 0 or len(a[0]) % 2 != 0: raise Exception("Odd matrices are not supported!") matrix_length = len(a) mid = matrix_length // 2 top_right = [[a[i][j] for j in range(mid, matrix_length)] for i in range(mid)] bot_right = [ [a[i][j] for j in range(mid, matrix_length)] for i in range(mid, matrix_length) ] top_left = [[a[i][j] for j in range(mid)] for i in range(mid)] bot_left = [[a[i][j] for j in range(mid)] for i in range(mid, matrix_length)] return top_left, top_right, bot_left, bot_right def matrix_dimensions(matrix: list) -> tuple[int, int]: return len(matrix), len(matrix[0]) def print_matrix(matrix: list) -> None: print("\n".join(str(line) for line in matrix)) def actual_strassen(matrix_a: list, matrix_b: list) -> list: if matrix_dimensions(matrix_a) == (2, 2): return default_matrix_multiplication(matrix_a, matrix_b) a, b, c, d = split_matrix(matrix_a) e, f, g, h = split_matrix(matrix_b) t1 = actual_strassen(a, matrix_subtraction(f, h)) t2 = actual_strassen(matrix_addition(a, b), h) t3 = actual_strassen(matrix_addition(c, d), e) t4 = actual_strassen(d, matrix_subtraction(g, e)) t5 = actual_strassen(matrix_addition(a, d), matrix_addition(e, h)) t6 = actual_strassen(matrix_subtraction(b, d), matrix_addition(g, h)) t7 = actual_strassen(matrix_subtraction(a, c), matrix_addition(e, f)) top_left = matrix_addition(matrix_subtraction(matrix_addition(t5, t4), t2), t6) top_right = matrix_addition(t1, t2) bot_left = matrix_addition(t3, t4) bot_right = matrix_subtraction(matrix_subtraction(matrix_addition(t1, t5), t3), t7) new_matrix = [] for i in range(len(top_right)): new_matrix.append(top_left[i] + top_right[i]) for i in range(len(bot_right)): new_matrix.append(bot_left[i] + bot_right[i]) return new_matrix def strassen(matrix1: list, matrix2: list) -> list: if matrix_dimensions(matrix1)[1] != matrix_dimensions(matrix2)[0]: msg = ( "Unable to multiply these matrices, please check the dimensions.\n" f"Matrix A: {matrix1}\n" f"Matrix B: {matrix2}" ) raise Exception(msg) dimension1 = matrix_dimensions(matrix1) dimension2 = matrix_dimensions(matrix2) if dimension1[0] == dimension1[1] and dimension2[0] == dimension2[1]: return [matrix1, matrix2] maximum = max(*dimension1, *dimension2) maxim = int(math.pow(2, math.ceil(math.log2(maximum)))) new_matrix1 = matrix1 new_matrix2 = matrix2 for i in range(maxim): if i < dimension1[0]: for _ in range(dimension1[1], maxim): new_matrix1[i].append(0) else: new_matrix1.append([0] * maxim) if i < dimension2[0]: for _ in range(dimension2[1], maxim): new_matrix2[i].append(0) else: new_matrix2.append([0] * maxim) final_matrix = actual_strassen(new_matrix1, new_matrix2) for i in range(maxim): if i < dimension1[0]: for _ in range(dimension2[1], maxim): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": matrix1 = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] matrix2 = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrix1, matrix2))
https www hackerrank comchallengesabbrproblem you can perform the following operation on some string 1 capitalize zero or more of s lowercase letters at some index i i e make them uppercase 2 delete all of the remaining lowercase letters in example adabcd and babc dabcd capitalize a and cdabcd remove d abc abbrdabcd abc true abbrdbcd abc false abbr dabcd abc true abbr dbcd abc false
def abbr(a: str, b: str) -> bool: n = len(a) m = len(b) dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] dp[0][0] = True for i in range(n): for j in range(m + 1): if dp[i][j]: if j < m and a[i].upper() == b[j]: dp[i + 1][j + 1] = True if a[i].islower(): dp[i + 1][j] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
program to list all the ways a target string can be constructed from the given list of substrings returns the list containing all the possible combinations a stringtarget can be constructed from the given list of substringswordbank allconstructhello he l o he l l o allconstructpurple purp p ur le purpl purp le p ur p le create a table seed value iterate through the indices condition slice condition adds the word to every combination the current position holds now push that combination to the tableilenword combinations are in reverse order so reverse for better output returns the list containing all the possible combinations a string target can be constructed from the given list of substrings word_bank all_construct hello he l o he l l o all_construct purple purp p ur le purpl purp le p ur p le create a table seed value because empty string has empty combination iterate through the indices condition slice condition adds the word to every combination the current position holds now push that combination to the table i len word combinations are in reverse order so reverse for better output
from __future__ import annotations def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]: word_bank = word_bank or [] table_size: int = len(target) + 1 table: list[list[list[str]]] = [] for _ in range(table_size): table.append([]) table[0] = [[]] for i in range(table_size): if table[i] != []: for word in word_bank: if target[i : i + len(word)] == word: new_combinations: list[list[str]] = [ [word, *way] for way in table[i] ] table[i + len(word)] += new_combinations for combination in table[len(target)]: combination.reverse() return table[len(target)] if __name__ == "__main__": print(all_construct("jwajalapa", ["jwa", "j", "w", "a", "la", "lapa"])) print(all_construct("rajamati", ["s", "raj", "amat", "raja", "ma", "i", "t"])) print( all_construct( "hexagonosaurus", ["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "s"], ) )
this is a python implementation for questions involving task assignments between people here bitmasking and dp are used for solving this question we have n tasks and m people each person in m can do only certain of these tasks also a person can do only one task and a task is performed only by one person find the total no of ways in which the tasks can be distributed dp table will have a dimension of 2mn initially all values are set to 1 finalmask is used to check if all persons are included by setting all bits to 1 if mask self finalmask all persons are distributed tasks return 1 if not everyone gets the task and no more tasks are available return 0 if case already considered number of ways when we don t this task in the arrangement now assign the tasks one by one to all possible persons and recursively assign for the remaining tasks if p is already given a task assign this task to p and change the mask value and recursively assign tasks with the new mask value save the value store the list of persons for each task call the function to fill the dp table final answer is stored in dp01 the list of tasks that can be done by m persons for the particular example the tasks can be distributed as 1 2 3 1 2 4 1 5 3 1 5 4 3 1 4 3 2 4 3 5 4 4 1 3 4 2 3 4 5 3 total 10 total no of tasks n dp table will have a dimension of 2 m n initially all values are set to 1 stores the list of persons for each task final_mask is used to check if all persons are included by setting all bits to 1 if mask self finalmask all persons are distributed tasks return 1 if not everyone gets the task and no more tasks are available return 0 if case already considered number of ways when we don t this task in the arrangement now assign the tasks one by one to all possible persons and recursively assign for the remaining tasks if p is already given a task assign this task to p and change the mask value and recursively assign tasks with the new mask value save the value store the list of persons for each task call the function to fill the dp table final answer is stored in dp 0 1 total no of tasks the value of n the list of tasks that can be done by m persons for the particular example the tasks can be distributed as 1 2 3 1 2 4 1 5 3 1 5 4 3 1 4 3 2 4 3 5 4 4 1 3 4 2 3 4 5 3 total 10
from collections import defaultdict class AssignmentUsingBitmask: def __init__(self, task_performed, total): self.total_tasks = total self.dp = [ [-1 for i in range(total + 1)] for j in range(2 ** len(task_performed)) ] self.task = defaultdict(list) self.final_mask = (1 << len(task_performed)) - 1 def count_ways_until(self, mask, task_no): if mask == self.final_mask: return 1 if task_no > self.total_tasks: return 0 if self.dp[mask][task_no] != -1: return self.dp[mask][task_no] total_ways_util = self.count_ways_until(mask, task_no + 1) if task_no in self.task: for p in self.task[task_no]: if mask & (1 << p): continue total_ways_util += self.count_ways_until(mask | (1 << p), task_no + 1) self.dp[mask][task_no] = total_ways_util return self.dp[mask][task_no] def count_no_of_ways(self, task_performed): for i in range(len(task_performed)): for j in task_performed[i]: self.task[j].append(i) return self.count_ways_until(0, 1) if __name__ == "__main__": total_tasks = 5 task_performed = [[1, 3, 4], [1, 2, 5], [3, 4]] print( AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways( task_performed ) )
print all the catalan numbers from 0 to n n being the user input the catalan numbers are a sequence of positive integers that appear in many counting problems in combinatorics 1 such problems include counting 2 the number of dyck words of length 2n the number wellformed expressions with n pairs of parentheses e g is valid but is not the number of different ways n 1 factors can be completely parenthesized e g for n 2 cn 2 and abc and abc are the two valid ways to parenthesize the number of full binary trees with n 1 leaves a catalan number satisfies the following recurrence relation which we will use in this algorithm 1 c0 c1 1 cn sumci cni1 from i 0 to n1 in addition the nth catalan number can be calculated using the closed form formula below 1 cn 1 n 1 2n choose n sources 1 https brilliant orgwikicatalannumbers 2 https en wikipedia orgwikicatalannumber return a list of the catalan number sequence from 0 through upperlimit catalannumbers5 1 1 2 5 14 42 catalannumbers2 1 1 2 catalannumbers1 traceback most recent call last valueerror limit for the catalan sequence must be 0 base case c0 c1 1 recurrence relation ci sumcj cij1 from j 0 to i return a list of the catalan number sequence from 0 through upper_limit catalan_numbers 5 1 1 2 5 14 42 catalan_numbers 2 1 1 2 catalan_numbers 1 traceback most recent call last valueerror limit for the catalan sequence must be 0 base case c 0 c 1 1 recurrence relation c i sum c j c i j 1 from j 0 to i
def catalan_numbers(upper_limit: int) -> "list[int]": if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0") catalan_list = [0] * (upper_limit + 1) catalan_list[0] = 1 if upper_limit > 0: catalan_list[1] = 1 for i in range(2, upper_limit + 1): for j in range(i): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("\n********* Catalan Numbers Using Dynamic Programming ************\n") print("\n*** Enter -1 at any time to quit ***") print("\nEnter the upper limit (≥ 0) for the Catalan number sequence: ", end="") try: while True: N = int(input().strip()) if N < 0: print("\n********* Goodbye!! ************") break else: print(f"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print("Try another upper limit for the sequence: ", end="") except (NameError, ValueError): print("\n********* Invalid input, goodbye! ************\n") import doctest doctest.testmod()
usrbinenv python3 leetcdoe no 70 climbing stairs distinct ways to climb a numberofsteps staircase where each time you can either climb 1 or 2 steps args numberofsteps number of steps on the staircase returns distinct ways to climb a numberofsteps staircase raises assertionerror numberofsteps not positive integer climbstairs3 3 climbstairs1 1 climbstairs7 doctest ellipsis traceback most recent call last assertionerror numberofsteps needs to be positive integer your input 7 usr bin env python3 leetcdoe no 70 climbing stairs distinct ways to climb a number_of_steps staircase where each time you can either climb 1 or 2 steps args number_of_steps number of steps on the staircase returns distinct ways to climb a number_of_steps staircase raises assertionerror number_of_steps not positive integer climb_stairs 3 3 climb_stairs 1 1 climb_stairs 7 doctest ellipsis traceback most recent call last assertionerror number_of_steps needs to be positive integer your input 7
def climb_stairs(number_of_steps: int) -> int: assert ( isinstance(number_of_steps, int) and number_of_steps > 0 ), f"number_of_steps needs to be positive integer, your input {number_of_steps}" if number_of_steps == 1: return 1 previous, current = 1, 1 for _ in range(number_of_steps - 1): current, previous = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
question you are given an array of distinct integers and you have to tell how many different ways of selecting the elements from the array are there such that the sum of chosen elements is equal to the target number tar example input n 3 target 5 array 1 2 5 output 9 approach the basic idea is to go over recursively to find the way such that the sum of chosen elements is tar for every element we have two choices 1 include the element in our set of chosen elements 2 dont include the element in our set of chosen elements function checks the all possible combinations and returns the count of possible combination in exponential time complexity combinationsumiv3 1 2 5 5 9 function checks the all possible combinations and returns the count of possible combination in on2 time complexity as we are using dynamic programming array here combinationsumivdparray3 1 2 5 5 9 function checks the all possible combinations with using bottom up approach and returns the count of possible combination in on2 time complexity as we are using dynamic programming array here combinationsumivbottomup3 1 2 5 5 9 function checks the all possible combinations and returns the count of possible combination in exponential time complexity combination_sum_iv 3 1 2 5 5 9 function checks the all possible combinations and returns the count of possible combination in o n 2 time complexity as we are using dynamic programming array here combination_sum_iv_dp_array 3 1 2 5 5 9 function checks the all possible combinations with using bottom up approach and returns the count of possible combination in o n 2 time complexity as we are using dynamic programming array here combination_sum_iv_bottom_up 3 1 2 5 5 9
def combination_sum_iv(n: int, array: list[int], target: int) -> int: def count_of_possible_combinations(target: int) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item) for item in array) return count_of_possible_combinations(target) def combination_sum_iv_dp_array(n: int, array: list[int], target: int) -> int: def count_of_possible_combinations_with_dp_array( target: int, dp_array: list[int] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] answer = sum( count_of_possible_combinations_with_dp_array(target - item, dp_array) for item in array ) dp_array[target] = answer return answer dp_array = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(target, dp_array) def combination_sum_iv_bottom_up(n: int, array: list[int], target: int) -> int: dp_array = [0] * (target + 1) dp_array[0] = 1 for i in range(1, target + 1): for j in range(n): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() n = 3 target = 5 array = [1, 2, 5] print(combination_sum_iv(n, array, target))
turfa auliarachman date october 12 2016 this is a pure python implementation of dynamic programming solution to the edit distance problem the problem is given two strings a and b find the minimum number of operations to string b such that a b the permitted operations are removal insertion and substitution use solver editdistance editdistanceresult solver solvefirststring secondstring editdistance mindisttopdownintention execution 5 editdistance mindisttopdownintention 9 editdistance mindisttopdown 0 editdistance mindistbottomupintention execution 5 editdistance mindistbottomupintention 9 editdistance mindistbottomup 0 use solver editdistance editdistanceresult solver solve firststring secondstring editdistance min_dist_top_down intention execution 5 editdistance min_dist_top_down intention 9 editdistance min_dist_top_down 0 editdistance min_dist_bottom_up intention execution 5 editdistance min_dist_bottom_up intention 9 editdistance min_dist_bottom_up 0 first string is empty second string is empty last characters are equal
class EditDistance: def __init__(self): self.word1 = "" self.word2 = "" self.dp = [] def __min_dist_top_down_dp(self, m: int, n: int) -> int: if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.word1[m] == self.word2[n]: self.dp[m][n] = self.__min_dist_top_down_dp(m - 1, n - 1) else: insert = self.__min_dist_top_down_dp(m, n - 1) delete = self.__min_dist_top_down_dp(m - 1, n) replace = self.__min_dist_top_down_dp(m - 1, n - 1) self.dp[m][n] = 1 + min(insert, delete, replace) return self.dp[m][n] def min_dist_top_down(self, word1: str, word2: str) -> int: self.word1 = word1 self.word2 = word2 self.dp = [[-1 for _ in range(len(word2))] for _ in range(len(word1))] return self.__min_dist_top_down_dp(len(word1) - 1, len(word2) - 1) def min_dist_bottom_up(self, word1: str, word2: str) -> int: self.word1 = word1 self.word2 = word2 m = len(word1) n = len(word2) self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0: self.dp[i][j] = j elif j == 0: self.dp[i][j] = i elif word1[i - 1] == word2[j - 1]: self.dp[i][j] = self.dp[i - 1][j - 1] else: insert = self.dp[i][j - 1] delete = self.dp[i - 1][j] replace = self.dp[i - 1][j - 1] self.dp[i][j] = 1 + min(insert, delete, replace) return self.dp[m][n] if __name__ == "__main__": solver = EditDistance() print("****************** Testing Edit Distance DP Algorithm ******************") print() S1 = input("Enter the first string: ").strip() S2 = input("Enter the second string: ").strip() print() print(f"The minimum edit distance is: {solver.min_dist_top_down(S1, S2)}") print(f"The minimum edit distance is: {solver.min_dist_bottom_up(S1, S2)}") print() print("*************** End of Testing Edit Distance DP Algorithm ***************")
factorial of a number using memoization factorial7 5040 factorial1 traceback most recent call last valueerror number should not be negative factoriali for i in range10 1 1 2 6 24 120 720 5040 40320 362880 factorial of a number using memoization factorial 7 5040 factorial 1 traceback most recent call last valueerror number should not be negative factorial i for i in range 10 1 1 2 6 24 120 720 5040 40320 362880
from functools import lru_cache @lru_cache def factorial(num: int) -> int: if num < 0: raise ValueError("Number should not be negative.") return 1 if num in (0, 1) else num * factorial(num - 1) if __name__ == "__main__": import doctest doctest.testmod()
usrbinenv python3 this program calculates the nth fibonacci number in ologn it s possible to calculate f1000000 in less than a second return fn fibonaccii for i in range13 0 1 1 2 3 5 8 13 21 34 55 89 144 returns fn fn1 f2n fn2fn1 fn f2n1 fn12fn2 usr bin env python3 this program calculates the nth fibonacci number in o log n it s possible to calculate f 1_000_000 in less than a second return f n fibonacci i for i in range 13 0 1 1 2 3 5 8 13 21 34 55 89 144 returns f n f n 1 f 0 f 1 f 2n f n 2f n 1 f n f 2n 1 f n 1 2 f n 2
from __future__ import annotations import sys def fibonacci(n: int) -> int: if n < 0: raise ValueError("Negative arguments are not supported") return _fib(n)[0] def _fib(n: int) -> tuple[int, int]: if n == 0: return (0, 1) a, b = _fib(n // 2) c = a * (b * 2 - a) d = a * a + b * b return (d, c + d) if n % 2 else (c, d) if __name__ == "__main__": n = int(sys.argv[1]) print(f"fibonacci({n}) is {fibonacci(n)}")
this is a pure python implementation of dynamic programming solution to the fibonacci sequence problem get the fibonacci number of index if the number does not exist calculate all missing numbers leading up to the number of index fibonacci get10 0 1 1 2 3 5 8 13 21 34 fibonacci get5 0 1 1 2 3 get the fibonacci number of index if the number does not exist calculate all missing numbers leading up to the number of index fibonacci get 10 0 1 1 2 3 5 8 13 21 34 fibonacci get 5 0 1 1 2 3
class Fibonacci: def __init__(self) -> None: self.sequence = [0, 1] def get(self, index: int) -> list: if (difference := index - (len(self.sequence) - 2)) >= 1: for _ in range(difference): self.sequence.append(self.sequence[-1] + self.sequence[-2]) return self.sequence[:index] def main() -> None: print( "Fibonacci Series Using Dynamic Programming\n", "Enter the index of the Fibonacci number you want to calculate ", "in the prompt below. (To exit enter exit or Ctrl-C)\n", sep="", ) fibonacci = Fibonacci() while True: prompt: str = input(">> ") if prompt in {"exit", "quit"}: break try: index: int = int(prompt) except ValueError: print("Enter a number or 'exit'") continue print(fibonacci.get(index)) if __name__ == "__main__": main()
https en wikipedia orgwikifizzbuzzprogramming plays fizzbuzz prints fizz if number is a multiple of 3 prints buzz if its a multiple of 5 prints fizzbuzz if its a multiple of both 3 and 5 or 15 else prints the number itself fizzbuzz1 7 1 2 fizz 4 buzz fizz 7 fizzbuzz1 0 traceback most recent call last valueerror iterations must be done more than 0 times to play fizzbuzz fizzbuzz5 5 traceback most recent call last valueerror starting number must be and integer and be more than 0 fizzbuzz10 5 traceback most recent call last valueerror iterations must be done more than 0 times to play fizzbuzz fizzbuzz1 5 5 traceback most recent call last valueerror starting number must be and integer and be more than 0 fizzbuzz1 5 5 traceback most recent call last valueerror iterations must be defined as integers starting number must be and integer and be more than 0 if not iterations 1 raise valueerroriterations must be done more than 0 times to play fizzbuzz out while number iterations if number 3 0 out fizz if number 5 0 out buzz if 0 not in number 3 number 5 out strnumber printout number 1 out return out if name main import doctest doctest testmod https en wikipedia org wiki fizz_buzz programming plays fizzbuzz prints fizz if number is a multiple of 3 prints buzz if its a multiple of 5 prints fizzbuzz if its a multiple of both 3 and 5 or 15 else prints the number itself fizz_buzz 1 7 1 2 fizz 4 buzz fizz 7 fizz_buzz 1 0 traceback most recent call last valueerror iterations must be done more than 0 times to play fizzbuzz fizz_buzz 5 5 traceback most recent call last valueerror starting number must be and integer and be more than 0 fizz_buzz 10 5 traceback most recent call last valueerror iterations must be done more than 0 times to play fizzbuzz fizz_buzz 1 5 5 traceback most recent call last valueerror starting number must be and integer and be more than 0 fizz_buzz 1 5 5 traceback most recent call last valueerror iterations must be defined as integers starting number must be and integer and be more than 0 print out
def fizz_buzz(number: int, iterations: int) -> str: if not isinstance(iterations, int): raise ValueError("iterations must be defined as integers") if not isinstance(number, int) or not number >= 1: raise ValueError( ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz") out = "" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(number) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
the number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts plus the number of partitions into at least k1 parts subtracting 1 from each part of a partition of n into k parts gives a partition of nk into k parts these two facts together are used for this algorithm https en wikipedia orgwikipartitionnumbertheory https en wikipedia orgwikipartitionfunctionnumbertheory partition5 7 partition7 15 partition100 190569292 partition1000 24061467864032622473692149727991 partition7 traceback most recent call last indexerror list index out of range partition0 traceback most recent call last indexerror list assignment index out of range partition7 8 traceback most recent call last typeerror float object cannot be interpreted as an integer partition 5 7 partition 7 15 partition 100 190569292 partition 1_000 24061467864032622473692149727991 partition 7 traceback most recent call last indexerror list index out of range partition 0 traceback most recent call last indexerror list assignment index out of range partition 7 8 traceback most recent call last typeerror float object cannot be interpreted as an integer
def partition(m: int) -> int: memo: list[list[int]] = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 for n in range(m + 1): for k in range(1, m): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: n = int(input("Enter a number: ").strip()) print(partition(n)) except ValueError: print("Please enter a number.") else: try: n = int(sys.argv[1]) print(partition(n)) except ValueError: print("Please pass a number.")
syed faizan 3rd year student iiit pune github faizan2700 you are given a bitmask m and you want to efficiently iterate through all of its submasks the mask s is submask of m if only bits that were included in bitmask are set args mask number which shows mask always integer 0 zero does not have any submasks returns allsubmasks the list of submasks of mask mask s is called submask of mask m if only bits that were included in original mask are set raises assertionerror mask not positive integer listofsubmasks15 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 listofsubmasks13 13 12 9 8 5 4 1 listofsubmasks7 doctest ellipsis traceback most recent call last assertionerror mask needs to be positive integer your input 7 listofsubmasks0 doctest ellipsis traceback most recent call last assertionerror mask needs to be positive integer your input 0 first submask iterated will be mask itself then operation will be performed to get other submasks till we reach empty submask that is zero zero is not included in final submasks list args mask number which shows mask always integer 0 zero does not have any submasks returns all_submasks the list of submasks of mask mask s is called submask of mask m if only bits that were included in original mask are set raises assertionerror mask not positive integer list_of_submasks 15 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 list_of_submasks 13 13 12 9 8 5 4 1 list_of_submasks 7 doctest ellipsis traceback most recent call last assertionerror mask needs to be positive integer your input 7 list_of_submasks 0 doctest ellipsis traceback most recent call last assertionerror mask needs to be positive integer your input 0 first submask iterated will be mask itself then operation will be performed to get other submasks till we reach empty submask that is zero zero is not included in final submasks list
from __future__ import annotations def list_of_submasks(mask: int) -> list[int]: assert ( isinstance(mask, int) and mask > 0 ), f"mask needs to be positive integer, your input {mask}" all_submasks = [] submask = mask while submask: all_submasks.append(submask) submask = (submask - 1) & mask return all_submasks if __name__ == "__main__": import doctest doctest.testmod()
given weights and values of n items put these items in a knapsack of capacity w to get the maximum total value in the knapsack note that only the integer weights 01 knapsack problem is solvable using dynamic programming this code involves the concept of memory functions here we solve the subproblems which are needed unlike the below example f is a 2d array with 1s filled up solves the integer weights knapsack problem returns one of the several possible optimal subsets parameters w int the total maximum weight for the given knapsack problem wt list the vector of weights for all items where wti is the weight of the ith item val list the vector of values for all items where vali is the value of the ith item returns optimalval float the optimal value for the given knapsack problem exampleoptionalset set the indices of one of the optimal subsets which gave rise to the optimal value examples knapsackwithexamplesolution10 1 3 5 2 10 20 100 22 142 2 3 4 knapsackwithexamplesolution6 4 3 2 3 3 2 4 4 8 3 4 knapsackwithexamplesolution6 4 3 2 3 3 2 4 traceback most recent call last valueerror the number of weights must be the same as the number of values but got 4 weights and 3 values recursively reconstructs one of the optimal subsets given a filled dp table and the vector of weights parameters dp list of list the table of a solved integer weight dynamic programming problem wt list or tuple the vector of weights of the items i int the index of the item under consideration j int the current possible maximum weight optimalset set the optimal subset so far this gets modified by the function returns none for the current item i at a maximum weight j to be part of an optimal subset the optimal value at i j must be greater than the optimal value at i1 j where i 1 means considering only the previous items at the given maximum weight adding test case for knapsack testing the dynamic programming problem with example the optimal subset for the above example are items 3 and 4 this code involves the concept of memory functions here we solve the subproblems which are needed unlike the below example f is a 2d array with 1s filled up a global dp table for knapsack solves the integer weights knapsack problem returns one of the several possible optimal subsets parameters w int the total maximum weight for the given knapsack problem wt list the vector of weights for all items where wt i is the weight of the i th item val list the vector of values for all items where val i is the value of the i th item returns optimal_val float the optimal value for the given knapsack problem example_optional_set set the indices of one of the optimal subsets which gave rise to the optimal value examples knapsack_with_example_solution 10 1 3 5 2 10 20 100 22 142 2 3 4 knapsack_with_example_solution 6 4 3 2 3 3 2 4 4 8 3 4 knapsack_with_example_solution 6 4 3 2 3 3 2 4 traceback most recent call last valueerror the number of weights must be the same as the number of values but got 4 weights and 3 values recursively reconstructs one of the optimal subsets given a filled dp table and the vector of weights parameters dp list of list the table of a solved integer weight dynamic programming problem wt list or tuple the vector of weights of the items i int the index of the item under consideration j int the current possible maximum weight optimal_set set the optimal subset so far this gets modified by the function returns none for the current item i at a maximum weight j to be part of an optimal subset the optimal value at i j must be greater than the optimal value at i 1 j where i 1 means considering only the previous items at the given maximum weight adding test case for knapsack switched the n and w testing the dynamic programming problem with example the optimal subset for the above example are items 3 and 4
def mf_knapsack(i, wt, val, j): global f if f[i][j] < 0: if j < wt[i - 1]: val = mf_knapsack(i - 1, wt, val, j) else: val = max( mf_knapsack(i - 1, wt, val, j), mf_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1], ) f[i][j] = val return f[i][j] def knapsack(w, wt, val, n): dp = [[0] * (w + 1) for _ in range(n + 1)] for i in range(1, n + 1): for w_ in range(1, w + 1): if wt[i - 1] <= w_: dp[i][w_] = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]], dp[i - 1][w_]) else: dp[i][w_] = dp[i - 1][w_] return dp[n][w_], dp def knapsack_with_example_solution(w: int, wt: list, val: list): if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) num_items = len(wt) if num_items != len(val): msg = ( "The number of weights must be the same as the number of values.\n" f"But got {num_items} weights and {len(val)} values" ) raise ValueError(msg) for i in range(num_items): if not isinstance(wt[i], int): msg = ( "All weights must be integers but got weight of " f"type {type(wt[i])} at index {i}" ) raise TypeError(msg) optimal_val, dp_table = knapsack(w, wt, val, num_items) example_optional_set: set = set() _construct_solution(dp_table, wt, num_items, w, example_optional_set) return optimal_val, example_optional_set def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set): if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(dp, wt, i - 1, j, optimal_set) else: optimal_set.add(i) _construct_solution(dp, wt, i - 1, j - wt[i - 1], optimal_set) if __name__ == "__main__": val = [3, 2, 4, 4] wt = [4, 3, 2, 3] n = 4 w = 6 f = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] optimal_solution, _ = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) optimal_solution, optimal_subset = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("optimal_value = ", optimal_solution) print("An optimal subset corresponding to the optimal value", optimal_subset)
algorithm to find the biggest subset in the given array such that for any 2 elements x and y in the subset either x divides y or y divides x largestdivisiblesubset1 16 7 8 4 16 8 4 1 largestdivisiblesubset1 2 3 2 1 largestdivisiblesubset1 2 3 3 largestdivisiblesubset1 2 4 8 8 4 2 1 largestdivisiblesubset1 2 4 8 8 4 2 1 largestdivisiblesubset1 1 1 1 1 1 largestdivisiblesubset0 0 0 0 0 0 largestdivisiblesubset1 1 1 1 1 1 largestdivisiblesubset sort the array in ascending order as the sequence does not matter we only have to pick up a subset initialize memo with 1s and hash with increasing numbers iterate through the array find the maximum length and its corresponding index reconstruct the divisible subset algorithm to find the biggest subset in the given array such that for any 2 elements x and y in the subset either x divides y or y divides x largest_divisible_subset 1 16 7 8 4 16 8 4 1 largest_divisible_subset 1 2 3 2 1 largest_divisible_subset 1 2 3 3 largest_divisible_subset 1 2 4 8 8 4 2 1 largest_divisible_subset 1 2 4 8 8 4 2 1 largest_divisible_subset 1 1 1 1 1 1 largest_divisible_subset 0 0 0 0 0 0 largest_divisible_subset 1 1 1 1 1 1 largest_divisible_subset sort the array in ascending order as the sequence does not matter we only have to pick up a subset initialize memo with 1s and hash with increasing numbers iterate through the array find the maximum length and its corresponding index reconstruct the divisible subset
from __future__ import annotations def largest_divisible_subset(items: list[int]) -> list[int]: items = sorted(items) number_of_items = len(items) memo = [1] * number_of_items hash_array = list(range(number_of_items)) for i, item in enumerate(items): for prev_index in range(i): if ((items[prev_index] != 0 and item % items[prev_index]) == 0) and ( (1 + memo[prev_index]) > memo[i] ): memo[i] = 1 + memo[prev_index] hash_array[i] = prev_index ans = -1 last_index = -1 for i, memo_item in enumerate(memo): if memo_item > ans: ans = memo_item last_index = i if last_index == -1: return [] result = [items[last_index]] while hash_array[last_index] != last_index: last_index = hash_array[last_index] result.append(items[last_index]) return result if __name__ == "__main__": from doctest import testmod testmod() items = [1, 16, 7, 8, 4] print( f"The longest divisible subset of {items} is {largest_divisible_subset(items)}." )
lcs problem statement given two sequences find the length of longest subsequence present in both of them a subsequence is a sequence that appears in the same relative order but not necessarily continuous example abc abg are subsequences of abcdefgh finds the longest common subsequence between two strings also returns the the subsequence found parameters x str one of the strings y str the other string returns lmn int the length of the longest subsequence also equal to lenseq seq str the subsequence found longestcommonsubsequenceprogramming gaming 6 gaming longestcommonsubsequencephysics smartphone 2 ph longestcommonsubsequencecomputer food 1 o find the length of strings declaring the array for storing the dp values finds the longest common subsequence between two strings also returns the the subsequence found parameters x str one of the strings y str the other string returns l m n int the length of the longest subsequence also equal to len seq seq str the subsequence found longest_common_subsequence programming gaming 6 gaming longest_common_subsequence physics smartphone 2 ph longest_common_subsequence computer food 1 o find the length of strings declaring the array for storing the dp values noqa e741
def longest_common_subsequence(x: str, y: str): assert x is not None assert y is not None m = len(x) n = len(y) l = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): match = 1 if x[i - 1] == y[j - 1] else 0 l[i][j] = max(l[i - 1][j], l[i][j - 1], l[i - 1][j - 1] + match) seq = "" i, j = m, n while i > 0 and j > 0: match = 1 if x[i - 1] == y[j - 1] else 0 if l[i][j] == l[i - 1][j - 1] + match: if match == 1: seq = x[i - 1] + seq i -= 1 j -= 1 elif l[i][j] == l[i - 1][j]: i -= 1 else: j -= 1 return l[m][n], seq if __name__ == "__main__": a = "AGGTAB" b = "GXTXAYB" expected_ln = 4 expected_subseq = "GTAB" ln, subseq = longest_common_subsequence(a, b) print("len =", ln, ", sub-sequence =", subseq) import doctest doctest.testmod()
longest common substring problem statement given two sequences find the longest common substring present in both of them a substring is necessarily continuous example abcdef and xabded have two longest common substrings ab or de therefore algorithm should return any one of them finds the longest common substring between two strings longestcommonsubstring longestcommonsubstringa longestcommonsubstring a longestcommonsubstringa a a longestcommonsubstringabcdef bcd bcd longestcommonsubstringabcdef xabded ab longestcommonsubstringgeeksforgeeks geeksquiz geeks longestcommonsubstringabcdxyz xyzabcd abcd longestcommonsubstringzxabcdezy yzabcdezx abcdez longestcommonsubstringoldsite geeksforgeeks org newsite geeksquiz com site geeks longestcommonsubstring1 1 traceback most recent call last valueerror longestcommonsubstring takes two strings for inputs finds the longest common substring between two strings longest_common_substring longest_common_substring a longest_common_substring a longest_common_substring a a a longest_common_substring abcdef bcd bcd longest_common_substring abcdef xabded ab longest_common_substring geeksforgeeks geeksquiz geeks longest_common_substring abcdxyz xyzabcd abcd longest_common_substring zxabcdezy yzabcdezx abcdez longest_common_substring oldsite geeksforgeeks org newsite geeksquiz com site geeks longest_common_substring 1 1 traceback most recent call last valueerror longest_common_substring takes two strings for inputs
def longest_common_substring(text1: str, text2: str) -> str: if not (isinstance(text1, str) and isinstance(text2, str)): raise ValueError("longest_common_substring() takes two strings for inputs") text1_length = len(text1) text2_length = len(text2) dp = [[0] * (text2_length + 1) for _ in range(text1_length + 1)] ans_index = 0 ans_length = 0 for i in range(1, text1_length + 1): for j in range(1, text2_length + 1): if text1[i - 1] == text2[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] if dp[i][j] > ans_length: ans_index = i ans_length = dp[i][j] return text1[ans_index - ans_length : ans_index] if __name__ == "__main__": import doctest doctest.testmod()
mehdi alaoui this is a pure python implementation of dynamic programming solution to the longest increasing subsequence of a given sequence the problem is given an array to find the longest and increasing subarray in that given array and return it example 10 22 9 33 21 50 41 60 80 as input will return 10 22 33 41 60 80 as output some examples longestsubsequence10 22 9 33 21 50 41 60 80 10 22 33 41 60 80 longestsubsequence4 8 7 5 1 12 2 3 9 1 2 3 9 longestsubsequence9 8 7 6 5 7 8 longestsubsequence1 1 1 1 1 1 longestsubsequence if the array contains only one element we return it it s the stop condition of recursion else this function is recursive some examples longest_subsequence 10 22 9 33 21 50 41 60 80 10 22 33 41 60 80 longest_subsequence 4 8 7 5 1 12 2 3 9 1 2 3 9 longest_subsequence 9 8 7 6 5 7 8 longest_subsequence 1 1 1 1 1 1 longest_subsequence if the array contains only one element we return it it s the stop condition of recursion else
from __future__ import annotations def longest_subsequence(array: list[int]) -> list[int]: array_length = len(array) if array_length <= 1: return array pivot = array[0] is_found = False i = 1 longest_subseq: list[int] = [] while not is_found and i < array_length: if array[i] < pivot: is_found = True temp_array = [element for element in array[i:] if element >= array[i]] temp_array = longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): longest_subseq = temp_array else: i += 1 temp_array = [element for element in array[1:] if element >= pivot] temp_array = [pivot, *longest_subsequence(temp_array)] if len(temp_array) > len(longest_subseq): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
aravind kashyap file lis py comments this programme outputs the longest strictly increasing subsequence in onlogn where n is the number of elements in the list longestincreasingsubsequencelength2 5 3 7 11 8 10 13 6 6 longestincreasingsubsequencelength 0 longestincreasingsubsequencelength0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 6 longestincreasingsubsequencelength5 4 3 2 1 1 aravind kashyap file lis py comments this programme outputs the longest strictly increasing subsequence in o nlogn where n is the number of elements in the list noqa e741 noqa e741 longest_increasing_subsequence_length 2 5 3 7 11 8 10 13 6 6 longest_increasing_subsequence_length 0 longest_increasing_subsequence_length 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 6 longest_increasing_subsequence_length 5 4 3 2 1 1
from __future__ import annotations def ceil_index(v, l, r, key): while r - l > 1: m = (l + r) // 2 if v[m] >= key: r = m else: l = m return r def longest_increasing_subsequence_length(v: list[int]) -> int: if len(v) == 0: return 0 tail = [0] * len(v) length = 1 tail[0] = v[0] for i in range(1, len(v)): if v[i] < tail[0]: tail[0] = v[i] elif v[i] > tail[length - 1]: tail[length] = v[i] length += 1 else: tail[ceil_index(tail, -1, length - 1, v[i])] = v[i] return length if __name__ == "__main__": import doctest doctest.testmod()
sanket kittad given a string s find the longest palindromic subsequence s length in s input s bbbab output 4 explanation one possible longest palindromic subsequence is bbbb leetcode link https leetcode comproblemslongestpalindromicsubsequencedescription this function returns the longest palindromic subsequence in a string longestpalindromicsubsequencebbbab 4 longestpalindromicsubsequencebbabcbcab 7 create and initialise dp array if characters at i and j are the same include them in the palindromic subsequence this function returns the longest palindromic subsequence in a string longest_palindromic_subsequence bbbab 4 longest_palindromic_subsequence bbabcbcab 7 create and initialise dp array if characters at i and j are the same include them in the palindromic subsequence
def longest_palindromic_subsequence(input_string: str) -> int: n = len(input_string) rev = input_string[::-1] m = len(rev) dp = [[-1] * (m + 1) for i in range(n + 1)] for i in range(n + 1): dp[i][0] = 0 for i in range(m + 1): dp[0][i] = 0 for i in range(1, n + 1): for j in range(1, m + 1): if input_string[i - 1] == rev[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
find the minimum number of multiplications needed to multiply chain of matrices reference https www geeksforgeeks orgmatrixchainmultiplicationdp8 the algorithm has interesting realworld applications example 1 image transformations in computer graphics as images are composed of matrix 2 solve complex polynomial equations in the field of algebra using least processing power 3 calculate overall impact of macroeconomic decisions as economic equations involve a number of variables 4 selfdriving car navigation can be made more accurate as matrix multiplication can accurately determine position and orientation of obstacles in short time python doctests can be run with the following command python m doctest v matrixchainmultiply py given a sequence arr that represents chain of 2d matrices such that the dimension of the ith matrix is arri1arri so suppose arr 40 20 30 10 30 means we have 4 matrices of dimensions 4020 2030 3010 and 1030 matrixchainmultiply returns an integer denoting minimum number of multiplications to multiply the chain we do not need to perform actual multiplication here we only need to decide the order in which to perform the multiplication hints 1 number of multiplications ie cost to multiply 2 matrices of size mp and pn is mpn 2 cost of matrix multiplication is associative ie m1m2m3 m1m2m3 3 matrix multiplication is not commutative so m1m2 does not mean m2m1 can be done 4 to determine the required order we can try different combinations so this problem has overlapping subproblems and can be solved using recursion we use dynamic programming for optimal time complexity example input arr 40 20 30 10 30 output 26000 find the minimum number of multiplcations required to multiply the chain of matrices args arr the input array of integers returns minimum number of multiplications needed to multiply the chain examples matrixchainmultiply1 2 3 4 3 30 matrixchainmultiply10 0 matrixchainmultiply10 20 0 matrixchainmultiply19 2 19 722 matrixchainmultiplylistrange1 100 323398 matrixchainmultiplylistrange1 251 2626798 initialising 2d dp matrix we want minimum cost of multiplication of matrices of dimension ik and kj this cost is arri1arrkarrj source https en wikipedia orgwikimatrixchainmultiplication the dynamic programming solution is faster than cached the recursive solution and can handle larger inputs matrixchainorder1 2 3 4 3 30 matrixchainorder10 0 matrixchainorder10 20 0 matrixchainorder19 2 19 722 matrixchainorderlistrange1 100 323398 matrixchainorderlistrange1 251 max before recursionerror is raised 2626798 printfstarting msg find the minimum number of multiplcations required to multiply the chain of matrices args arr the input array of integers returns minimum number of multiplications needed to multiply the chain examples matrix_chain_multiply 1 2 3 4 3 30 matrix_chain_multiply 10 0 matrix_chain_multiply 10 20 0 matrix_chain_multiply 19 2 19 722 matrix_chain_multiply list range 1 100 323398 matrix_chain_multiply list range 1 251 2626798 initialising 2d dp matrix we want minimum cost of multiplication of matrices of dimension i k and k j this cost is arr i 1 arr k arr j source https en wikipedia org wiki matrix_chain_multiplication the dynamic programming solution is faster than cached the recursive solution and can handle larger inputs matrix_chain_order 1 2 3 4 3 30 matrix_chain_order 10 0 matrix_chain_order 10 20 0 matrix_chain_order 19 2 19 722 matrix_chain_order list range 1 100 323398 matrix_chain_order list range 1 251 max before recursionerror is raised 2626798 print f starting msg
from collections.abc import Iterator from contextlib import contextmanager from functools import cache from sys import maxsize def matrix_chain_multiply(arr: list[int]) -> int: if len(arr) < 2: return 0 n = len(arr) dp = [[maxsize for j in range(n)] for i in range(n)] for i in range(n - 1, 0, -1): for j in range(i, n): if i == j: dp[i][j] = 0 continue for k in range(i, j): dp[i][j] = min( dp[i][j], dp[i][k] + dp[k + 1][j] + arr[i - 1] * arr[k] * arr[j] ) return dp[1][n - 1] def matrix_chain_order(dims: list[int]) -> int: @cache def a(i: int, j: int) -> int: return min( (a(i, k) + dims[i] * dims[k] * dims[j] + a(k, j) for k in range(i + 1, j)), default=0, ) return a(0, len(dims) - 1) @contextmanager def elapsed_time(msg: str) -> Iterator: from time import perf_counter_ns start = perf_counter_ns() yield print(f"Finished: {msg} in {(perf_counter_ns() - start) / 10 ** 9} seconds.") if __name__ == "__main__": import doctest doctest.testmod() with elapsed_time("matrix_chain_order"): print(f"{matrix_chain_order(list(range(1, 251))) = }") with elapsed_time("matrix_chain_multiply"): print(f"{matrix_chain_multiply(list(range(1, 251))) = }") with elapsed_time("matrix_chain_order"): print(f"{matrix_chain_order(list(range(1, 251))) = }") with elapsed_time("matrix_chain_multiply"): print(f"{matrix_chain_multiply(list(range(1, 251))) = }")
dynamic programming implementation of matrix chain multiplication time complexity on3 space complexity on2 print order of matrix with ai as matrix size of matrix created from above array will be 3035 3515 155 510 1020 2025 dynamic programming implementation of matrix chain multiplication time complexity o n 3 space complexity o n 2 print order of matrix with ai as matrix size of matrix created from above array will be 30 35 35 15 15 5 5 10 10 20 20 25
import sys def matrix_chain_order(array): n = len(array) matrix = [[0 for x in range(n)] for x in range(n)] sol = [[0 for x in range(n)] for x in range(n)] for chain_length in range(2, n): for a in range(1, n - chain_length + 1): b = a + chain_length - 1 matrix[a][b] = sys.maxsize for c in range(a, b): cost = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: matrix[a][b] = cost sol[a][b] = c return matrix, sol def print_optiomal_solution(optimal_solution, i, j): if i == j: print("A" + str(i), end=" ") else: print("(", end=" ") print_optiomal_solution(optimal_solution, i, optimal_solution[i][j]) print_optiomal_solution(optimal_solution, optimal_solution[i][j] + 1, j) print(")", end=" ") def main(): array = [30, 35, 15, 5, 10, 20, 25] n = len(array) matrix, optimal_solution = matrix_chain_order(array) print("No. of Operation required: " + str(matrix[1][n - 1])) print_optiomal_solution(optimal_solution, 1, n - 1) if __name__ == "__main__": main()
video explanation https www youtube comwatch v6w60zi1ntl8featureemblogo find the maximum nonadjacent sum of the integers in the nums input list maximumnonadjacentsum1 2 3 4 maximumnonadjacentsum1 5 3 7 2 2 6 18 maximumnonadjacentsum1 5 3 7 2 2 6 0 maximumnonadjacentsum499 500 3 7 2 2 6 500 video explanation https www youtube com watch v 6w60zi1ntl8 feature emb_logo find the maximum non adjacent sum of the integers in the nums input list maximum_non_adjacent_sum 1 2 3 4 maximum_non_adjacent_sum 1 5 3 7 2 2 6 18 maximum_non_adjacent_sum 1 5 3 7 2 2 6 0 maximum_non_adjacent_sum 499 500 3 7 2 2 6 500
from __future__ import annotations def maximum_non_adjacent_sum(nums: list[int]) -> int: if not nums: return 0 max_including = nums[0] max_excluding = 0 for num in nums[1:]: max_including, max_excluding = ( max_excluding + num, max(max_including, max_excluding), ) return max(max_excluding, max_including) if __name__ == "__main__": import doctest doctest.testmod()
returns the maximum product that can be obtained by multiplying a contiguous subarray of the given integer list nums example maxproductsubarray2 3 2 4 6 maxproductsubarray2 0 1 0 maxproductsubarray2 3 2 4 1 48 maxproductsubarray1 1 maxproductsubarray0 0 maxproductsubarray 0 maxproductsubarray 0 maxproductsubarraynone 0 maxproductsubarray2 3 2 4 5 1 traceback most recent call last valueerror numbers must be an iterable of integers maxproductsubarrayabc traceback most recent call last valueerror numbers must be an iterable of integers update the maximum and minimum subarray products update the maximum product found till now returns the maximum product that can be obtained by multiplying a contiguous subarray of the given integer list nums example max_product_subarray 2 3 2 4 6 max_product_subarray 2 0 1 0 max_product_subarray 2 3 2 4 1 48 max_product_subarray 1 1 max_product_subarray 0 0 max_product_subarray 0 max_product_subarray 0 max_product_subarray none 0 max_product_subarray 2 3 2 4 5 1 traceback most recent call last valueerror numbers must be an iterable of integers max_product_subarray abc traceback most recent call last valueerror numbers must be an iterable of integers update the maximum and minimum subarray products update the maximum product found till now
def max_product_subarray(numbers: list[int]) -> int: if not numbers: return 0 if not isinstance(numbers, (list, tuple)) or not all( isinstance(number, int) for number in numbers ): raise ValueError("numbers must be an iterable of integers") max_till_now = min_till_now = max_prod = numbers[0] for i in range(1, len(numbers)): number = numbers[i] if number < 0: max_till_now, min_till_now = min_till_now, max_till_now max_till_now = max(number, max_till_now * number) min_till_now = min(number, min_till_now * number) max_prod = max(max_prod, max_till_now) return max_prod
the maximum subarray sum problem is the task of finding the maximum sum that can be obtained from a contiguous subarray within a given array of numbers for example given the array 2 1 3 4 1 2 1 5 4 the contiguous subarray with the maximum sum is 4 1 2 1 so the maximum subarray sum is 6 kadane s algorithm is a simple dynamic programming algorithm that solves the maximum subarray sum problem in on time and o1 space reference https en wikipedia orgwikimaximumsubarrayproblem solves the maximum subarray sum problem using kadane s algorithm param arr the given array of numbers param allowemptysubarrays if true then the algorithm considers empty subarrays maxsubarraysum2 8 9 19 maxsubarraysum0 0 0 maxsubarraysum1 0 0 0 1 0 1 0 maxsubarraysum1 2 3 4 2 10 maxsubarraysum2 1 3 4 1 2 1 5 4 6 maxsubarraysum2 3 9 8 2 8 maxsubarraysum2 3 1 4 6 1 maxsubarraysum2 3 1 4 6 allowemptysubarraystrue 0 maxsubarraysum 0 solves the maximum subarray sum problem using kadane s algorithm param arr the given array of numbers param allow_empty_subarrays if true then the algorithm considers empty subarrays max_subarray_sum 2 8 9 19 max_subarray_sum 0 0 0 max_subarray_sum 1 0 0 0 1 0 1 0 max_subarray_sum 1 2 3 4 2 10 max_subarray_sum 2 1 3 4 1 2 1 5 4 6 max_subarray_sum 2 3 9 8 2 8 max_subarray_sum 2 3 1 4 6 1 max_subarray_sum 2 3 1 4 6 allow_empty_subarrays true 0 max_subarray_sum 0
from collections.abc import Sequence def max_subarray_sum( arr: Sequence[float], allow_empty_subarrays: bool = False ) -> float: if not arr: return 0 max_sum = 0 if allow_empty_subarrays else float("-inf") curr_sum = 0.0 for num in arr: curr_sum = max(0 if allow_empty_subarrays else num, curr_sum + num) max_sum = max(max_sum, curr_sum) return max_sum if __name__ == "__main__": from doctest import testmod testmod() nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f"{max_subarray_sum(nums) = }")
alexander pantyukhin date october 14 2022 this is an implementation of the upbottom approach to find edit distance the implementation was tested on leetcode https leetcode comproblemseditdistance levinstein distance dynamic programming up down mindistanceupbottomintention execution 5 mindistanceupbottomintention 9 mindistanceupbottom 0 mindistanceupbottomzooicoarchaeologist zoologist 10 if first word index overflows delete all from the second word if second word index overflows delete all from the first word min_distance_up_bottom intention execution 5 min_distance_up_bottom intention 9 min_distance_up_bottom 0 min_distance_up_bottom zooicoarchaeologist zoologist 10 if first word index overflows delete all from the second word if second word index overflows delete all from the first word current letters not identical
import functools def min_distance_up_bottom(word1: str, word2: str) -> int: len_word1 = len(word1) len_word2 = len(word2) @functools.cache def min_distance(index1: int, index2: int) -> int: if index1 >= len_word1: return len_word2 - index2 if index2 >= len_word2: return len_word1 - index1 diff = int(word1[index1] != word2[index2]) return min( 1 + min_distance(index1 + 1, index2), 1 + min_distance(index1, index2 + 1), diff + min_distance(index1 + 1, index2 + 1), ) return min_distance(0, 0) if __name__ == "__main__": import doctest doctest.testmod()
you have m types of coins available in infinite quantities where the value of each coins is given in the array ss0 sm1 can you determine number of ways of making change for n units using the given types of coins https www hackerrank comchallengescoinchangeproblem dpcount1 2 3 4 4 dpcount1 2 3 7 8 dpcount2 5 3 6 10 5 dpcount10 99 0 dpcount4 5 6 0 1 dpcount1 2 3 5 0 tablei represents the number of ways to get to amount i there is exactly 1 way to get to zeroyou pick no coins pick all coins one by one and update table values after the index greater than or equal to the value of the picked coin dp_count 1 2 3 4 4 dp_count 1 2 3 7 8 dp_count 2 5 3 6 10 5 dp_count 10 99 0 dp_count 4 5 6 0 1 dp_count 1 2 3 5 0 table i represents the number of ways to get to amount i there is exactly 1 way to get to zero you pick no coins pick all coins one by one and update table values after the index greater than or equal to the value of the picked coin
def dp_count(s, n): if n < 0: return 0 table = [0] * (n + 1) table[0] = 1 for coin_val in s: for j in range(coin_val, n + 1): table[j] += table[j - coin_val] return table[n] if __name__ == "__main__": import doctest doctest.testmod()
youtube explanation https www youtube comwatch vlbrtnuxggu find the minimum cost traced by all possible paths from top left to bottom right in a given matrix minimumcostpath2 1 3 1 4 2 6 minimumcostpath2 1 4 2 1 3 3 2 1 7 preprocessing the first row preprocessing the first column updating the path cost for current position youtube explanation https www youtube com watch v lbrtnuxg gu find the minimum cost traced by all possible paths from top left to bottom right in a given matrix minimum_cost_path 2 1 3 1 4 2 6 minimum_cost_path 2 1 4 2 1 3 3 2 1 7 preprocessing the first row preprocessing the first column updating the path cost for current position
from __future__ import annotations def minimum_cost_path(matrix: list[list[int]]) -> int: for i in range(1, len(matrix[0])): matrix[0][i] += matrix[0][i - 1] for i in range(1, len(matrix)): matrix[i][0] += matrix[i - 1][0] for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1]) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
partition a set into two subsets such that the difference of subset sums is minimum findmin1 2 3 4 5 1 findmin5 5 5 5 5 5 findmin5 5 5 5 0 findmin3 3 findmin 0 findmin1 2 3 4 0 findmin0 0 0 0 0 findmin1 5 5 1 0 findmin1 5 5 1 0 findmin9 9 9 9 9 9 findmin1 5 10 3 1 findmin1 0 1 0 findminrange10 0 1 1 findmin1 traceback most recent call last indexerror list assignment index out of range findmin0 0 0 1 2 4 traceback most recent call last indexerror list assignment index out of range findmin1 5 10 3 traceback most recent call last indexerror list assignment index out of range find_min 1 2 3 4 5 1 find_min 5 5 5 5 5 5 find_min 5 5 5 5 0 find_min 3 3 find_min 0 find_min 1 2 3 4 0 find_min 0 0 0 0 0 find_min 1 5 5 1 0 find_min 1 5 5 1 0 find_min 9 9 9 9 9 9 find_min 1 5 10 3 1 find_min 1 0 1 0 find_min range 10 0 1 1 find_min 1 traceback most recent call last indexerror list assignment index out of range find_min 0 0 0 1 2 4 traceback most recent call last indexerror list assignment index out of range find_min 1 5 10 3 traceback most recent call last indexerror list assignment index out of range
def find_min(numbers: list[int]) -> int: n = len(numbers) s = sum(numbers) dp = [[False for x in range(s + 1)] for y in range(n + 1)] for i in range(n + 1): dp[i][0] = True for i in range(1, s + 1): dp[0][i] = False for i in range(1, n + 1): for j in range(1, s + 1): dp[i][j] = dp[i - 1][j] if numbers[i - 1] <= j: dp[i][j] = dp[i][j] or dp[i - 1][j - numbers[i - 1]] for j in range(int(s / 2), -1, -1): if dp[n][j] is True: diff = s - 2 * j break return diff if __name__ == "__main__": from doctest import testmod testmod()
return the length of the shortest contiguous subarray in a list of numbers whose sum is at least target reference https stackoverflow comquestions8269916 minimumsubarraysum7 2 3 1 2 4 3 2 minimumsubarraysum7 2 3 1 2 4 3 4 minimumsubarraysum11 1 1 1 1 1 1 1 1 0 minimumsubarraysum10 1 2 3 4 5 6 7 2 minimumsubarraysum5 1 1 1 1 1 5 1 minimumsubarraysum0 0 minimumsubarraysum0 1 2 3 1 minimumsubarraysum10 10 20 30 1 minimumsubarraysum7 1 1 1 1 1 1 10 1 minimumsubarraysum6 0 minimumsubarraysum2 1 2 3 1 minimumsubarraysum6 0 minimumsubarraysum6 3 4 5 1 minimumsubarraysum8 none 0 minimumsubarraysum2 abc traceback most recent call last valueerror numbers must be an iterable of integers return the length of the shortest contiguous subarray in a list of numbers whose sum is at least target reference https stackoverflow com questions 8269916 minimum_subarray_sum 7 2 3 1 2 4 3 2 minimum_subarray_sum 7 2 3 1 2 4 3 4 minimum_subarray_sum 11 1 1 1 1 1 1 1 1 0 minimum_subarray_sum 10 1 2 3 4 5 6 7 2 minimum_subarray_sum 5 1 1 1 1 1 5 1 minimum_subarray_sum 0 0 minimum_subarray_sum 0 1 2 3 1 minimum_subarray_sum 10 10 20 30 1 minimum_subarray_sum 7 1 1 1 1 1 1 10 1 minimum_subarray_sum 6 0 minimum_subarray_sum 2 1 2 3 1 minimum_subarray_sum 6 0 minimum_subarray_sum 6 3 4 5 1 minimum_subarray_sum 8 none 0 minimum_subarray_sum 2 abc traceback most recent call last valueerror numbers must be an iterable of integers
import sys def minimum_subarray_sum(target: int, numbers: list[int]) -> int: if not numbers: return 0 if target == 0 and target in numbers: return 0 if not isinstance(numbers, (list, tuple)) or not all( isinstance(number, int) for number in numbers ): raise ValueError("numbers must be an iterable of integers") left = right = curr_sum = 0 min_len = sys.maxsize while right < len(numbers): curr_sum += numbers[right] while curr_sum >= target and left <= right: min_len = min(min_len, right - left + 1) curr_sum -= numbers[left] left += 1 right += 1 return 0 if min_len == sys.maxsize else min_len
count the number of minimum squares to represent a number minimumsquarestorepresentanumber25 1 minimumsquarestorepresentanumber37 2 minimumsquarestorepresentanumber21 3 minimumsquarestorepresentanumber58 2 minimumsquarestorepresentanumber1 traceback most recent call last valueerror the value of input must not be a negative number minimumsquarestorepresentanumber0 1 minimumsquarestorepresentanumber12 34 traceback most recent call last valueerror the value of input must be a natural number count the number of minimum squares to represent a number minimum_squares_to_represent_a_number 25 1 minimum_squares_to_represent_a_number 37 2 minimum_squares_to_represent_a_number 21 3 minimum_squares_to_represent_a_number 58 2 minimum_squares_to_represent_a_number 1 traceback most recent call last valueerror the value of input must not be a negative number minimum_squares_to_represent_a_number 0 1 minimum_squares_to_represent_a_number 12 34 traceback most recent call last valueerror the value of input must be a natural number
import math import sys def minimum_squares_to_represent_a_number(number: int) -> int: if number != int(number): raise ValueError("the value of input must be a natural number") if number < 0: raise ValueError("the value of input must not be a negative number") if number == 0: return 1 answers = [-1] * (number + 1) answers[0] = 0 for i in range(1, number + 1): answer = sys.maxsize root = int(math.sqrt(i)) for j in range(1, root + 1): current_answer = 1 + answers[i - (j**2)] answer = min(answer, current_answer) answers[i] = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
youtube explanation https www youtube comwatch vf2xi3c1s95m given an integer n return the minimum steps from n to 1 available steps decrement by 1 if n is divisible by 2 divide by 2 if n is divisible by 3 divide by 3 example 1 n 10 10 9 3 1 result 3 steps example 2 n 15 15 5 4 2 1 result 4 steps example 3 n 6 6 2 1 result 2 step minimum steps to 1 implemented using tabulation minstepstoone10 3 minstepstoone15 4 minstepstoone6 2 param number return int starting position check if out of bounds check if out of bounds minimum steps to 1 implemented using tabulation min_steps_to_one 10 3 min_steps_to_one 15 4 min_steps_to_one 6 2 param number return int starting position check if out of bounds check if out of bounds
from __future__ import annotations __author__ = "Alexander Joslin" def min_steps_to_one(number: int) -> int: if number <= 0: msg = f"n must be greater than 0. Got n = {number}" raise ValueError(msg) table = [number + 1] * (number + 1) table[1] = 0 for i in range(1, number): table[i + 1] = min(table[i + 1], table[i] + 1) if i * 2 <= number: table[i * 2] = min(table[i * 2], table[i] + 1) if i * 3 <= number: table[i * 3] = min(table[i * 3], table[i] + 1) return table[number] if __name__ == "__main__": import doctest doctest.testmod()
alexander pantyukhin date november 1 2022 task given a list of days when you need to travel each day is integer from 1 to 365 you are able to use tickets for 1 day 7 days and 30 days each ticket has a cost find the minimum cost you need to travel every day in the given list of days implementation notes implementation dynamic programming up bottom approach runtime complexity on the implementation was tested on the leetcode https leetcode comproblemsminimumcostfortickets minimum cost for tickets dynamic programming up down mincosttickets1 4 6 7 8 20 2 7 15 11 mincosttickets1 2 3 4 5 6 7 8 9 10 30 31 2 7 15 17 mincosttickets1 2 3 4 5 6 7 8 9 10 30 31 2 90 150 24 mincosttickets2 2 90 150 2 mincosttickets 2 90 150 0 mincosttickets hello 2 90 150 traceback most recent call last valueerror the parameter days should be a list of integers mincosttickets world traceback most recent call last valueerror the parameter costs should be a list of three integers mincosttickets0 25 2 3 4 5 6 7 8 9 10 30 31 2 90 150 traceback most recent call last valueerror the parameter days should be a list of integers mincosttickets1 2 3 4 5 6 7 8 9 10 30 31 2 0 9 150 traceback most recent call last valueerror the parameter costs should be a list of three integers mincosttickets1 2 3 4 5 6 7 8 9 10 30 31 2 90 150 traceback most recent call last valueerror all days elements should be greater than 0 mincosttickets2 367 2 90 150 traceback most recent call last valueerror all days elements should be less than 366 mincosttickets2 3 4 5 6 7 8 9 10 30 31 traceback most recent call last valueerror the parameter costs should be a list of three integers mincosttickets traceback most recent call last valueerror the parameter costs should be a list of three integers mincosttickets2 3 4 5 6 7 8 9 10 30 31 1 2 3 4 traceback most recent call last valueerror the parameter costs should be a list of three integers validation mincost_tickets 1 4 6 7 8 20 2 7 15 11 mincost_tickets 1 2 3 4 5 6 7 8 9 10 30 31 2 7 15 17 mincost_tickets 1 2 3 4 5 6 7 8 9 10 30 31 2 90 150 24 mincost_tickets 2 2 90 150 2 mincost_tickets 2 90 150 0 mincost_tickets hello 2 90 150 traceback most recent call last valueerror the parameter days should be a list of integers mincost_tickets world traceback most recent call last valueerror the parameter costs should be a list of three integers mincost_tickets 0 25 2 3 4 5 6 7 8 9 10 30 31 2 90 150 traceback most recent call last valueerror the parameter days should be a list of integers mincost_tickets 1 2 3 4 5 6 7 8 9 10 30 31 2 0 9 150 traceback most recent call last valueerror the parameter costs should be a list of three integers mincost_tickets 1 2 3 4 5 6 7 8 9 10 30 31 2 90 150 traceback most recent call last valueerror all days elements should be greater than 0 mincost_tickets 2 367 2 90 150 traceback most recent call last valueerror all days elements should be less than 366 mincost_tickets 2 3 4 5 6 7 8 9 10 30 31 traceback most recent call last valueerror the parameter costs should be a list of three integers mincost_tickets traceback most recent call last valueerror the parameter costs should be a list of three integers mincost_tickets 2 3 4 5 6 7 8 9 10 30 31 1 2 3 4 traceback most recent call last valueerror the parameter costs should be a list of three integers validation
import functools def mincost_tickets(days: list[int], costs: list[int]) -> int: if not isinstance(days, list) or not all(isinstance(day, int) for day in days): raise ValueError("The parameter days should be a list of integers") if len(costs) != 3 or not all(isinstance(cost, int) for cost in costs): raise ValueError("The parameter costs should be a list of three integers") if len(days) == 0: return 0 if min(days) <= 0: raise ValueError("All days elements should be greater than 0") if max(days) >= 366: raise ValueError("All days elements should be less than 366") days_set = set(days) @functools.cache def dynamic_programming(index: int) -> int: if index > 365: return 0 if index not in days_set: return dynamic_programming(index + 1) return min( costs[0] + dynamic_programming(index + 1), costs[1] + dynamic_programming(index + 7), costs[2] + dynamic_programming(index + 30), ) return dynamic_programming(1) if __name__ == "__main__": import doctest doctest.testmod()
usrbinenv python3 this python program implements an optimal binary search tree abbreviated bst building dynamic programming algorithm that delivers on2 performance the goal of the optimal bst problem is to build a lowcost bst for a given set of nodes each with its own key and frequency the frequency of the node is defined as how many time the node is being searched the search cost of binary search tree is given by this formula cost1 n sumi 1 to ndepthnodei 1 nodeifreq where n is number of nodes in the bst the characteristic of lowcost bsts is having a faster overall search time than other implementations the reason for their fast search time is that the nodes with high frequencies will be placed near the root of the tree while the nodes with low frequencies will be placed near the leaves of the tree thus reducing search time in the most frequent instances binary search tree node def initself key freq self key key self freq freq def strself return fnodekeyself key freqself freq def printbinarysearchtreeroot key i j parent isleft if i j or i 0 or j lenroot 1 return node rootij if parent 1 root does not have a parent printfkeynode is the root of the binary search tree elif isleft printfkeynode is the left child of key parent else printfkeynode is the right child of key parent printbinarysearchtreeroot key i node 1 keynode true printbinarysearchtreeroot key node 1 j keynode false def findoptimalbinarysearchtreenodes tree nodes must be sorted first the code below sorts the keys in increasing order and rearrange its frequencies accordingly nodes sortkeylambda node node key n lennodes keys nodesi key for i in rangen freqs nodesi freq for i in rangen this 2d array stores the overall tree cost which s as minimized as possible for a single key cost is equal to frequency of the key dp freqsi if i j else 0 for j in rangen for i in rangen sumij stores the sum of key frequencies between i and j inclusive in nodes array total freqsi if i j else 0 for j in rangen for i in rangen stores tree roots that will be used later for constructing binary search tree root i if i j else 0 for j in rangen for i in rangen for intervallength in range2 n 1 for i in rangen intervallength 1 j i intervallength 1 dpij sys maxsize set the value to infinity totalij totalij 1 freqsj apply knuth s optimization loop without optimization for r in rangei j 1 for r in rangerootij 1 rooti 1j 1 r is a temporal root left dpir 1 if r i else 0 optimal cost for left subtree right dpr 1j if r j else 0 optimal cost for right subtree cost left totalij right if dpij cost dpij cost rootij r printbinary search tree nodes for node in nodes printnode printfnthe cost of optimal bst for given tree nodes is dp0n 1 printbinarysearchtreeroot keys 0 n 1 1 false def main a sample binary search tree nodes nodei randint1 50 for i in range10 0 1 findoptimalbinarysearchtreenodes if name main main usr bin env python3 this python program implements an optimal binary search tree abbreviated bst building dynamic programming algorithm that delivers o n 2 performance the goal of the optimal bst problem is to build a low cost bst for a given set of nodes each with its own key and frequency the frequency of the node is defined as how many time the node is being searched the search cost of binary search tree is given by this formula cost 1 n sum i 1 to n depth node_i 1 node_i_freq where n is number of nodes in the bst the characteristic of low cost bsts is having a faster overall search time than other implementations the reason for their fast search time is that the nodes with high frequencies will be placed near the root of the tree while the nodes with low frequencies will be placed near the leaves of the tree thus reducing search time in the most frequent instances binary search tree node str node 1 2 node key 1 freq 2 recursive function to print a bst from a root table key 3 8 9 10 17 21 root 0 1 1 1 1 1 0 1 1 1 1 3 0 0 2 3 3 3 0 0 0 3 3 3 0 0 0 0 4 5 0 0 0 0 0 5 print_binary_search_tree root key 0 5 1 false 8 is the root of the binary search tree 3 is the left child of key 8 10 is the right child of key 8 9 is the left child of key 10 21 is the right child of key 10 17 is the left child of key 21 root does not have a parent this function calculates and prints the optimal binary search tree the dynamic programming algorithm below runs in o n 2 time implemented from clrs introduction to algorithms book https en wikipedia org wiki introduction_to_algorithms find_optimal_binary_search_tree node 12 8 node 10 34 node 20 50 node 42 3 node 25 40 node 37 30 binary search tree nodes node key 10 freq 34 node key 12 freq 8 node key 20 freq 50 node key 25 freq 40 node key 37 freq 30 node key 42 freq 3 blankline the cost of optimal bst for given tree nodes is 324 20 is the root of the binary search tree 10 is the left child of key 20 12 is the right child of key 10 25 is the right child of key 20 37 is the right child of key 25 42 is the right child of key 37 tree nodes must be sorted first the code below sorts the keys in increasing order and rearrange its frequencies accordingly this 2d array stores the overall tree cost which s as minimized as possible for a single key cost is equal to frequency of the key sum i j stores the sum of key frequencies between i and j inclusive in nodes array stores tree roots that will be used later for constructing binary search tree set the value to infinity apply knuth s optimization loop without optimization for r in range i j 1 r is a temporal root optimal cost for left subtree optimal cost for right subtree a sample binary search tree
import sys from random import randint class Node: def __init__(self, key, freq): self.key = key self.freq = freq def __str__(self): return f"Node(key={self.key}, freq={self.freq})" def print_binary_search_tree(root, key, i, j, parent, is_left): if i > j or i < 0 or j > len(root) - 1: return node = root[i][j] if parent == -1: print(f"{key[node]} is the root of the binary search tree.") elif is_left: print(f"{key[node]} is the left child of key {parent}.") else: print(f"{key[node]} is the right child of key {parent}.") print_binary_search_tree(root, key, i, node - 1, key[node], True) print_binary_search_tree(root, key, node + 1, j, key[node], False) def find_optimal_binary_search_tree(nodes): nodes.sort(key=lambda node: node.key) n = len(nodes) keys = [nodes[i].key for i in range(n)] freqs = [nodes[i].freq for i in range(n)] dp = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] total = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)] root = [[i if i == j else 0 for j in range(n)] for i in range(n)] for interval_length in range(2, n + 1): for i in range(n - interval_length + 1): j = i + interval_length - 1 dp[i][j] = sys.maxsize total[i][j] = total[i][j - 1] + freqs[j] for r in range(root[i][j - 1], root[i + 1][j] + 1): left = dp[i][r - 1] if r != i else 0 right = dp[r + 1][j] if r != j else 0 cost = left + total[i][j] + right if dp[i][j] > cost: dp[i][j] = cost root[i][j] = r print("Binary search tree nodes:") for node in nodes: print(node) print(f"\nThe cost of optimal BST for given tree nodes is {dp[0][n - 1]}.") print_binary_search_tree(root, keys, 0, n - 1, -1, False) def main(): nodes = [Node(i, randint(1, 50)) for i in range(10, 0, -1)] find_optimal_binary_search_tree(nodes) if __name__ == "__main__": main()
given a string s partition s such that every substring of the partition is a palindrome find the minimum cuts needed for a palindrome partitioning of s time complexity on2 space complexity on2 for other explanations refer to https www youtube comwatch vh8v5hjugd0 returns the minimum cuts needed for a palindrome partitioning of string findminimumpartitionsaab 1 findminimumpartitionsaaa 0 findminimumpartitionsababbbabbababa 3 returns the minimum cuts needed for a palindrome partitioning of string find_minimum_partitions aab 1 find_minimum_partitions aaa 0 find_minimum_partitions ababbbabbababa 3
def find_minimum_partitions(string: str) -> int: length = len(string) cut = [0] * length is_palindromic = [[False for i in range(length)] for j in range(length)] for i, c in enumerate(string): mincut = i for j in range(i + 1): if c == string[j] and (i - j < 2 or is_palindromic[j + 1][i - 1]): is_palindromic[j][i] = True mincut = min(mincut, 0 if j == 0 else (cut[j - 1] + 1)) cut[i] = mincut return cut[length - 1] if __name__ == "__main__": s = input("Enter the string: ").strip() ans = find_minimum_partitions(s) print(f"Minimum number of partitions required for the '{s}' is {ans}")
regex matching check if a text matches pattern or not pattern matches any single character matches zero or more of the preceding element more info https medium comtricktheinterviwerregularexpressionmatching9972eb74c03 recursive matching algorithm time complexity o2 text pattern space complexity recursion depth is otext pattern param text text to match param pattern pattern to match return true if text matches pattern false otherwise recursivematch abc a c true recursivematch abc af c true recursivematch abc a c true recursivematch abc a cd false recursivematch aa true dynamic programming matching algorithm time complexity otext pattern space complexity otext pattern param text text to match param pattern pattern to match return true if text matches pattern false otherwise dpmatch abc a c true dpmatch abc af c true dpmatch abc a c true dpmatch abc a cd false dpmatch aa true recursive matching algorithm time complexity o 2 text pattern space complexity recursion depth is o text pattern param text text to match param pattern pattern to match return true if text matches pattern false otherwise recursive_match abc a c true recursive_match abc af c true recursive_match abc a c true recursive_match abc a c d false recursive_match aa true dynamic programming matching algorithm time complexity o text pattern space complexity o text pattern param text text to match param pattern pattern to match return true if text matches pattern false otherwise dp_match abc a c true dp_match abc af c true dp_match abc a c true dp_match abc a c d false dp_match aa true
def recursive_match(text: str, pattern: str) -> bool: if not pattern: return not text if not text: return pattern[-1] == "*" and recursive_match(text, pattern[:-2]) if text[-1] == pattern[-1] or pattern[-1] == ".": return recursive_match(text[:-1], pattern[:-1]) if pattern[-1] == "*": return recursive_match(text[:-1], pattern) or recursive_match( text, pattern[:-2] ) return False def dp_match(text: str, pattern: str) -> bool: m = len(text) n = len(pattern) dp = [[False for _ in range(n + 1)] for _ in range(m + 1)] dp[0][0] = True for j in range(1, n + 1): dp[0][j] = pattern[j - 1] == "*" and dp[0][j - 2] for i in range(1, m + 1): for j in range(1, n + 1): if pattern[j - 1] in {".", text[i - 1]}: dp[i][j] = dp[i - 1][j - 1] elif pattern[j - 1] == "*": dp[i][j] = dp[i][j - 2] if pattern[j - 2] in {".", text[i - 1]}: dp[i][j] |= dp[i - 1][j] else: dp[i][j] = False return dp[m][n] if __name__ == "__main__": import doctest doctest.testmod()
this module provides two implementations for the rodcutting problem 1 a naive recursive implementation which has an exponential runtime 2 two dynamic programming implementations which have quadratic runtime the rodcutting problem is the problem of finding the maximum possible revenue obtainable from a rod of length n given a list of prices for each integral piece of the rod the maximum revenue can thus be obtained by cutting the rod and selling the pieces separately or not cutting it at all if the price of it is the maximum obtainable solves the rodcutting problem via naively without using the benefit of dynamic programming the results is the same subproblems are solved several times leading to an exponential runtime runtime o2n arguments n int the length of the rod prices list the prices for each piece of rod pii is the price for a rod of length i returns the maximum revenue obtainable for a rod of length n given the list of prices for each piece examples naivecutrodrecursive4 1 5 8 9 10 naivecutrodrecursive10 1 5 8 9 10 17 17 20 24 30 30 constructs a topdown dynamic programming solution for the rodcutting problem via memoization this function serves as a wrapper for topdowncutrodrecursive runtime on2 arguments n int the length of the rod prices list the prices for each piece of rod pii is the price for a rod of length i note for convenience and because python s lists using 0indexing lengthmaxrev n 1 to accommodate for the revenue obtainable from a rod of length 0 returns the maximum revenue obtainable for a rod of length n given the list of prices for each piece examples topdowncutrod4 1 5 8 9 10 topdowncutrod10 1 5 8 9 10 17 17 20 24 30 30 constructs a topdown dynamic programming solution for the rodcutting problem via memoization runtime on2 arguments n int the length of the rod prices list the prices for each piece of rod pii is the price for a rod of length i maxrev list the computed maximum revenue for a piece of rod maxrevi is the maximum revenue obtainable for a rod of length i returns the maximum revenue obtainable for a rod of length n given the list of prices for each piece constructs a bottomup dynamic programming solution for the rodcutting problem runtime on2 arguments n int the maximum length of the rod prices list the prices for each piece of rod pii is the price for a rod of length i returns the maximum revenue obtainable from cutting a rod of length n given the prices for each piece of rod p examples bottomupcutrod4 1 5 8 9 10 bottomupcutrod10 1 5 8 9 10 17 17 20 24 30 30 lengthmaxrev n 1 to accommodate for the revenue obtainable from a rod of length 0 basic checks on the arguments to the rodcutting algorithms n int the length of the rod prices list the price list for each piece of rod throws valueerror if n is negative or there are fewer items in the price list than the length of the rod the best revenue comes from cutting the rod into 6 pieces each of length 1 resulting in a revenue of 6 6 36 solves the rod cutting problem via naively without using the benefit of dynamic programming the results is the same sub problems are solved several times leading to an exponential runtime runtime o 2 n arguments n int the length of the rod prices list the prices for each piece of rod p i i is the price for a rod of length i returns the maximum revenue obtainable for a rod of length n given the list of prices for each piece examples naive_cut_rod_recursive 4 1 5 8 9 10 naive_cut_rod_recursive 10 1 5 8 9 10 17 17 20 24 30 30 constructs a top down dynamic programming solution for the rod cutting problem via memoization this function serves as a wrapper for _top_down_cut_rod_recursive runtime o n 2 arguments n int the length of the rod prices list the prices for each piece of rod p i i is the price for a rod of length i note for convenience and because python s lists using 0 indexing length max_rev n 1 to accommodate for the revenue obtainable from a rod of length 0 returns the maximum revenue obtainable for a rod of length n given the list of prices for each piece examples top_down_cut_rod 4 1 5 8 9 10 top_down_cut_rod 10 1 5 8 9 10 17 17 20 24 30 30 constructs a top down dynamic programming solution for the rod cutting problem via memoization runtime o n 2 arguments n int the length of the rod prices list the prices for each piece of rod p i i is the price for a rod of length i max_rev list the computed maximum revenue for a piece of rod max_rev i is the maximum revenue obtainable for a rod of length i returns the maximum revenue obtainable for a rod of length n given the list of prices for each piece constructs a bottom up dynamic programming solution for the rod cutting problem runtime o n 2 arguments n int the maximum length of the rod prices list the prices for each piece of rod p i i is the price for a rod of length i returns the maximum revenue obtainable from cutting a rod of length n given the prices for each piece of rod p examples bottom_up_cut_rod 4 1 5 8 9 10 bottom_up_cut_rod 10 1 5 8 9 10 17 17 20 24 30 30 length max_rev n 1 to accommodate for the revenue obtainable from a rod of length 0 basic checks on the arguments to the rod cutting algorithms n int the length of the rod prices list the price list for each piece of rod throws valueerror if n is negative or there are fewer items in the price list than the length of the rod the best revenue comes from cutting the rod into 6 pieces each of length 1 resulting in a revenue of 6 6 36
def naive_cut_rod_recursive(n: int, prices: list): _enforce_args(n, prices) if n == 0: return 0 max_revue = float("-inf") for i in range(1, n + 1): max_revue = max( max_revue, prices[i - 1] + naive_cut_rod_recursive(n - i, prices) ) return max_revue def top_down_cut_rod(n: int, prices: list): _enforce_args(n, prices) max_rev = [float("-inf") for _ in range(n + 1)] return _top_down_cut_rod_recursive(n, prices, max_rev) def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list): if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: max_revenue = float("-inf") for i in range(1, n + 1): max_revenue = max( max_revenue, prices[i - 1] + _top_down_cut_rod_recursive(n - i, prices, max_rev), ) max_rev[n] = max_revenue return max_rev[n] def bottom_up_cut_rod(n: int, prices: list): _enforce_args(n, prices) max_rev = [float("-inf") for _ in range(n + 1)] max_rev[0] = 0 for i in range(1, n + 1): max_revenue_i = max_rev[i] for j in range(1, i + 1): max_revenue_i = max(max_revenue_i, prices[j - 1] + max_rev[i - j]) max_rev[i] = max_revenue_i return max_rev[n] def _enforce_args(n: int, prices: list): if n < 0: msg = f"n must be greater than or equal to 0. Got n = {n}" raise ValueError(msg) if n > len(prices): msg = ( "Each integral piece of rod must have a corresponding price. " f"Got n = {n} but length of prices = {len(prices)}" ) raise ValueError(msg) def main(): prices = [6, 10, 12, 15, 20, 23] n = len(prices) expected_max_revenue = 36 max_rev_top_down = top_down_cut_rod(n, prices) max_rev_bottom_up = bottom_up_cut_rod(n, prices) max_rev_naive = naive_cut_rod_recursive(n, prices) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
https en wikipedia orgwikismithe28093watermanalgorithm the smithwaterman algorithm is a dynamic programming algorithm used for sequence alignment it is particularly useful for finding similarities between two sequences such as dna or protein sequences in this implementation gaps are penalized linearly meaning that the score is reduced by a fixed amount for each gap introduced in the alignment however it s important to note that the smithwaterman algorithm supports other gap penalty methods as well calculate the score for a character pair based on whether they match or mismatch returns 1 if the characters match 1 if they mismatch and 2 if either of the characters is a gap scorefunction a a 1 scorefunction a c 1 scorefunction a 2 scorefunction a 2 scorefunction 2 perform the smithwaterman local sequence alignment algorithm returns a 2d list representing the score matrix each value in the matrix corresponds to the score of the best local alignment ending at that point smithwaterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smithwaterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smithwaterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smithwaterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smithwaterman acac 0 0 0 0 0 smithwaterman ca 0 0 0 smithwaterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smithwaterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smithwaterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smithwaterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smithwaterman acac 0 0 0 0 0 smithwaterman ca 0 0 0 smithwaterman agt agt 0 0 0 0 0 1 0 0 0 0 2 0 0 0 0 3 smithwaterman agt gta 0 0 0 0 0 0 0 1 0 1 0 0 0 0 2 0 smithwaterman agt gtc 0 0 0 0 0 0 0 0 0 1 0 0 0 0 2 0 smithwaterman agt g 0 0 0 0 0 1 0 0 smithwaterman g agt 0 0 0 0 0 0 1 0 smithwaterman agt agtct 0 0 0 0 0 0 0 1 0 0 0 0 0 0 2 0 0 0 0 0 0 3 1 1 smithwaterman agtct agt 0 0 0 0 0 1 0 0 0 0 2 0 0 0 0 3 0 0 0 1 0 0 0 1 smithwaterman agtct gtc 0 0 0 0 0 0 0 0 0 1 0 0 0 0 2 0 0 0 0 3 0 0 1 1 make both query and subject uppercase initialize score matrix calculate scores for each cell take maximum score make both query and subject uppercase query query upper subject subject upper find the indices of the maximum value in the score matrix maxvalue floatinf imax jmax 0 for i row in enumeratescore for j value in enumeraterow if value maxvalue maxvalue value imax jmax i j traceback logic to find optimal alignment i imax j jmax align1 align2 gap scorefunction guard against empty query or subject if i 0 or j 0 return while i 0 and j 0 if scoreij scorei 1j 1 scorefunction queryi 1 subjectj 1 optimal path is a diagonal take both letters align1 queryi 1 align1 align2 subjectj 1 align2 i 1 j 1 elif scoreij scorei 1j gap optimal path is a vertical align1 queryi 1 align1 align2 falign2 i 1 else optimal path is a horizontal align1 falign1 align2 subjectj 1 align2 j 1 return falign1nalign2 if name main query heagawghee subject pawheae score smithwatermanquery subject match1 mismatch1 gap2 printtracebackscore query subject calculate the score for a character pair based on whether they match or mismatch returns 1 if the characters match 1 if they mismatch and 2 if either of the characters is a gap score_function a a 1 score_function a c 1 score_function a 2 score_function a 2 score_function 2 perform the smith waterman local sequence alignment algorithm returns a 2d list representing the score matrix each value in the matrix corresponds to the score of the best local alignment ending at that point smith_waterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smith_waterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smith_waterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smith_waterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smith_waterman acac 0 0 0 0 0 smith_waterman ca 0 0 0 smith_waterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smith_waterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smith_waterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smith_waterman acac ca 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 smith_waterman acac 0 0 0 0 0 smith_waterman ca 0 0 0 smith_waterman agt agt 0 0 0 0 0 1 0 0 0 0 2 0 0 0 0 3 smith_waterman agt gta 0 0 0 0 0 0 0 1 0 1 0 0 0 0 2 0 smith_waterman agt gtc 0 0 0 0 0 0 0 0 0 1 0 0 0 0 2 0 smith_waterman agt g 0 0 0 0 0 1 0 0 smith_waterman g agt 0 0 0 0 0 0 1 0 smith_waterman agt agtct 0 0 0 0 0 0 0 1 0 0 0 0 0 0 2 0 0 0 0 0 0 3 1 1 smith_waterman agtct agt 0 0 0 0 0 1 0 0 0 0 2 0 0 0 0 3 0 0 0 1 0 0 0 1 smith_waterman agtct gtc 0 0 0 0 0 0 0 0 0 1 0 0 0 0 2 0 0 0 0 3 0 0 1 1 make both query and subject uppercase initialize score matrix calculate scores for each cell take maximum score perform traceback to find the optimal local alignment starts from the highest scoring cell in the matrix and traces back recursively until a 0 score is found returns the alignment strings traceback 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 acac ca ca nca traceback 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 acac ca ca nca traceback 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 acac ca ca nca traceback 0 0 0 0 0 1 0 1 0 0 0 2 0 1 0 acac ca ca nca traceback 0 0 0 acac make both query and subject uppercase find the indices of the maximum value in the score matrix traceback logic to find optimal alignment guard against empty query or subject optimal path is a diagonal take both letters optimal path is a vertical optimal path is a horizontal
def score_function( source_char: str, target_char: str, match: int = 1, mismatch: int = -1, gap: int = -2, ) -> int: if "-" in (source_char, target_char): return gap return match if source_char == target_char else mismatch def smith_waterman( query: str, subject: str, match: int = 1, mismatch: int = -1, gap: int = -2, ) -> list[list[int]]: query = query.upper() subject = subject.upper() m = len(query) n = len(subject) score = [[0] * (n + 1) for _ in range(m + 1)] kwargs = {"match": match, "mismatch": mismatch, "gap": gap} for i in range(1, m + 1): for j in range(1, n + 1): match = score[i - 1][j - 1] + score_function( query[i - 1], subject[j - 1], **kwargs ) delete = score[i - 1][j] + gap insert = score[i][j - 1] + gap score[i][j] = max(0, match, delete, insert) return score def traceback(score: list[list[int]], query: str, subject: str) -> str: r query = query.upper() subject = subject.upper() max_value = float("-inf") i_max = j_max = 0 for i, row in enumerate(score): for j, value in enumerate(row): if value > max_value: max_value = value i_max, j_max = i, j i = i_max j = j_max align1 = "" align2 = "" gap = score_function("-", "-") if i == 0 or j == 0: return "" while i > 0 and j > 0: if score[i][j] == score[i - 1][j - 1] + score_function( query[i - 1], subject[j - 1] ): align1 = query[i - 1] + align1 align2 = subject[j - 1] + align2 i -= 1 j -= 1 elif score[i][j] == score[i - 1][j] + gap: align1 = query[i - 1] + align1 align2 = f"-{align2}" i -= 1 else: align1 = f"-{align1}" align2 = subject[j - 1] + align2 j -= 1 return f"{align1}\n{align2}" if __name__ == "__main__": query = "HEAGAWGHEE" subject = "PAWHEAE" score = smith_waterman(query, subject, match=1, mismatch=-1, gap=-2) print(traceback(score, query, subject))
compute nelement combinations from a given list using dynamic programming args elements the list of elements from which combinations will be generated n the number of elements in each combination returns a list of tuples each representing a combination of n elements subsetcombinationselements10 20 30 40 n2 10 20 10 30 10 40 20 30 20 40 30 40 subsetcombinationselements1 2 3 n1 1 2 3 subsetcombinationselements1 2 3 n3 1 2 3 subsetcombinationselements42 n1 42 subsetcombinationselements6 7 8 9 n4 6 7 8 9 subsetcombinationselements10 20 30 40 50 n0 subsetcombinationselements1 2 3 4 n2 1 2 1 3 1 4 2 3 2 4 3 4 subsetcombinationselements1 apple 3 14 n2 1 apple 1 3 14 apple 3 14 subsetcombinationselements single n0 subsetcombinationselements n9 from itertools import combinations allsubsetcombinationsitems n listcombinationsitems n for items n in 10 20 30 40 2 1 2 3 1 1 2 3 3 42 1 6 7 8 9 4 10 20 30 40 50 1 1 2 3 4 2 1 apple 3 14 2 single 0 9 true compute n element combinations from a given list using dynamic programming args elements the list of elements from which combinations will be generated n the number of elements in each combination returns a list of tuples each representing a combination of n elements subset_combinations elements 10 20 30 40 n 2 10 20 10 30 10 40 20 30 20 40 30 40 subset_combinations elements 1 2 3 n 1 1 2 3 subset_combinations elements 1 2 3 n 3 1 2 3 subset_combinations elements 42 n 1 42 subset_combinations elements 6 7 8 9 n 4 6 7 8 9 subset_combinations elements 10 20 30 40 50 n 0 subset_combinations elements 1 2 3 4 n 2 1 2 1 3 1 4 2 3 2 4 3 4 subset_combinations elements 1 apple 3 14 n 2 1 apple 1 3 14 apple 3 14 subset_combinations elements single n 0 subset_combinations elements n 9 from itertools import combinations all subset_combinations items n list combinations items n for items n in 10 20 30 40 2 1 2 3 1 1 2 3 3 42 1 6 7 8 9 4 10 20 30 40 50 1 1 2 3 4 2 1 apple 3 14 2 single 0 9 true
def subset_combinations(elements: list[int], n: int) -> list: r = len(elements) if n > r: return [] dp: list[list[tuple]] = [[] for _ in range(r + 1)] dp[0].append(()) for i in range(1, r + 1): for j in range(i, 0, -1): for prev_combination in dp[j - 1]: dp[j].append(tuple(prev_combination) + (elements[i - 1],)) try: return sorted(dp[n]) except TypeError: return dp[n] if __name__ == "__main__": from doctest import testmod testmod() print(f"{subset_combinations(elements=[10, 20, 30, 40], n=2) = }")
issumsubset2 4 6 8 5 false issumsubset2 4 6 8 14 true a subset value says 1 if that subset sum can be formed else 0 initially no subsets can be formed hence false0 for each arr value a sum of zero0 can be formed by not taking any element hence true1 sum is not zero and set is empty then false is_sum_subset 2 4 6 8 5 false is_sum_subset 2 4 6 8 14 true a subset value says 1 if that subset sum can be formed else 0 initially no subsets can be formed hence false 0 for each arr value a sum of zero 0 can be formed by not taking any element hence true 1 sum is not zero and set is empty then false
def is_sum_subset(arr: list[int], required_sum: int) -> bool: arr_len = len(arr) subset = [[False] * (required_sum + 1) for _ in range(arr_len + 1)] for i in range(arr_len + 1): subset[i][0] = True for i in range(1, required_sum + 1): subset[0][i] = False for i in range(1, arr_len + 1): for j in range(1, required_sum + 1): if arr[i - 1] > j: subset[i][j] = subset[i - 1][j] if arr[i - 1] <= j: subset[i][j] = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
given an array of nonnegative integers representing an elevation map where the width of each bar is 1 this program calculates how much rainwater can be trapped example height 0 1 0 2 1 0 1 3 2 1 2 1 output 6 this problem can be solved using the concept of dynamic programming we calculate the maximum height of bars on the left and right of every bar in array then iterate over the width of structure and at each index the amount of water that will be stored is equal to minimum of maximum height of bars on both sides minus height of bar at current position the trappedrainwater function calculates the total amount of rainwater that can be trapped given an array of bar heights it uses a dynamic programming approach determining the maximum height of bars on both sides for each bar and then computing the trapped water above each bar the function returns the total trapped water trappedrainwater0 1 0 2 1 0 1 3 2 1 2 1 6 trappedrainwater7 1 5 3 6 4 9 trappedrainwater7 1 5 3 6 1 traceback most recent call last valueerror no height can be negative the trapped_rainwater function calculates the total amount of rainwater that can be trapped given an array of bar heights it uses a dynamic programming approach determining the maximum height of bars on both sides for each bar and then computing the trapped water above each bar the function returns the total trapped water trapped_rainwater 0 1 0 2 1 0 1 3 2 1 2 1 6 trapped_rainwater 7 1 5 3 6 4 9 trapped_rainwater 7 1 5 3 6 1 traceback most recent call last valueerror no height can be negative
def trapped_rainwater(heights: tuple[int, ...]) -> int: if not heights: return 0 if any(h < 0 for h in heights): raise ValueError("No height can be negative") length = len(heights) left_max = [0] * length left_max[0] = heights[0] for i, height in enumerate(heights[1:], start=1): left_max[i] = max(height, left_max[i - 1]) right_max = [0] * length right_max[-1] = heights[-1] for i in range(length - 2, -1, -1): right_max[i] = max(heights[i], right_max[i + 1]) return sum( min(left, right) - height for left, right, height in zip(left_max, right_max, heights) ) if __name__ == "__main__": import doctest doctest.testmod() print(f"{trapped_rainwater((0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1)) = }") print(f"{trapped_rainwater((7, 1, 5, 3, 6, 4)) = }")
tribonacci sequence using dynamic programming given a number return first n tribonacci numbers tribonacci5 0 0 1 1 2 tribonacci8 0 0 1 1 2 4 7 13 tribonacci sequence using dynamic programming given a number return first n tribonacci numbers tribonacci 5 0 0 1 1 2 tribonacci 8 0 0 1 1 2 4 7 13
def tribonacci(num: int) -> list[int]: dp = [0] * num dp[2] = 1 for i in range(3, num): dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] return dp if __name__ == "__main__": import doctest doctest.testmod()
viterbi algorithm to find the most likely path of states from the start and the expected output https en wikipedia orgwikiviterbialgorithm sdafads wikipedia example observations normal cold dizzy states healthy fever startp healthy 0 6 fever 0 4 transp healthy healthy 0 7 fever 0 3 fever healthy 0 4 fever 0 6 emitp healthy normal 0 5 cold 0 4 dizzy 0 1 fever normal 0 1 cold 0 3 dizzy 0 6 viterbiobservations states startp transp emitp healthy healthy fever viterbi states startp transp emitp traceback most recent call last valueerror there s an empty parameter viterbiobservations startp transp emitp traceback most recent call last valueerror there s an empty parameter viterbiobservations states transp emitp traceback most recent call last valueerror there s an empty parameter viterbiobservations states startp emitp traceback most recent call last valueerror there s an empty parameter viterbiobservations states startp transp traceback most recent call last valueerror there s an empty parameter viterbiinvalid states startp transp emitp traceback most recent call last valueerror observationsspace must be a list viterbivalid 123 states startp transp emitp traceback most recent call last valueerror observationsspace must be a list of strings viterbiobservations invalid startp transp emitp traceback most recent call last valueerror statesspace must be a list viterbiobservations valid 123 startp transp emitp traceback most recent call last valueerror statesspace must be a list of strings viterbiobservations states invalid transp emitp traceback most recent call last valueerror initialprobabilities must be a dict viterbiobservations states 2 2 transp emitp traceback most recent call last valueerror initialprobabilities all keys must be strings viterbiobservations states a 2 transp emitp traceback most recent call last valueerror initialprobabilities all values must be float viterbiobservations states startp invalid emitp traceback most recent call last valueerror transitionprobabilities must be a dict viterbiobservations states startp a 2 emitp traceback most recent call last valueerror transitionprobabilities all values must be dict viterbiobservations states startp 2 2 2 emitp traceback most recent call last valueerror transitionprobabilities all keys must be strings viterbiobservations states startp a 2 2 emitp traceback most recent call last valueerror transitionprobabilities all keys must be strings viterbiobservations states startp a b 2 emitp traceback most recent call last valueerror transitionprobabilities nested dictionary all values must be float viterbiobservations states startp transp invalid traceback most recent call last valueerror emissionprobabilities must be a dict viterbiobservations states startp transp none traceback most recent call last valueerror there s an empty parameter creates data structures and fill initial step fills the data structure with the probabilities of different transitions and pointers to previous states calculates the argmax for probability function update probabilities and pointers dicts the final observation argmax for given final observation process pointers backwards observations normal cold dizzy states healthy fever startp healthy 0 6 fever 0 4 transp healthy healthy 0 7 fever 0 3 fever healthy 0 4 fever 0 6 emitp healthy normal 0 5 cold 0 4 dizzy 0 1 fever normal 0 1 cold 0 3 dizzy 0 6 validationobservations states startp transp emitp validation states startp transp emitp traceback most recent call last valueerror there s an empty parameter validatenotemptya b c 0 5 d e 0 6 f g 0 7 validatenotemptya b c 0 5 f g 0 7 traceback most recent call last valueerror there s an empty parameter validatenotemptya b none d e 0 6 f g 0 7 traceback most recent call last valueerror there s an empty parameter validatelistsa b validatelists1234 b traceback most recent call last valueerror observationsspace must be a list validatelistsa 3 traceback most recent call last valueerror statesspace must be a list of strings validatelista mockname validatelista mockname traceback most recent call last valueerror mockname must be a list validatelist0 5 mockname traceback most recent call last valueerror mockname must be a list of strings validatedictsc 0 5 d e 0 6 f g 0 7 validatedictsinvalid d e 0 6 f g 0 7 traceback most recent call last valueerror initialprobabilities must be a dict validatedictsc 0 5 2 e 0 6 f g 0 7 traceback most recent call last valueerror transitionprobabilities all keys must be strings validatedictsc 0 5 d e 0 6 f 2 0 7 traceback most recent call last valueerror emissionprobabilities all keys must be strings validatedictsc 0 5 d e 0 6 f g h traceback most recent call last valueerror emissionprobabilities nested dictionary all values must be float validatenesteddicta b 0 5 mockname validatenesteddictinvalid mockname traceback most recent call last valueerror mockname must be a dict validatenesteddicta 8 mockname traceback most recent call last valueerror mockname all values must be dict validatenesteddicta 2 0 5 mockname traceback most recent call last valueerror mockname all keys must be strings validatenesteddicta b 4 mockname traceback most recent call last valueerror mockname nested dictionary all values must be float validatedictb 0 5 mockname float validatedictinvalid mockname float traceback most recent call last valueerror mockname must be a dict validatedicta 8 mockname dict traceback most recent call last valueerror mockname all values must be dict validatedict2 0 5 mockname float true traceback most recent call last valueerror mockname all keys must be strings validatedictb 4 mockname float true traceback most recent call last valueerror mockname nested dictionary all values must be float viterbi algorithm to find the most likely path of states from the start and the expected output https en wikipedia org wiki viterbi_algorithm sdafads wikipedia example observations normal cold dizzy states healthy fever start_p healthy 0 6 fever 0 4 trans_p healthy healthy 0 7 fever 0 3 fever healthy 0 4 fever 0 6 emit_p healthy normal 0 5 cold 0 4 dizzy 0 1 fever normal 0 1 cold 0 3 dizzy 0 6 viterbi observations states start_p trans_p emit_p healthy healthy fever viterbi states start_p trans_p emit_p traceback most recent call last valueerror there s an empty parameter viterbi observations start_p trans_p emit_p traceback most recent call last valueerror there s an empty parameter viterbi observations states trans_p emit_p traceback most recent call last valueerror there s an empty parameter viterbi observations states start_p emit_p traceback most recent call last valueerror there s an empty parameter viterbi observations states start_p trans_p traceback most recent call last valueerror there s an empty parameter viterbi invalid states start_p trans_p emit_p traceback most recent call last valueerror observations_space must be a list viterbi valid 123 states start_p trans_p emit_p traceback most recent call last valueerror observations_space must be a list of strings viterbi observations invalid start_p trans_p emit_p traceback most recent call last valueerror states_space must be a list viterbi observations valid 123 start_p trans_p emit_p traceback most recent call last valueerror states_space must be a list of strings viterbi observations states invalid trans_p emit_p traceback most recent call last valueerror initial_probabilities must be a dict viterbi observations states 2 2 trans_p emit_p traceback most recent call last valueerror initial_probabilities all keys must be strings viterbi observations states a 2 trans_p emit_p traceback most recent call last valueerror initial_probabilities all values must be float viterbi observations states start_p invalid emit_p traceback most recent call last valueerror transition_probabilities must be a dict viterbi observations states start_p a 2 emit_p traceback most recent call last valueerror transition_probabilities all values must be dict viterbi observations states start_p 2 2 2 emit_p traceback most recent call last valueerror transition_probabilities all keys must be strings viterbi observations states start_p a 2 2 emit_p traceback most recent call last valueerror transition_probabilities all keys must be strings viterbi observations states start_p a b 2 emit_p traceback most recent call last valueerror transition_probabilities nested dictionary all values must be float viterbi observations states start_p trans_p invalid traceback most recent call last valueerror emission_probabilities must be a dict viterbi observations states start_p trans_p none traceback most recent call last valueerror there s an empty parameter creates data structures and fill initial step fills the data structure with the probabilities of different transitions and pointers to previous states calculates the argmax for probability function update probabilities and pointers dicts the final observation argmax for given final observation process pointers backwards observations normal cold dizzy states healthy fever start_p healthy 0 6 fever 0 4 trans_p healthy healthy 0 7 fever 0 3 fever healthy 0 4 fever 0 6 emit_p healthy normal 0 5 cold 0 4 dizzy 0 1 fever normal 0 1 cold 0 3 dizzy 0 6 _validation observations states start_p trans_p emit_p _validation states start_p trans_p emit_p traceback most recent call last valueerror there s an empty parameter _validate_not_empty a b c 0 5 d e 0 6 f g 0 7 _validate_not_empty a b c 0 5 f g 0 7 traceback most recent call last valueerror there s an empty parameter _validate_not_empty a b none d e 0 6 f g 0 7 traceback most recent call last valueerror there s an empty parameter _validate_lists a b _validate_lists 1234 b traceback most recent call last valueerror observations_space must be a list _validate_lists a 3 traceback most recent call last valueerror states_space must be a list of strings _validate_list a mock_name _validate_list a mock_name traceback most recent call last valueerror mock_name must be a list _validate_list 0 5 mock_name traceback most recent call last valueerror mock_name must be a list of strings _validate_dicts c 0 5 d e 0 6 f g 0 7 _validate_dicts invalid d e 0 6 f g 0 7 traceback most recent call last valueerror initial_probabilities must be a dict _validate_dicts c 0 5 2 e 0 6 f g 0 7 traceback most recent call last valueerror transition_probabilities all keys must be strings _validate_dicts c 0 5 d e 0 6 f 2 0 7 traceback most recent call last valueerror emission_probabilities all keys must be strings _validate_dicts c 0 5 d e 0 6 f g h traceback most recent call last valueerror emission_probabilities nested dictionary all values must be float _validate_nested_dict a b 0 5 mock_name _validate_nested_dict invalid mock_name traceback most recent call last valueerror mock_name must be a dict _validate_nested_dict a 8 mock_name traceback most recent call last valueerror mock_name all values must be dict _validate_nested_dict a 2 0 5 mock_name traceback most recent call last valueerror mock_name all keys must be strings _validate_nested_dict a b 4 mock_name traceback most recent call last valueerror mock_name nested dictionary all values must be float _validate_dict b 0 5 mock_name float _validate_dict invalid mock_name float traceback most recent call last valueerror mock_name must be a dict _validate_dict a 8 mock_name dict traceback most recent call last valueerror mock_name all values must be dict _validate_dict 2 0 5 mock_name float true traceback most recent call last valueerror mock_name all keys must be strings _validate_dict b 4 mock_name float true traceback most recent call last valueerror mock_name nested dictionary all values must be float
from typing import Any def viterbi( observations_space: list, states_space: list, initial_probabilities: dict, transition_probabilities: dict, emission_probabilities: dict, ) -> list: _validation( observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ) probabilities: dict = {} pointers: dict = {} for state in states_space: observation = observations_space[0] probabilities[(state, observation)] = ( initial_probabilities[state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = None for o in range(1, len(observations_space)): observation = observations_space[o] prior_observation = observations_space[o - 1] for state in states_space: arg_max = "" max_probability = -1 for k_state in states_space: probability = ( probabilities[(k_state, prior_observation)] * transition_probabilities[k_state][state] * emission_probabilities[state][observation] ) if probability > max_probability: max_probability = probability arg_max = k_state probabilities[(state, observation)] = ( probabilities[(arg_max, prior_observation)] * transition_probabilities[arg_max][state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = arg_max final_observation = observations_space[len(observations_space) - 1] arg_max = "" max_probability = -1 for k_state in states_space: probability = probabilities[(k_state, final_observation)] if probability > max_probability: max_probability = probability arg_max = k_state last_state = arg_max previous = last_state result = [] for o in range(len(observations_space) - 1, -1, -1): result.append(previous) previous = pointers[previous, observations_space[o]] result.reverse() return result def _validation( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: _validate_not_empty( observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ) _validate_lists(observations_space, states_space) _validate_dicts( initial_probabilities, transition_probabilities, emission_probabilities ) def _validate_not_empty( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: if not all( [ observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ] ): raise ValueError("There's an empty parameter") def _validate_lists(observations_space: Any, states_space: Any) -> None: _validate_list(observations_space, "observations_space") _validate_list(states_space, "states_space") def _validate_list(_object: Any, var_name: str) -> None: if not isinstance(_object, list): msg = f"{var_name} must be a list" raise ValueError(msg) else: for x in _object: if not isinstance(x, str): msg = f"{var_name} must be a list of strings" raise ValueError(msg) def _validate_dicts( initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: _validate_dict(initial_probabilities, "initial_probabilities", float) _validate_nested_dict(transition_probabilities, "transition_probabilities") _validate_nested_dict(emission_probabilities, "emission_probabilities") def _validate_nested_dict(_object: Any, var_name: str) -> None: _validate_dict(_object, var_name, dict) for x in _object.values(): _validate_dict(x, var_name, float, True) def _validate_dict( _object: Any, var_name: str, value_type: type, nested: bool = False ) -> None: if not isinstance(_object, dict): msg = f"{var_name} must be a dict" raise ValueError(msg) if not all(isinstance(x, str) for x in _object): msg = f"{var_name} all keys must be strings" raise ValueError(msg) if not all(isinstance(x, value_type) for x in _object.values()): nested_text = "nested dictionary " if nested else "" msg = f"{var_name} {nested_text}all values must be {value_type.__name__}" raise ValueError(msg) if __name__ == "__main__": from doctest import testmod testmod()
ilyas dahhou date oct 7 2023 task given an input string and a pattern implement wildcard pattern matching with support for and where matches any single character matches any sequence of characters including the empty sequence the matching should cover the entire input string not partial runtime complexity om n the implementation was tested on the leetcode https leetcode comproblemswildcardmatching ismatch true ismatchaa a false ismatchabc abc true ismatchabc c true ismatchabc a true ismatchabc a true ismatchabc b true ismatchabc true ismatchabc ad false ismatchabc ac false ismatch baaabab baba false ismatch baaabab baab true ismatch aa true fill in the first row fill in the rest of the dp table is_match true is_match aa a false is_match abc abc true is_match abc c true is_match abc a true is_match abc a true is_match abc b true is_match abc true is_match abc a d false is_match abc a c false is_match baaabab ba ba false is_match baaabab ba ab true is_match aa true fill in the first row fill in the rest of the dp table
def is_match(string: str, pattern: str) -> bool: dp = [[False] * (len(pattern) + 1) for _ in string + "1"] dp[0][0] = True for j, char in enumerate(pattern, 1): if char == "*": dp[0][j] = dp[0][j - 1] for i, s_char in enumerate(string, 1): for j, p_char in enumerate(pattern, 1): if p_char in (s_char, "?"): dp[i][j] = dp[i - 1][j - 1] elif pattern[j - 1] == "*": dp[i][j] = dp[i - 1][j] or dp[i][j - 1] return dp[len(string)][len(pattern)] if __name__ == "__main__": import doctest doctest.testmod() print(f"{is_match('baaabab','*****ba*****ab') = }")
alexander pantyukhin date december 12 2022 task given a string and a list of words return true if the string can be segmented into a spaceseparated sequence of one or more words note that the same word may be reused multiple times in the segmentation implementation notes trie dynamic programming up down the trie will be used to store the words it will be useful for scanning available words for the current position in the string leetcode https leetcode comproblemswordbreakdescription runtime on n space on return true if numbers have opposite signs false otherwise wordbreakapplepenapple apple pen true wordbreakcatsandog cats dog sand and cat false wordbreakcars car ca rs true wordbreak abc false wordbreak123 a traceback most recent call last valueerror the string should be not empty string wordbreak a traceback most recent call last valueerror the string should be not empty string wordbreak abc 123 traceback most recent call last valueerror the words should be a list of nonempty strings wordbreak abc traceback most recent call last valueerror the words should be a list of nonempty strings validation build trie dynamic programming method string a isbreakable1 true return true if numbers have opposite signs false otherwise word_break applepenapple apple pen true word_break catsandog cats dog sand and cat false word_break cars car ca rs true word_break abc false word_break 123 a traceback most recent call last valueerror the string should be not empty string word_break a traceback most recent call last valueerror the string should be not empty string word_break abc 123 traceback most recent call last valueerror the words should be a list of non empty strings word_break abc traceback most recent call last valueerror the words should be a list of non empty strings validation build trie dynamic programming method string a is_breakable 1 true
import functools from typing import Any def word_break(string: str, words: list[str]) -> bool: if not isinstance(string, str) or len(string) == 0: raise ValueError("the string should be not empty string") if not isinstance(words, list) or not all( isinstance(item, str) and len(item) > 0 for item in words ): raise ValueError("the words should be a list of non-empty strings") trie: dict[str, Any] = {} word_keeper_key = "WORD_KEEPER" for word in words: trie_node = trie for c in word: if c not in trie_node: trie_node[c] = {} trie_node = trie_node[c] trie_node[word_keeper_key] = True len_string = len(string) @functools.cache def is_breakable(index: int) -> bool: if index == len_string: return True trie_node = trie for i in range(index, len_string): trie_node = trie_node.get(string[i], None) if trie_node is None: return False if trie_node.get(word_keeper_key, False) and is_breakable(i + 1): return True return False return is_breakable(0) if __name__ == "__main__": import doctest doctest.testmod()
calculate the apparent power in a singlephase ac circuit reference https en wikipedia orgwikiacpowerapparentpower apparentpower100 5 0 0 5000j apparentpower100 5 90 0 3 061616997868383e14500j apparentpower100 5 45 60 129 40952255126027482 9629131445341j apparentpower200 10 30 90 999 99999999999981732 0508075688776j convert angles from degrees to radians convert voltage and current to rectangular form calculate apparent power calculate the apparent power in a single phase ac circuit reference https en wikipedia org wiki ac_power apparent_power apparent_power 100 5 0 0 500 0j apparent_power 100 5 90 0 3 061616997868383e 14 500j apparent_power 100 5 45 60 129 40952255126027 482 9629131445341j apparent_power 200 10 30 90 999 9999999999998 1732 0508075688776j convert angles from degrees to radians convert voltage and current to rectangular form calculate apparent power
import cmath import math def apparent_power( voltage: float, current: float, voltage_angle: float, current_angle: float ) -> complex: voltage_angle_rad = math.radians(voltage_angle) current_angle_rad = math.radians(current_angle) voltage_rect = cmath.rect(voltage, voltage_angle_rad) current_rect = cmath.rect(current, current_angle_rad) return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
this function can calculate the builtin voltage of a pn junction diode this is calculated from the given three values examples builtinvoltagedonorconc1e17 acceptorconc1e17 intrinsicconc1e10 0 833370010652644 builtinvoltagedonorconc0 acceptorconc1600 intrinsicconc200 traceback most recent call last valueerror donor concentration should be positive builtinvoltagedonorconc1000 acceptorconc0 intrinsicconc1200 traceback most recent call last valueerror acceptor concentration should be positive builtinvoltagedonorconc1000 acceptorconc1000 intrinsicconc0 traceback most recent call last valueerror intrinsic concentration should be positive builtinvoltagedonorconc1000 acceptorconc3000 intrinsicconc2000 traceback most recent call last valueerror donor concentration should be greater than intrinsic concentration builtinvoltagedonorconc3000 acceptorconc1000 intrinsicconc2000 traceback most recent call last valueerror acceptor concentration should be greater than intrinsic concentration temperature unit k donor concentration acceptor concentration intrinsic concentration this function can calculate the builtin voltage of a pn junction diode this is calculated from the given three values examples builtin_voltage donor_conc 1e17 acceptor_conc 1e17 intrinsic_conc 1e10 0 833370010652644 builtin_voltage donor_conc 0 acceptor_conc 1600 intrinsic_conc 200 traceback most recent call last valueerror donor concentration should be positive builtin_voltage donor_conc 1000 acceptor_conc 0 intrinsic_conc 1200 traceback most recent call last valueerror acceptor concentration should be positive builtin_voltage donor_conc 1000 acceptor_conc 1000 intrinsic_conc 0 traceback most recent call last valueerror intrinsic concentration should be positive builtin_voltage donor_conc 1000 acceptor_conc 3000 intrinsic_conc 2000 traceback most recent call last valueerror donor concentration should be greater than intrinsic concentration builtin_voltage donor_conc 3000 acceptor_conc 1000 intrinsic_conc 2000 traceback most recent call last valueerror acceptor concentration should be greater than intrinsic concentration
from math import log from scipy.constants import Boltzmann, physical_constants T = 300 def builtin_voltage( donor_conc: float, acceptor_conc: float, intrinsic_conc: float, ) -> float: if donor_conc <= 0: raise ValueError("Donor concentration should be positive") elif acceptor_conc <= 0: raise ValueError("Acceptor concentration should be positive") elif intrinsic_conc <= 0: raise ValueError("Intrinsic concentration should be positive") elif donor_conc <= intrinsic_conc: raise ValueError( "Donor concentration should be greater than intrinsic concentration" ) elif acceptor_conc <= intrinsic_conc: raise ValueError( "Acceptor concentration should be greater than intrinsic concentration" ) else: return ( Boltzmann * T * log((donor_conc * acceptor_conc) / intrinsic_conc**2) / physical_constants["electron volt"][0] ) if __name__ == "__main__": import doctest doctest.testmod()
https farside ph utexas eduteaching316lecturesnode46 html ceq c1 c2 cn calculate the equivalent resistance for any number of capacitors in parallel capacitorparallel5 71389 12 3 20 71389 capacitorparallel5 71389 12 3 traceback most recent call last valueerror capacitor at index 2 has a negative value ceq 1 1c1 1c2 1cn capacitorseries5 71389 12 3 1 6901062252507735 capacitorseries5 71389 12 3 traceback most recent call last valueerror capacitor at index 2 has a negative or zero value capacitorseries5 71389 12 0 000 traceback most recent call last valueerror capacitor at index 2 has a negative or zero value https farside ph utexas edu teaching 316 lectures node46 html ceq c1 c2 cn calculate the equivalent resistance for any number of capacitors in parallel capacitor_parallel 5 71389 12 3 20 71389 capacitor_parallel 5 71389 12 3 traceback most recent call last valueerror capacitor at index 2 has a negative value ceq 1 1 c1 1 c2 1 cn capacitor_series 5 71389 12 3 1 6901062252507735 capacitor_series 5 71389 12 3 traceback most recent call last valueerror capacitor at index 2 has a negative or zero value capacitor_series 5 71389 12 0 000 traceback most recent call last valueerror capacitor at index 2 has a negative or zero value
from __future__ import annotations def capacitor_parallel(capacitors: list[float]) -> float: sum_c = 0.0 for index, capacitor in enumerate(capacitors): if capacitor < 0: msg = f"Capacitor at index {index} has a negative value!" raise ValueError(msg) sum_c += capacitor return sum_c def capacitor_series(capacitors: list[float]) -> float: first_sum = 0.0 for index, capacitor in enumerate(capacitors): if capacitor <= 0: msg = f"Capacitor at index {index} has a negative or zero value!" raise ValueError(msg) first_sum += 1 / capacitor return 1 / first_sum if __name__ == "__main__": import doctest doctest.testmod()
https en wikipedia orgwikichargecarrierdensity https www pveducation orgpvcdrompnjunctionsequilibriumcarrierconcentration http www ece utep educoursesee3329ee3329studyguidetocfundamentalscarriersconcentrations html this function can calculate any one of the three 1 electron concentration 2 hole concentration 3 intrinsic concentration given the other two examples carrierconcentrationelectronconc25 holeconc100 intrinsicconc0 intrinsicconc 50 0 carrierconcentrationelectronconc0 holeconc1600 intrinsicconc200 electronconc 25 0 carrierconcentrationelectronconc1000 holeconc0 intrinsicconc1200 holeconc 1440 0 carrierconcentrationelectronconc1000 holeconc400 intrinsicconc1200 traceback most recent call last valueerror you cannot supply more or less than 2 values carrierconcentrationelectronconc1000 holeconc0 intrinsicconc1200 traceback most recent call last valueerror electron concentration cannot be negative in a semiconductor carrierconcentrationelectronconc0 holeconc400 intrinsicconc1200 traceback most recent call last valueerror hole concentration cannot be negative in a semiconductor carrierconcentrationelectronconc0 holeconc400 intrinsicconc1200 traceback most recent call last valueerror intrinsic concentration cannot be negative in a semiconductor https en wikipedia org wiki charge_carrier_density https www pveducation org pvcdrom pn junctions equilibrium carrier concentration http www ece utep edu courses ee3329 ee3329 studyguide toc fundamentals carriers concentrations html this function can calculate any one of the three 1 electron concentration 2 hole concentration 3 intrinsic concentration given the other two examples carrier_concentration electron_conc 25 hole_conc 100 intrinsic_conc 0 intrinsic_conc 50 0 carrier_concentration electron_conc 0 hole_conc 1600 intrinsic_conc 200 electron_conc 25 0 carrier_concentration electron_conc 1000 hole_conc 0 intrinsic_conc 1200 hole_conc 1440 0 carrier_concentration electron_conc 1000 hole_conc 400 intrinsic_conc 1200 traceback most recent call last valueerror you cannot supply more or less than 2 values carrier_concentration electron_conc 1000 hole_conc 0 intrinsic_conc 1200 traceback most recent call last valueerror electron concentration cannot be negative in a semiconductor carrier_concentration electron_conc 0 hole_conc 400 intrinsic_conc 1200 traceback most recent call last valueerror hole concentration cannot be negative in a semiconductor carrier_concentration electron_conc 0 hole_conc 400 intrinsic_conc 1200 traceback most recent call last valueerror intrinsic concentration cannot be negative in a semiconductor
from __future__ import annotations def carrier_concentration( electron_conc: float, hole_conc: float, intrinsic_conc: float, ) -> tuple: if (electron_conc, hole_conc, intrinsic_conc).count(0) != 1: raise ValueError("You cannot supply more or less than 2 values") elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative in a semiconductor") elif hole_conc < 0: raise ValueError("Hole concentration cannot be negative in a semiconductor") elif intrinsic_conc < 0: raise ValueError( "Intrinsic concentration cannot be negative in a semiconductor" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
source the arrl handbook for radio communications https en wikipedia orgwikirctimeconstant description when a capacitor is connected with a potential source ac or dc it starts to charge at a general speed but when a resistor is connected in the circuit with in series to a capacitor then the capacitor charges slowly means it will take more time than usual while the capacitor is being charged the voltage is in exponential function with time resistanceohms capacitancefarads is called rctimeconstant which may also be represented as tau by using this rctimeconstant we can find the voltage at any time t from the initiation of charging a capacitor with the help of the exponential function containing rc both at charging and discharging of a capacitor find capacitor voltage at any nth second after initiating its charging examples chargingcapacitorsourcevoltage 2 resistance 9 capacitance8 4 timesec 5 0 013 chargingcapacitorsourcevoltage2 2 resistance3 5 capacitance2 4 timesec9 1 446 chargingcapacitorsourcevoltage15 resistance200 capacitance20 timesec2 0 007 chargingcapacitor20 2000 30pow10 5 4 19 975 chargingcapacitorsourcevoltage0 resistance10 0 capacitance 30 timesec3 traceback most recent call last valueerror source voltage must be positive chargingcapacitorsourcevoltage20 resistance2000 capacitance30 timesec4 traceback most recent call last valueerror resistance must be positive chargingcapacitorsourcevoltage30 resistance1500 capacitance0 timesec4 traceback most recent call last valueerror capacitance must be positive source the arrl handbook for radio communications https en wikipedia org wiki rc_time_constant description when a capacitor is connected with a potential source ac or dc it starts to charge at a general speed but when a resistor is connected in the circuit with in series to a capacitor then the capacitor charges slowly means it will take more time than usual while the capacitor is being charged the voltage is in exponential function with time resistance ohms capacitance farads is called rc timeconstant which may also be represented as τ tau by using this rc timeconstant we can find the voltage at any time t from the initiation of charging a capacitor with the help of the exponential function containing rc both at charging and discharging of a capacitor value of exp 2 718281828459 voltage in volts resistance in ohms capacitance in farads time in seconds after charging initiation of capacitor find capacitor voltage at any nth second after initiating its charging examples charging_capacitor source_voltage 2 resistance 9 capacitance 8 4 time_sec 5 0 013 charging_capacitor source_voltage 2 2 resistance 3 5 capacitance 2 4 time_sec 9 1 446 charging_capacitor source_voltage 15 resistance 200 capacitance 20 time_sec 2 0 007 charging_capacitor 20 2000 30 pow 10 5 4 19 975 charging_capacitor source_voltage 0 resistance 10 0 capacitance 30 time_sec 3 traceback most recent call last valueerror source voltage must be positive charging_capacitor source_voltage 20 resistance 2000 capacitance 30 time_sec 4 traceback most recent call last valueerror resistance must be positive charging_capacitor source_voltage 30 resistance 1500 capacitance 0 time_sec 4 traceback most recent call last valueerror capacitance must be positive
from math import exp def charging_capacitor( source_voltage: float, resistance: float, capacitance: float, time_sec: float, ) -> float: if source_voltage <= 0: raise ValueError("Source voltage must be positive.") if resistance <= 0: raise ValueError("Resistance must be positive.") if capacitance <= 0: raise ValueError("Capacitance must be positive.") return round(source_voltage * (1 - exp(-time_sec / (resistance * capacitance))), 3) if __name__ == "__main__": import doctest doctest.testmod()
source the arrl handbook for radio communications https en wikipedia orgwikirlcircuit description inductor is a passive electronic device which stores energy but unlike capacitor it stores energy in its magnetic field or magnetostatic field when inductor is connected to dc current source nothing happens it just works like a wire because it s real effect cannot be seen while dc is connected its not even going to store energy inductor stores energy only when it is working on ac current connecting a inductor in series with a resistorwhen r 0 to a ac potential source from zero to a finite value causes a sudden voltage to induced in inductor which opposes the current which results in initially slowly current rise however it would cease if there is no further changes in current with resistance zero current will never stop rising resistanceohms inductancehenrys is known as rltimeconstant it also represents as tau while the charging of a inductor with a resistor results in a exponential function when inductor is connected across ac potential source it starts to store the energy in its magnetic field with the help rltimeconstant we can find current at any time in inductor while it is charging find inductor current at any nth second after initiating its charging examples charginginductorsourcevoltage5 8 resistance1 5 inductance2 3 time2 2 817 charginginductorsourcevoltage8 resistance5 inductance3 time2 1 543 charginginductorsourcevoltage8 resistance5pow10 2 inductance3 time2 0 016 charginginductorsourcevoltage8 resistance100 inductance15 time12 traceback most recent call last valueerror source voltage must be positive charginginductorsourcevoltage80 resistance15 inductance100 time5 traceback most recent call last valueerror resistance must be positive charginginductorsourcevoltage12 resistance200 inductance20 time5 traceback most recent call last valueerror inductance must be positive charginginductorsourcevoltage0 resistance200 inductance20 time5 traceback most recent call last valueerror source voltage must be positive charginginductorsourcevoltage10 resistance0 inductance20 time5 traceback most recent call last valueerror resistance must be positive charginginductorsourcevoltage15 resistance25 inductance0 time5 traceback most recent call last valueerror inductance must be positive source the arrl handbook for radio communications https en wikipedia org wiki rl_circuit description inductor is a passive electronic device which stores energy but unlike capacitor it stores energy in its magnetic field or magnetostatic field when inductor is connected to dc current source nothing happens it just works like a wire because it s real effect cannot be seen while dc is connected its not even going to store energy inductor stores energy only when it is working on ac current connecting a inductor in series with a resistor when r 0 to a ac potential source from zero to a finite value causes a sudden voltage to induced in inductor which opposes the current which results in initially slowly current rise however it would cease if there is no further changes in current with resistance zero current will never stop rising resistance ohms inductance henrys is known as rl timeconstant it also represents as τ tau while the charging of a inductor with a resistor results in a exponential function when inductor is connected across ac potential source it starts to store the energy in its magnetic field with the help rl time constant we can find current at any time in inductor while it is charging value of exp 2 718281828459 source_voltage should be in volts resistance should be in ohms inductance should be in henrys time should in seconds find inductor current at any nth second after initiating its charging examples charging_inductor source_voltage 5 8 resistance 1 5 inductance 2 3 time 2 2 817 charging_inductor source_voltage 8 resistance 5 inductance 3 time 2 1 543 charging_inductor source_voltage 8 resistance 5 pow 10 2 inductance 3 time 2 0 016 charging_inductor source_voltage 8 resistance 100 inductance 15 time 12 traceback most recent call last valueerror source voltage must be positive charging_inductor source_voltage 80 resistance 15 inductance 100 time 5 traceback most recent call last valueerror resistance must be positive charging_inductor source_voltage 12 resistance 200 inductance 20 time 5 traceback most recent call last valueerror inductance must be positive charging_inductor source_voltage 0 resistance 200 inductance 20 time 5 traceback most recent call last valueerror source voltage must be positive charging_inductor source_voltage 10 resistance 0 inductance 20 time 5 traceback most recent call last valueerror resistance must be positive charging_inductor source_voltage 15 resistance 25 inductance 0 time 5 traceback most recent call last valueerror inductance must be positive
from math import exp def charging_inductor( source_voltage: float, resistance: float, inductance: float, time: float, ) -> float: if source_voltage <= 0: raise ValueError("Source voltage must be positive.") if resistance <= 0: raise ValueError("Resistance must be positive.") if inductance <= 0: raise ValueError("Inductance must be positive.") return round( source_voltage / resistance * (1 - exp((-time * resistance) / inductance)), 3 ) if __name__ == "__main__": import doctest doctest.testmod()
https en wikipedia orgwikicircularconvolution circular convolution also known as cyclic convolution is a special case of periodic convolution which is the convolution of two periodic functions that have the same period periodic convolution arises for example in the context of the discretetime fourier transform dtft in particular the dtft of the product of two discrete sequences is the periodic convolution of the dtfts of the individual sequences and each dtft is a periodic summation of a continuous fourier transform function source https en wikipedia orgwikicircularconvolution this class stores the first and second signal and performs the circular convolution first signal and second signal are stored as 1d array this function performs the circular convolution of the first and second signal using matrix method usage import circularconvolution as cc convolution cc circularconvolution convolution circularconvolution 10 10 6 14 convolution firstsignal 0 2 0 4 0 6 0 8 1 0 1 2 1 4 1 6 convolution secondsignal 0 1 0 3 0 5 0 7 0 9 1 1 1 3 1 5 convolution circularconvolution 5 2 6 0 6 48 6 64 6 48 6 0 5 2 4 08 convolution firstsignal 1 1 2 2 convolution secondsignal 0 5 1 1 2 0 75 convolution circularconvolution 6 25 3 0 1 5 2 0 2 75 convolution firstsignal 1 1 2 3 1 convolution secondsignal 1 2 3 convolution circularconvolution 8 2 3 4 11 create a zero matrix of maxlength x maxlength fills the smaller signal with zeros to make both signals of same length fills the matrix in the following way assuming x is the signal of length 4 x0 x3 x2 x1 x1 x0 x3 x2 x2 x1 x0 x3 x3 x2 x1 x0 multiply the matrix with the first signal roundingoff to two decimal places https en wikipedia org wiki circular_convolution circular convolution also known as cyclic convolution is a special case of periodic convolution which is the convolution of two periodic functions that have the same period periodic convolution arises for example in the context of the discrete time fourier transform dtft in particular the dtft of the product of two discrete sequences is the periodic convolution of the dtfts of the individual sequences and each dtft is a periodic summation of a continuous fourier transform function source https en wikipedia org wiki circular_convolution this class stores the first and second signal and performs the circular convolution first signal and second signal are stored as 1 d array this function performs the circular convolution of the first and second signal using matrix method usage import circular_convolution as cc convolution cc circularconvolution convolution circular_convolution 10 10 6 14 convolution first_signal 0 2 0 4 0 6 0 8 1 0 1 2 1 4 1 6 convolution second_signal 0 1 0 3 0 5 0 7 0 9 1 1 1 3 1 5 convolution circular_convolution 5 2 6 0 6 48 6 64 6 48 6 0 5 2 4 08 convolution first_signal 1 1 2 2 convolution second_signal 0 5 1 1 2 0 75 convolution circular_convolution 6 25 3 0 1 5 2 0 2 75 convolution first_signal 1 1 2 3 1 convolution second_signal 1 2 3 convolution circular_convolution 8 2 3 4 11 create a zero matrix of max_length x max_length fills the smaller signal with zeros to make both signals of same length fills the matrix in the following way assuming x is the signal of length 4 x 0 x 3 x 2 x 1 x 1 x 0 x 3 x 2 x 2 x 1 x 0 x 3 x 3 x 2 x 1 x 0 multiply the matrix with the first signal rounding off to two decimal places
import doctest from collections import deque import numpy as np class CircularConvolution: def __init__(self) -> None: self.first_signal = [2, 1, 2, -1] self.second_signal = [1, 2, 3, 4] def circular_convolution(self) -> list[float]: length_first_signal = len(self.first_signal) length_second_signal = len(self.second_signal) max_length = max(length_first_signal, length_second_signal) matrix = [[0] * max_length for i in range(max_length)] if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(max_length): rotated_signal = deque(self.second_signal) rotated_signal.rotate(i) for j, item in enumerate(rotated_signal): matrix[i][j] += item final_signal = np.matmul(np.transpose(matrix), np.transpose(self.first_signal)) return [round(i, 2) for i in final_signal] if __name__ == "__main__": doctest.testmod()
https en wikipedia orgwikicoulomb27slaw apply coulomb s law on any three given values these can be force charge1 charge2 or distance and then in a python dict return namevalue pair of the zero value coulomb s law states that the magnitude of the electrostatic force of attraction or repulsion between two point charges is directly proportional to the product of the magnitudes of charges and inversely proportional to the square of the distance between them reference coulomb 1785 premier mmoire sur llectricit et le magntisme histoire de lacadmie royale des sciences pp 569577 parameters force float with units in newtons charge1 float with units in coulombs charge2 float with units in coulombs distance float with units in meters returns result dict namevalue pair of the zero value couloumbslawforce0 charge13 charge25 distance2000 force 33705 0 couloumbslawforce10 charge13 charge25 distance0 distance 116112 01488218177 couloumbslawforce10 charge10 charge25 distance2000 charge1 0 0008900756564307966 couloumbslawforce0 charge10 charge25 distance2000 traceback most recent call last valueerror one and only one argument must be 0 couloumbslawforce0 charge13 charge25 distance2000 traceback most recent call last valueerror distance cannot be negative https en wikipedia org wiki coulomb 27s_law units n m s c 2 apply coulomb s law on any three given values these can be force charge1 charge2 or distance and then in a python dict return name value pair of the zero value coulomb s law states that the magnitude of the electrostatic force of attraction or repulsion between two point charges is directly proportional to the product of the magnitudes of charges and inversely proportional to the square of the distance between them reference coulomb 1785 premier mémoire sur l électricité et le magnétisme histoire de l académie royale des sciences pp 569 577 parameters force float with units in newtons charge1 float with units in coulombs charge2 float with units in coulombs distance float with units in meters returns result dict name value pair of the zero value couloumbs_law force 0 charge1 3 charge2 5 distance 2000 force 33705 0 couloumbs_law force 10 charge1 3 charge2 5 distance 0 distance 116112 01488218177 couloumbs_law force 10 charge1 0 charge2 5 distance 2000 charge1 0 0008900756564307966 couloumbs_law force 0 charge1 0 charge2 5 distance 2000 traceback most recent call last valueerror one and only one argument must be 0 couloumbs_law force 0 charge1 3 charge2 5 distance 2000 traceback most recent call last valueerror distance cannot be negative
from __future__ import annotations COULOMBS_CONSTANT = 8.988e9 def couloumbs_law( force: float, charge1: float, charge2: float, distance: float ) -> dict[str, float]: charge_product = abs(charge1 * charge2) if (force, charge1, charge2, distance).count(0) != 1: raise ValueError("One and only one argument must be 0") if distance < 0: raise ValueError("Distance cannot be negative") if force == 0: force = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif charge1 == 0: charge1 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge2) return {"charge1": charge1} elif charge2 == 0: charge2 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge1) return {"charge2": charge2} elif distance == 0: distance = (COULOMBS_CONSTANT * charge_product / abs(force)) ** 0.5 return {"distance": distance} raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
this function can calculate any one of the three 1 conductivity 2 electron concentration 3 electron mobility this is calculated from the other two provided values examples electricconductivityconductivity25 electronconc100 mobility0 mobility 1 5604519068722301e18 electricconductivityconductivity0 electronconc1600 mobility200 conductivity 5 12672e14 electricconductivityconductivity1000 electronconc0 mobility1200 electronconc 5 201506356240767e18 units c this function can calculate any one of the three 1 conductivity 2 electron concentration 3 electron mobility this is calculated from the other two provided values examples electric_conductivity conductivity 25 electron_conc 100 mobility 0 mobility 1 5604519068722301e 18 electric_conductivity conductivity 0 electron_conc 1600 mobility 200 conductivity 5 12672e 14 electric_conductivity conductivity 1000 electron_conc 0 mobility 1200 electron_conc 5 201506356240767e 18
from __future__ import annotations ELECTRON_CHARGE = 1.6021e-19 def electric_conductivity( conductivity: float, electron_conc: float, mobility: float, ) -> tuple[str, float]: if (conductivity, electron_conc, mobility).count(0) != 1: raise ValueError("You cannot supply more or less than 2 values") elif conductivity < 0: raise ValueError("Conductivity cannot be negative") elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative") elif mobility < 0: raise ValueError("mobility cannot be negative") elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
https en m wikipedia orgwikielectricpower this function can calculate any one of the three voltage current power fundamental value of electrical system examples are below electricpowervoltage0 current2 power5 resultname voltage value2 5 electricpowervoltage2 current2 power0 resultname power value4 0 electricpowervoltage2 current3 power0 resultname power value6 0 electricpowervoltage2 current4 power2 traceback most recent call last valueerror only one argument must be 0 electricpowervoltage0 current0 power2 traceback most recent call last valueerror only one argument must be 0 electricpowervoltage0 current2 power4 traceback most recent call last valueerror power cannot be negative in any electricalelectronics system electricpowervoltage2 2 current2 2 power0 resultname power value4 84 https en m wikipedia org wiki electric_power this function can calculate any one of the three voltage current power fundamental value of electrical system examples are below electric_power voltage 0 current 2 power 5 result name voltage value 2 5 electric_power voltage 2 current 2 power 0 result name power value 4 0 electric_power voltage 2 current 3 power 0 result name power value 6 0 electric_power voltage 2 current 4 power 2 traceback most recent call last valueerror only one argument must be 0 electric_power voltage 0 current 0 power 2 traceback most recent call last valueerror only one argument must be 0 electric_power voltage 0 current 2 power 4 traceback most recent call last valueerror power cannot be negative in any electrical electronics system electric_power voltage 2 2 current 2 2 power 0 result name power value 4 84
from __future__ import annotations from typing import NamedTuple class Result(NamedTuple): name: str value: float def electric_power(voltage: float, current: float, power: float) -> tuple: if (voltage, current, power).count(0) != 1: raise ValueError("Only one argument must be 0") elif power < 0: raise ValueError( "Power cannot be negative in any electrical/electronics system" ) elif voltage == 0: return Result("voltage", power / current) elif current == 0: return Result("current", power / voltage) elif power == 0: return Result("power", float(round(abs(voltage * current), 2))) else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
electrical impedance is the measure of the opposition that a circuit presents to a current when a voltage is applied impedance extends the concept of resistance to alternating current ac circuits source https en wikipedia orgwikielectricalimpedance apply electrical impedance formula on any two given electrical values which can be resistance reactance and impedance and then in a python dict return namevalue pair of the zero value electricalimpedance3 4 0 impedance 5 0 electricalimpedance0 4 5 resistance 3 0 electricalimpedance3 0 5 reactance 4 0 electricalimpedance3 4 5 traceback most recent call last valueerror one and only one argument must be 0 apply electrical impedance formula on any two given electrical values which can be resistance reactance and impedance and then in a python dict return name value pair of the zero value electrical_impedance 3 4 0 impedance 5 0 electrical_impedance 0 4 5 resistance 3 0 electrical_impedance 3 0 5 reactance 4 0 electrical_impedance 3 4 5 traceback most recent call last valueerror one and only one argument must be 0
from __future__ import annotations from math import pow, sqrt def electrical_impedance( resistance: float, reactance: float, impedance: float ) -> dict[str, float]: if (resistance, reactance, impedance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance == 0: return {"resistance": sqrt(pow(impedance, 2) - pow(reactance, 2))} elif reactance == 0: return {"reactance": sqrt(pow(impedance, 2) - pow(resistance, 2))} elif impedance == 0: return {"impedance": sqrt(pow(resistance, 2) + pow(reactance, 2))} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
calculate the frequency andor duty cycle of an astable 555 timer https en wikipedia orgwiki555timericastable these functions take in the value of the external resistances in ohms and capacitance in microfarad and calculates the following freq 1 44 r1 2 x r2 x c1 in hz where freq is the frequency r1 is the first resistance in ohms r2 is the second resistance in ohms c1 is the capacitance in microfarads duty cycle r1 r2 r1 2 x r2 x 100 in where r1 is the first resistance in ohms r2 is the second resistance in ohms usage examples astablefrequencyresistance145 resistance245 capacitance7 1523 8095238095239 astablefrequencyresistance1356 resistance2234 capacitance976 1 7905459175553078 astablefrequencyresistance12 resistance21 capacitance2 traceback most recent call last valueerror all values must be positive astablefrequencyresistance145 resistance245 capacitance0 traceback most recent call last valueerror all values must be positive usage examples astabledutycycleresistance145 resistance245 66 66666666666666 astabledutycycleresistance1356 resistance2234 71 60194174757282 astabledutycycleresistance12 resistance21 traceback most recent call last valueerror all values must be positive astabledutycycleresistance10 resistance20 traceback most recent call last valueerror all values must be positive calculate the frequency and or duty cycle of an astable 555 timer https en wikipedia org wiki 555_timer_ic astable these functions take in the value of the external resistances in ohms and capacitance in microfarad and calculates the following freq 1 44 r1 2 x r2 x c1 in hz where freq is the frequency r1 is the first resistance in ohms r2 is the second resistance in ohms c1 is the capacitance in microfarads duty cycle r1 r2 r1 2 x r2 x 100 in where r1 is the first resistance in ohms r2 is the second resistance in ohms usage examples astable_frequency resistance_1 45 resistance_2 45 capacitance 7 1523 8095238095239 astable_frequency resistance_1 356 resistance_2 234 capacitance 976 1 7905459175553078 astable_frequency resistance_1 2 resistance_2 1 capacitance 2 traceback most recent call last valueerror all values must be positive astable_frequency resistance_1 45 resistance_2 45 capacitance 0 traceback most recent call last valueerror all values must be positive usage examples astable_duty_cycle resistance_1 45 resistance_2 45 66 66666666666666 astable_duty_cycle resistance_1 356 resistance_2 234 71 60194174757282 astable_duty_cycle resistance_1 2 resistance_2 1 traceback most recent call last valueerror all values must be positive astable_duty_cycle resistance_1 0 resistance_2 0 traceback most recent call last valueerror all values must be positive
from __future__ import annotations def astable_frequency( resistance_1: float, resistance_2: float, capacitance: float ) -> float: if resistance_1 <= 0 or resistance_2 <= 0 or capacitance <= 0: raise ValueError("All values must be positive") return (1.44 / ((resistance_1 + 2 * resistance_2) * capacitance)) * 10**6 def astable_duty_cycle(resistance_1: float, resistance_2: float) -> float: if resistance_1 <= 0 or resistance_2 <= 0: raise ValueError("All values must be positive") return (resistance_1 + resistance_2) / (resistance_1 + 2 * resistance_2) * 100 if __name__ == "__main__": import doctest doctest.testmod()
https en wikipedia orgwikielectricalreactanceinductivereactance calculate inductive reactance frequency or inductance from two given electrical properties then return namevalue pair of the zero value in a python dict parameters inductance float with units in henries frequency float with units in hertz reactance float with units in ohms indreactance35e6 1e3 0 traceback most recent call last valueerror inductance cannot be negative indreactance35e6 1e3 0 traceback most recent call last valueerror frequency cannot be negative indreactance35e6 0 1 traceback most recent call last valueerror inductive reactance cannot be negative indreactance0 10e3 50 inductance 0 0007957747154594767 indreactance35e3 0 50 frequency 227 36420441699332 indreactance35e6 1e3 0 reactance 0 2199114857512855 https en wikipedia org wiki electrical_reactance inductive_reactance calculate inductive reactance frequency or inductance from two given electrical properties then return name value pair of the zero value in a python dict parameters inductance float with units in henries frequency float with units in hertz reactance float with units in ohms ind_reactance 35e 6 1e3 0 traceback most recent call last valueerror inductance cannot be negative ind_reactance 35e 6 1e3 0 traceback most recent call last valueerror frequency cannot be negative ind_reactance 35e 6 0 1 traceback most recent call last valueerror inductive reactance cannot be negative ind_reactance 0 10e3 50 inductance 0 0007957747154594767 ind_reactance 35e 3 0 50 frequency 227 36420441699332 ind_reactance 35e 6 1e3 0 reactance 0 2199114857512855
from __future__ import annotations from math import pi def ind_reactance( inductance: float, frequency: float, reactance: float ) -> dict[str, float]: if (inductance, frequency, reactance).count(0) != 1: raise ValueError("One and only one argument must be 0") if inductance < 0: raise ValueError("Inductance cannot be negative") if frequency < 0: raise ValueError("Frequency cannot be negative") if reactance < 0: raise ValueError("Inductive reactance cannot be negative") if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
https en wikipedia orgwikiohm27slaw apply ohm s law on any two given electrical values which can be voltage current and resistance and then in a python dict return namevalue pair of the zero value ohmslawvoltage10 resistance5 current0 current 2 0 ohmslawvoltage0 current0 resistance10 traceback most recent call last valueerror one and only one argument must be 0 ohmslawvoltage0 current1 resistance2 traceback most recent call last valueerror resistance cannot be negative ohmslawresistance0 voltage10 current1 resistance 10 0 ohmslawvoltage0 current1 5 resistance2 voltage 3 0 https en wikipedia org wiki ohm 27s_law apply ohm s law on any two given electrical values which can be voltage current and resistance and then in a python dict return name value pair of the zero value ohms_law voltage 10 resistance 5 current 0 current 2 0 ohms_law voltage 0 current 0 resistance 10 traceback most recent call last valueerror one and only one argument must be 0 ohms_law voltage 0 current 1 resistance 2 traceback most recent call last valueerror resistance cannot be negative ohms_law resistance 0 voltage 10 current 1 resistance 10 0 ohms_law voltage 0 current 1 5 resistance 2 voltage 3 0
from __future__ import annotations def ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]: if (voltage, current, resistance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance < 0: raise ValueError("Resistance cannot be negative") if voltage == 0: return {"voltage": float(current * resistance)} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
calculate real power from apparent power and power factor examples realpower100 0 9 90 0 realpower0 0 8 0 0 realpower100 0 9 90 0 calculate reactive power from apparent power and power factor examples reactivepower100 0 9 43 58898943540673 reactivepower0 0 8 0 0 reactivepower100 0 9 43 58898943540673 calculate real power from apparent power and power factor examples real_power 100 0 9 90 0 real_power 0 0 8 0 0 real_power 100 0 9 90 0 calculate reactive power from apparent power and power factor examples reactive_power 100 0 9 43 58898943540673 reactive_power 0 0 8 0 0 reactive_power 100 0 9 43 58898943540673
import math def real_power(apparent_power: float, power_factor: float) -> float: if ( not isinstance(power_factor, (int, float)) or power_factor < -1 or power_factor > 1 ): raise ValueError("power_factor must be a valid float value between -1 and 1.") return apparent_power * power_factor def reactive_power(apparent_power: float, power_factor: float) -> float: if ( not isinstance(power_factor, (int, float)) or power_factor < -1 or power_factor > 1 ): raise ValueError("power_factor must be a valid float value between -1 and 1.") return apparent_power * math.sqrt(1 - power_factor**2) if __name__ == "__main__": import doctest doctest.testmod()
title calculating the resistance of a n band resistor using the color codes description resistors resist the flow of electrical current each one has a value that tells how strongly it resists current flow this value s unit is the ohm often noted with the greek letter omega the colored bands on a resistor can tell you everything you need to know about its value and tolerance as long as you understand how to read them the order in which the colors are arranged is very important and each value of resistor has its own unique combination the color coding for resistors is an international standard that is defined in iec 60062 the number of bands present in a resistor varies from three to six these represent significant figures multiplier tolerance reliability and temperature coefficient each color used for a type of band has a value assigned to it it is read from left to right all resistors will have significant figures and multiplier bands in a three band resistor first two bands from the left represent significant figures and the third represents the multiplier band significant figures the number of significant figures band in a resistor can vary from two to three colors and values associated with significant figure bands black 0 brown 1 red 2 orange 3 yellow 4 green 5 blue 6 violet 7 grey 8 white 9 multiplier there will be one multiplier band in a resistor it is multiplied with the significant figures obtained from previous bands colors and values associated with multiplier band black 100 brown 101 red 102 orange 103 yellow 104 green 105 blue 106 violet 107 grey 108 white 109 gold 101 silver 102 note that multiplier bands use gold and silver which are not used for significant figure bands tolerance the tolerance band is not always present it can be seen in four band resistors and above this is a percentage by which the resistor value can vary colors and values associated with tolerance band brown 1 red 2 orange 0 05 yellow 0 02 green 0 5 blue 0 25 violet 0 1 grey 0 01 gold 5 silver 10 if no color is mentioned then by default tolerance is 20 note that tolerance band does not use black and white colors temperature coeffecient indicates the change in resistance of the component as a function of ambient temperature in terms of ppmk it is present in six band resistors colors and values associated with temperature coeffecient black 250 ppmk brown 100 ppmk red 50 ppmk orange 15 ppmk yellow 25 ppmk green 20 ppmk blue 10 ppmk violet 5 ppmk grey 1 ppmk note that temperature coeffecient band does not use white gold silver colors sources https www calculator netresistorcalculator html https learn parallax comsupportreferenceresistorcolorcodes https byjus comphysicsresistorcolourcodes function returns the digit associated with the color function takes a list containing colors as input and returns digits as string getsignificantdigits black blue 06 getsignificantdigits aqua blue traceback most recent call last valueerror aqua is not a valid color for significant figure bands function returns the multiplier value associated with the color function takes color as input and returns multiplier value getmultiplier gold 0 1 getmultiplier ivory traceback most recent call last valueerror ivory is not a valid color for multiplier band function returns the tolerance value associated with the color function takes color as input and returns tolerance value gettolerance green 0 5 gettolerance indigo traceback most recent call last valueerror indigo is not a valid color for tolerance band function returns the temperature coeffecient value associated with the color function takes color as input and returns temperature coeffecient value gettemperaturecoeffecient yellow 25 gettemperaturecoeffecient cyan traceback most recent call last valueerror cyan is not a valid color for temperature coeffecient band function returns the number of bands of a given type in a resistor with n bands function takes totalnumberofbands and typeofband as input and returns number of bands belonging to that type in the given resistor getbandtypecount3 significant 2 getbandtypecount2 significant traceback most recent call last valueerror 2 is not a valid number of bands getbandtypecount3 sign traceback most recent call last valueerror sign is not valid for a 3 band resistor getbandtypecount3 tolerance traceback most recent call last valueerror tolerance is not valid for a 3 band resistor getbandtypecount5 tempcoeffecient traceback most recent call last valueerror tempcoeffecient is not valid for a 5 band resistor function checks if the input provided is valid or not function takes numberofbands and colors as input and returns true if it is valid checkvalidity3 black blue orange true checkvalidity4 black blue orange traceback most recent call last valueerror expecting 4 colors provided 3 colors checkvalidity3 cyan red yellow traceback most recent call last valueerror cyan is not a valid color function calculates the total resistance of the resistor using the color codes function takes numberofbands colorcodelist as input and returns resistance calculateresistance3 black blue orange resistance 6000 20 calculateresistance4 orange green blue gold resistance 35000000 5 calculateresistance5 violet brown grey silver green resistance 7 18 0 5 calculateresistance6 red green blue yellow orange grey resistance 2560000 0 05 1 ppmk calculateresistance0 violet brown grey silver green traceback most recent call last valueerror invalid number of bands resistor bands must be 3 to 6 calculateresistance4 violet brown grey silver green traceback most recent call last valueerror expecting 4 colors provided 5 colors calculateresistance4 violet silver brown grey traceback most recent call last valueerror silver is not a valid color for significant figure bands calculateresistance4 violet blue lime grey traceback most recent call last valueerror lime is not a valid color function returns the digit associated with the color function takes a list containing colors as input and returns digits as string get_significant_digits black blue 06 get_significant_digits aqua blue traceback most recent call last valueerror aqua is not a valid color for significant figure bands function returns the multiplier value associated with the color function takes color as input and returns multiplier value get_multiplier gold 0 1 get_multiplier ivory traceback most recent call last valueerror ivory is not a valid color for multiplier band function returns the tolerance value associated with the color function takes color as input and returns tolerance value get_tolerance green 0 5 get_tolerance indigo traceback most recent call last valueerror indigo is not a valid color for tolerance band function returns the temperature coeffecient value associated with the color function takes color as input and returns temperature coeffecient value get_temperature_coeffecient yellow 25 get_temperature_coeffecient cyan traceback most recent call last valueerror cyan is not a valid color for temperature coeffecient band function returns the number of bands of a given type in a resistor with n bands function takes total_number_of_bands and type_of_band as input and returns number of bands belonging to that type in the given resistor get_band_type_count 3 significant 2 get_band_type_count 2 significant traceback most recent call last valueerror 2 is not a valid number of bands get_band_type_count 3 sign traceback most recent call last valueerror sign is not valid for a 3 band resistor get_band_type_count 3 tolerance traceback most recent call last valueerror tolerance is not valid for a 3 band resistor get_band_type_count 5 temp_coeffecient traceback most recent call last valueerror temp_coeffecient is not valid for a 5 band resistor function checks if the input provided is valid or not function takes number_of_bands and colors as input and returns true if it is valid check_validity 3 black blue orange true check_validity 4 black blue orange traceback most recent call last valueerror expecting 4 colors provided 3 colors check_validity 3 cyan red yellow traceback most recent call last valueerror cyan is not a valid color function calculates the total resistance of the resistor using the color codes function takes number_of_bands color_code_list as input and returns resistance calculate_resistance 3 black blue orange resistance 6000ω 20 calculate_resistance 4 orange green blue gold resistance 35000000ω 5 calculate_resistance 5 violet brown grey silver green resistance 7 18ω 0 5 calculate_resistance 6 red green blue yellow orange grey resistance 2560000ω 0 05 1 ppm k calculate_resistance 0 violet brown grey silver green traceback most recent call last valueerror invalid number of bands resistor bands must be 3 to 6 calculate_resistance 4 violet brown grey silver green traceback most recent call last valueerror expecting 4 colors provided 5 colors calculate_resistance 4 violet silver brown grey traceback most recent call last valueerror silver is not a valid color for significant figure bands calculate_resistance 4 violet blue lime grey traceback most recent call last valueerror lime is not a valid color
valid_colors: list = [ "Black", "Brown", "Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Grey", "White", "Gold", "Silver", ] significant_figures_color_values: dict[str, int] = { "Black": 0, "Brown": 1, "Red": 2, "Orange": 3, "Yellow": 4, "Green": 5, "Blue": 6, "Violet": 7, "Grey": 8, "White": 9, } multiplier_color_values: dict[str, float] = { "Black": 10**0, "Brown": 10**1, "Red": 10**2, "Orange": 10**3, "Yellow": 10**4, "Green": 10**5, "Blue": 10**6, "Violet": 10**7, "Grey": 10**8, "White": 10**9, "Gold": 10**-1, "Silver": 10**-2, } tolerance_color_values: dict[str, float] = { "Brown": 1, "Red": 2, "Orange": 0.05, "Yellow": 0.02, "Green": 0.5, "Blue": 0.25, "Violet": 0.1, "Grey": 0.01, "Gold": 5, "Silver": 10, } temperature_coeffecient_color_values: dict[str, int] = { "Black": 250, "Brown": 100, "Red": 50, "Orange": 15, "Yellow": 25, "Green": 20, "Blue": 10, "Violet": 5, "Grey": 1, } band_types: dict[int, dict[str, int]] = { 3: {"significant": 2, "multiplier": 1}, 4: {"significant": 2, "multiplier": 1, "tolerance": 1}, 5: {"significant": 3, "multiplier": 1, "tolerance": 1}, 6: {"significant": 3, "multiplier": 1, "tolerance": 1, "temp_coeffecient": 1}, } def get_significant_digits(colors: list) -> str: digit = "" for color in colors: if color not in significant_figures_color_values: msg = f"{color} is not a valid color for significant figure bands" raise ValueError(msg) digit = digit + str(significant_figures_color_values[color]) return str(digit) def get_multiplier(color: str) -> float: if color not in multiplier_color_values: msg = f"{color} is not a valid color for multiplier band" raise ValueError(msg) return multiplier_color_values[color] def get_tolerance(color: str) -> float: if color not in tolerance_color_values: msg = f"{color} is not a valid color for tolerance band" raise ValueError(msg) return tolerance_color_values[color] def get_temperature_coeffecient(color: str) -> int: if color not in temperature_coeffecient_color_values: msg = f"{color} is not a valid color for temperature coeffecient band" raise ValueError(msg) return temperature_coeffecient_color_values[color] def get_band_type_count(total_number_of_bands: int, type_of_band: str) -> int: if total_number_of_bands not in band_types: msg = f"{total_number_of_bands} is not a valid number of bands" raise ValueError(msg) if type_of_band not in band_types[total_number_of_bands]: msg = f"{type_of_band} is not valid for a {total_number_of_bands} band resistor" raise ValueError(msg) return band_types[total_number_of_bands][type_of_band] def check_validity(number_of_bands: int, colors: list) -> bool: if number_of_bands >= 3 and number_of_bands <= 6: if number_of_bands == len(colors): for color in colors: if color not in valid_colors: msg = f"{color} is not a valid color" raise ValueError(msg) return True else: msg = f"Expecting {number_of_bands} colors, provided {len(colors)} colors" raise ValueError(msg) else: msg = "Invalid number of bands. Resistor bands must be 3 to 6" raise ValueError(msg) def calculate_resistance(number_of_bands: int, color_code_list: list) -> dict: is_valid = check_validity(number_of_bands, color_code_list) if is_valid: number_of_significant_bands = get_band_type_count( number_of_bands, "significant" ) significant_colors = color_code_list[:number_of_significant_bands] significant_digits = int(get_significant_digits(significant_colors)) multiplier_color = color_code_list[number_of_significant_bands] multiplier = get_multiplier(multiplier_color) if number_of_bands == 3: tolerance_color = None else: tolerance_color = color_code_list[number_of_significant_bands + 1] tolerance = ( 20 if tolerance_color is None else get_tolerance(str(tolerance_color)) ) if number_of_bands != 6: temperature_coeffecient_color = None else: temperature_coeffecient_color = color_code_list[ number_of_significant_bands + 2 ] temperature_coeffecient = ( 0 if temperature_coeffecient_color is None else get_temperature_coeffecient(str(temperature_coeffecient_color)) ) resisitance = significant_digits * multiplier if temperature_coeffecient == 0: answer = f"{resisitance}Ω ±{tolerance}% " else: answer = f"{resisitance}Ω ±{tolerance}% {temperature_coeffecient} ppm/K" return {"resistance": answer} else: raise ValueError("Input is invalid") if __name__ == "__main__": import doctest doctest.testmod()
https byjus comequivalentresistanceformula req 1 1r1 1r2 1rn resistorparallel3 21389 2 3 0 8737571620498019 resistorparallel3 21389 2 3 traceback most recent call last valueerror resistor at index 2 has a negative or zero value resistorparallel3 21389 2 0 000 traceback most recent call last valueerror resistor at index 2 has a negative or zero value req r1 r2 rn calculate the equivalent resistance for any number of resistors in parallel resistorseries3 21389 2 3 8 21389 resistorseries3 21389 2 3 traceback most recent call last valueerror resistor at index 2 has a negative value https byjus com equivalent resistance formula req 1 1 r1 1 r2 1 rn resistor_parallel 3 21389 2 3 0 8737571620498019 resistor_parallel 3 21389 2 3 traceback most recent call last valueerror resistor at index 2 has a negative or zero value resistor_parallel 3 21389 2 0 000 traceback most recent call last valueerror resistor at index 2 has a negative or zero value req r1 r2 rn calculate the equivalent resistance for any number of resistors in parallel resistor_series 3 21389 2 3 8 21389 resistor_series 3 21389 2 3 traceback most recent call last valueerror resistor at index 2 has a negative value
from __future__ import annotations def resistor_parallel(resistors: list[float]) -> float: first_sum = 0.00 index = 0 for resistor in resistors: if resistor <= 0: msg = f"Resistor at index {index} has a negative or zero value!" raise ValueError(msg) first_sum += 1 / float(resistor) index += 1 return 1 / first_sum def resistor_series(resistors: list[float]) -> float: sum_r = 0.00 index = 0 for resistor in resistors: sum_r += resistor if resistor < 0: msg = f"Resistor at index {index} has a negative value!" raise ValueError(msg) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
https en wikipedia orgwikilccircuit an lc circuit also called a resonant circuit tank circuit or tuned circuit is an electric circuit consisting of an inductor represented by the letter l and a capacitor represented by the letter c connected together the circuit can act as an electrical resonator an electrical analogue of a tuning fork storing energy oscillating at the circuit s resonant frequency source https en wikipedia orgwikilccircuit this function can calculate the resonant frequency of lc circuit for the given value of inductance and capacitnace examples are given below resonantfrequencyinductance10 capacitance5 resonant frequency 0 022507907903927652 resonantfrequencyinductance0 capacitance5 traceback most recent call last valueerror inductance cannot be 0 or negative resonantfrequencyinductance10 capacitance0 traceback most recent call last valueerror capacitance cannot be 0 or negative https en wikipedia org wiki lc_circuit an lc circuit also called a resonant circuit tank circuit or tuned circuit is an electric circuit consisting of an inductor represented by the letter l and a capacitor represented by the letter c connected together the circuit can act as an electrical resonator an electrical analogue of a tuning fork storing energy oscillating at the circuit s resonant frequency source https en wikipedia org wiki lc_circuit this function can calculate the resonant frequency of lc circuit for the given value of inductance and capacitnace examples are given below resonant_frequency inductance 10 capacitance 5 resonant frequency 0 022507907903927652 resonant_frequency inductance 0 capacitance 5 traceback most recent call last valueerror inductance cannot be 0 or negative resonant_frequency inductance 10 capacitance 0 traceback most recent call last valueerror capacitance cannot be 0 or negative
from __future__ import annotations from math import pi, sqrt def resonant_frequency(inductance: float, capacitance: float) -> tuple: if inductance <= 0: raise ValueError("Inductance cannot be 0 or negative") elif capacitance <= 0: raise ValueError("Capacitance cannot be 0 or negative") else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance)))), ) if __name__ == "__main__": import doctest doctest.testmod()
https en wikipedia orgwikiwheatstonebridge this function can calculate the unknown resistance in an wheatstone network given that the three other resistances in the network are known the formula to calculate the same is rxr2r1r3 usage examples wheatstonesolverresistance12 resistance24 resistance35 10 0 wheatstonesolverresistance1356 resistance2234 resistance3976 641 5280898876405 wheatstonesolverresistance12 resistance21 resistance32 traceback most recent call last valueerror all resistance values must be positive wheatstonesolverresistance10 resistance20 resistance32 traceback most recent call last valueerror all resistance values must be positive https en wikipedia org wiki wheatstone_bridge this function can calculate the unknown resistance in an wheatstone network given that the three other resistances in the network are known the formula to calculate the same is rx r2 r1 r3 usage examples wheatstone_solver resistance_1 2 resistance_2 4 resistance_3 5 10 0 wheatstone_solver resistance_1 356 resistance_2 234 resistance_3 976 641 5280898876405 wheatstone_solver resistance_1 2 resistance_2 1 resistance_3 2 traceback most recent call last valueerror all resistance values must be positive wheatstone_solver resistance_1 0 resistance_2 0 resistance_3 2 traceback most recent call last valueerror all resistance values must be positive
from __future__ import annotations def wheatstone_solver( resistance_1: float, resistance_2: float, resistance_3: float ) -> float: if resistance_1 <= 0 or resistance_2 <= 0 or resistance_3 <= 0: raise ValueError("All resistance values must be positive") else: return float((resistance_2 / resistance_1) * resistance_3) if __name__ == "__main__": import doctest doctest.testmod()
initialization invoke ensurance initialization invoke ensurance
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("socket.socket") @patch("builtins.open") def test_send_file_running_as_expected(file, sock): conn = Mock() sock.return_value.accept.return_value = conn, Mock() f = iter([1, None]) file.return_value.__enter__.return_value.read.side_effect = lambda _: next(f) send_file(filename="mytext.txt", testing=True) sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
program to calculate the amortization amount per month given principal borrowed rate of interest per annum years to repay the loan wikipedia reference https en wikipedia orgwikiequatedmonthlyinstallment formula for amortization amount per month a p r 1 rn 1 rn 1 where p is the principal r is the rate of interest per month and n is the number of payments equatedmonthlyinstallments25000 0 12 3 830 3577453212793 equatedmonthlyinstallments25000 0 12 10 358 67737100646826 equatedmonthlyinstallments0 0 12 3 traceback most recent call last exception principal borrowed must be 0 equatedmonthlyinstallments25000 1 3 traceback most recent call last exception rate of interest must be 0 equatedmonthlyinstallments25000 0 12 0 traceback most recent call last exception years to repay must be an integer 0 yearly rate is divided by 12 to get monthly rate years to repay is multiplied by 12 to get number of payments as payment is monthly formula for amortization amount per month a p r 1 r n 1 r n 1 where p is the principal r is the rate of interest per month and n is the number of payments equated_monthly_installments 25000 0 12 3 830 3577453212793 equated_monthly_installments 25000 0 12 10 358 67737100646826 equated_monthly_installments 0 0 12 3 traceback most recent call last exception principal borrowed must be 0 equated_monthly_installments 25000 1 3 traceback most recent call last exception rate of interest must be 0 equated_monthly_installments 25000 0 12 0 traceback most recent call last exception years to repay must be an integer 0 yearly rate is divided by 12 to get monthly rate years to repay is multiplied by 12 to get number of payments as payment is monthly
def equated_monthly_installments( principal: float, rate_per_annum: float, years_to_repay: int ) -> float: if principal <= 0: raise Exception("Principal borrowed must be > 0") if rate_per_annum < 0: raise Exception("Rate of interest must be >= 0") if years_to_repay <= 0 or not isinstance(years_to_repay, int): raise Exception("Years to repay must be an integer > 0") rate_per_month = rate_per_annum / 12 number_of_payments = years_to_repay * 12 return ( principal * rate_per_month * (1 + rate_per_month) ** number_of_payments / ((1 + rate_per_month) ** number_of_payments - 1) ) if __name__ == "__main__": import doctest doctest.testmod()
calculate the exponential moving average ema on the series of stock prices wikipedia reference https en wikipedia orgwikiexponentialsmoothing https www investopedia comtermseema asptocwhatisanexponential movingaverageema exponential moving average is used in finance to analyze changes stock prices ema is used in conjunction with simple moving average sma ema reacts to the changes in the value quicker than sma which is one of the advantages of using ema yields exponential moving averages of the given stock prices tupleexponentialmovingaverageiter2 5 3 8 2 6 9 10 3 2 3 5 3 25 5 725 5 8625 7 43125 8 715625 param stockprices a stream of stock prices param windowsize the number of stock prices that will trigger a new calculation of the exponential average windowsize 0 return yields a sequence of exponential moving averages formula st alpha xt 1 alpha stprev where st exponential moving average at timestamp t xt stock price in from the stock prices at timestamp t stprev exponential moving average at timestamp t1 alpha 21 windowsize smoothing factor exponential moving average ema is a rule of thumb technique for smoothing time series data using an exponential window function calculating smoothing factor exponential average at timestamp t assigning simple moving average till the windowsize for the first time is reached calculating exponential moving average based on current timestamp data point and previous exponential average value yields exponential moving averages of the given stock prices tuple exponential_moving_average iter 2 5 3 8 2 6 9 10 3 2 3 5 3 25 5 725 5 8625 7 43125 8 715625 param stock_prices a stream of stock prices param window_size the number of stock prices that will trigger a new calculation of the exponential average window_size 0 return yields a sequence of exponential moving averages formula st alpha xt 1 alpha st_prev where st exponential moving average at timestamp t xt stock price in from the stock prices at timestamp t st_prev exponential moving average at timestamp t 1 alpha 2 1 window_size smoothing factor exponential moving average ema is a rule of thumb technique for smoothing time series data using an exponential window function calculating smoothing factor exponential average at timestamp t assigning simple moving average till the window_size for the first time is reached calculating exponential moving average based on current timestamp data point and previous exponential average value
from collections.abc import Iterator def exponential_moving_average( stock_prices: Iterator[float], window_size: int ) -> Iterator[float]: if window_size <= 0: raise ValueError("window_size must be > 0") alpha = 2 / (1 + window_size) moving_average = 0.0 for i, stock_price in enumerate(stock_prices): if i <= window_size: moving_average = (moving_average + stock_price) * 0.5 if i else stock_price else: moving_average = (alpha * stock_price) + ((1 - alpha) * moving_average) yield moving_average if __name__ == "__main__": import doctest doctest.testmod() stock_prices = [2.0, 5, 3, 8.2, 6, 9, 10] window_size = 3 result = tuple(exponential_moving_average(iter(stock_prices), window_size)) print(f"{stock_prices = }") print(f"{window_size = }") print(f"{result = }")
https www investopedia com simpleinterest18000 0 0 06 3 3240 0 simpleinterest0 5 0 06 3 0 09 simpleinterest18000 0 0 01 10 1800 0 simpleinterest18000 0 0 0 3 0 0 simpleinterest5500 0 0 01 100 5500 0 simpleinterest10000 0 0 06 3 traceback most recent call last valueerror dailyinterestrate must be 0 simpleinterest10000 0 0 06 3 traceback most recent call last valueerror principal must be 0 simpleinterest5500 0 0 01 5 traceback most recent call last valueerror daysbetweenpayments must be 0 compoundinterest10000 0 0 05 3 1576 2500000000014 compoundinterest10000 0 0 05 1 500 00000000000045 compoundinterest0 5 0 05 3 0 07881250000000006 compoundinterest10000 0 0 06 4 traceback most recent call last valueerror numberofcompoundingperiods must be 0 compoundinterest10000 0 3 5 3 0 traceback most recent call last valueerror nominalannualinterestratepercentage must be 0 compoundinterest5500 0 0 01 5 traceback most recent call last valueerror principal must be 0 aprinterest10000 0 0 05 3 1618 223072263547 aprinterest10000 0 0 05 1 512 6749646744732 aprinterest0 5 0 05 3 0 08091115361317736 aprinterest10000 0 0 06 4 traceback most recent call last valueerror numberofyears must be 0 aprinterest10000 0 3 5 3 0 traceback most recent call last valueerror nominalannualpercentagerate must be 0 aprinterest5500 0 0 01 5 traceback most recent call last valueerror principal must be 0 https www investopedia com simple_interest 18000 0 0 06 3 3240 0 simple_interest 0 5 0 06 3 0 09 simple_interest 18000 0 0 01 10 1800 0 simple_interest 18000 0 0 0 3 0 0 simple_interest 5500 0 0 01 100 5500 0 simple_interest 10000 0 0 06 3 traceback most recent call last valueerror daily_interest_rate must be 0 simple_interest 10000 0 0 06 3 traceback most recent call last valueerror principal must be 0 simple_interest 5500 0 0 01 5 traceback most recent call last valueerror days_between_payments must be 0 compound_interest 10000 0 0 05 3 1576 2500000000014 compound_interest 10000 0 0 05 1 500 00000000000045 compound_interest 0 5 0 05 3 0 07881250000000006 compound_interest 10000 0 0 06 4 traceback most recent call last valueerror number_of_compounding_periods must be 0 compound_interest 10000 0 3 5 3 0 traceback most recent call last valueerror nominal_annual_interest_rate_percentage must be 0 compound_interest 5500 0 0 01 5 traceback most recent call last valueerror principal must be 0 apr_interest 10000 0 0 05 3 1618 223072263547 apr_interest 10000 0 0 05 1 512 6749646744732 apr_interest 0 5 0 05 3 0 08091115361317736 apr_interest 10000 0 0 06 4 traceback most recent call last valueerror number_of_years must be 0 apr_interest 10000 0 3 5 3 0 traceback most recent call last valueerror nominal_annual_percentage_rate must be 0 apr_interest 5500 0 0 01 5 traceback most recent call last valueerror principal must be 0
from __future__ import annotations def simple_interest( principal: float, daily_interest_rate: float, days_between_payments: float ) -> float: if days_between_payments <= 0: raise ValueError("days_between_payments must be > 0") if daily_interest_rate < 0: raise ValueError("daily_interest_rate must be >= 0") if principal <= 0: raise ValueError("principal must be > 0") return principal * daily_interest_rate * days_between_payments def compound_interest( principal: float, nominal_annual_interest_rate_percentage: float, number_of_compounding_periods: float, ) -> float: if number_of_compounding_periods <= 0: raise ValueError("number_of_compounding_periods must be > 0") if nominal_annual_interest_rate_percentage < 0: raise ValueError("nominal_annual_interest_rate_percentage must be >= 0") if principal <= 0: raise ValueError("principal must be > 0") return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def apr_interest( principal: float, nominal_annual_percentage_rate: float, number_of_years: float, ) -> float: if number_of_years <= 0: raise ValueError("number_of_years must be > 0") if nominal_annual_percentage_rate < 0: raise ValueError("nominal_annual_percentage_rate must be >= 0") if principal <= 0: raise ValueError("principal must be > 0") return compound_interest( principal, nominal_annual_percentage_rate / 365, number_of_years * 365 ) if __name__ == "__main__": import doctest doctest.testmod()
reference https www investopedia comtermsppresentvalue asp an algorithm that calculates the present value of a stream of yearly cash flows given 1 the discount rate as a decimal not a percent 2 an array of cash flows with the index of the cash flow being the associated year note this algorithm assumes that cash flows are paid at the end of the specified year presentvalue0 13 10 20 70 293 297 4 69 presentvalue0 07 109129 39 30923 23 15098 93 29734 39 42739 63 presentvalue0 07 109129 39 30923 23 15098 93 29734 39 175519 15 presentvalue1 109129 39 30923 23 15098 93 29734 39 traceback most recent call last valueerror discount rate cannot be negative presentvalue0 03 traceback most recent call last valueerror cash flows list cannot be empty present_value 0 13 10 20 70 293 297 4 69 present_value 0 07 109129 39 30923 23 15098 93 29734 39 42739 63 present_value 0 07 109129 39 30923 23 15098 93 29734 39 175519 15 present_value 1 109129 39 30923 23 15098 93 29734 39 traceback most recent call last valueerror discount rate cannot be negative present_value 0 03 traceback most recent call last valueerror cash flows list cannot be empty
def present_value(discount_rate: float, cash_flows: list[float]) -> float: if discount_rate < 0: raise ValueError("Discount rate cannot be negative") if not cash_flows: raise ValueError("Cash flows list cannot be empty") present_value = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(cash_flows) ) return round(present_value, ndigits=2) if __name__ == "__main__": import doctest doctest.testmod()
calculate price plus tax of a good or service given its price and a tax rate priceplustax100 0 25 125 0 priceplustax125 50 0 05 131 775 price_plus_tax 100 0 25 125 0 price_plus_tax 125 50 0 05 131 775
def price_plus_tax(price: float, tax_rate: float) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(f"{price_plus_tax(100, 0.25) = }") print(f"{price_plus_tax(125.50, 0.05) = }")
the simple moving average sma is a statistical calculation used to analyze data points by creating a constantly updated average price over a specific time period in finance sma is often used in time series analysis to smooth out price data and identify trends reference https en wikipedia orgwikimovingaverage calculate the simple moving average sma for some given time series data param data a list of numerical data points param windowsize an integer representing the size of the sma window return a list of sma values with the same length as the input data examples sma simplemovingaverage10 12 15 13 14 16 18 17 19 21 3 roundvalue 2 if value is not none else none for value in sma none none 12 33 13 33 14 0 14 33 16 0 17 0 18 0 19 0 simplemovingaverage10 12 15 5 none none none simplemovingaverage10 12 15 13 14 16 18 17 19 21 0 traceback most recent call last valueerror window size must be a positive integer example data replace with your own time series data specify the window size for the sma calculate the simple moving average print the sma values calculate the simple moving average sma for some given time series data param data a list of numerical data points param window_size an integer representing the size of the sma window return a list of sma values with the same length as the input data examples sma simple_moving_average 10 12 15 13 14 16 18 17 19 21 3 round value 2 if value is not none else none for value in sma none none 12 33 13 33 14 0 14 33 16 0 17 0 18 0 19 0 simple_moving_average 10 12 15 5 none none none simple_moving_average 10 12 15 13 14 16 18 17 19 21 0 traceback most recent call last valueerror window size must be a positive integer sma not available for early data points example data replace with your own time series data specify the window size for the sma calculate the simple moving average print the sma values
from collections.abc import Sequence def simple_moving_average( data: Sequence[float], window_size: int ) -> list[float | None]: if window_size < 1: raise ValueError("Window size must be a positive integer") sma: list[float | None] = [] for i in range(len(data)): if i < window_size - 1: sma.append(None) else: window = data[i - window_size + 1 : i + 1] sma_value = sum(window) / window_size sma.append(sma_value) return sma if __name__ == "__main__": import doctest doctest.testmod() data = [10, 12, 15, 13, 14, 16, 18, 17, 19, 21] window_size = 3 sma_values = simple_moving_average(data, window_size) print("Simple Moving Average (SMA) Values:") for i, value in enumerate(sma_values): if value is not None: print(f"Day {i + 1}: {value:.2f}") else: print(f"Day {i + 1}: Not enough data for SMA")
alexandre de zotti draws julia sets of quadratic polynomials and exponential maps more specifically this iterates the function a fixed number of times then plots whether the absolute value of the last iterate is greater than a fixed threshold named escape radius for the exponential map this is not really an escape radius but rather a convenient way to approximate the julia set with bounded orbits the examples presented here are the cauliflower julia set see e g https en wikipedia orgwikifile juliaz22b0 25 png other examples from https en wikipedia orgwikijuliaset an exponential map julia set ambiantly homeomorphic to the examples in https www math univtoulouse frcheritatgaliigalery html and https ddd uab catpubpubmat02141493v43n102141493v43n1p27 pdf remark some overflow runtime warnings are suppressed this is because of the way the iteration loop is implemented using numpy s efficient computations overflows and infinites are replaced after each step by a large number evaluate ez c evalexponential0 0 1 0 absevalexponential1 numpy pi1 j 1e15 true absevalexponential1 j 011 j 1e15 true evalquadraticpolynomial0 2 4 evalquadraticpolynomial1 1 0 roundevalquadraticpolynomial1 j 0 imag 1 roundevalquadraticpolynomial1 j 0 real 0 create a grid of complex values of size nbpixelsnbpixels with real and imaginary parts ranging from windowsize to windowsize inclusive returns a numpy array preparegrid1 3 array1 1 j 1 0 j 1 1 j 0 1 j 0 0 j 0 1 j 1 1 j 1 0 j 1 1 j iterate the function evalfunction exactly nbiterations times the first argument of the function is a parameter which is contained in functionparams the variable z0 is an array that contains the initial values to iterate from this function returns the final iterates iteratefunctionevalquadraticpolynomial 0 3 numpy array0 1 2 shape 3 numpy rounditeratefunctionevalquadraticpolynomial 0 3 numpy array0 1 20 0j numpy rounditeratefunctionevalquadraticpolynomial 0 3 numpy array0 1 21 10j numpy rounditeratefunctionevalquadraticpolynomial 0 3 numpy array0 1 22 2560j plots of whether the absolute value of zfinal is greater than the value of escaperadius adds the functionlabel and functionparams to the title showresults 80 0 1 numpy array0 1 5 4 2 1 1 2 1 1 3 ignore some overflow and invalid value warnings ignoreoverflowwarnings evaluate e z c eval_exponential 0 0 1 0 abs eval_exponential 1 numpy pi 1 j 1e 15 true abs eval_exponential 1 j 0 1 1 j 1e 15 true eval_quadratic_polynomial 0 2 4 eval_quadratic_polynomial 1 1 0 round eval_quadratic_polynomial 1 j 0 imag 1 round eval_quadratic_polynomial 1 j 0 real 0 create a grid of complex values of size nb_pixels nb_pixels with real and imaginary parts ranging from window_size to window_size inclusive returns a numpy array prepare_grid 1 3 array 1 1 j 1 0 j 1 1 j 0 1 j 0 0 j 0 1 j 1 1 j 1 0 j 1 1 j iterate the function eval_function exactly nb_iterations times the first argument of the function is a parameter which is contained in function_params the variable z_0 is an array that contains the initial values to iterate from this function returns the final iterates iterate_function eval_quadratic_polynomial 0 3 numpy array 0 1 2 shape 3 numpy round iterate_function eval_quadratic_polynomial 0 3 numpy array 0 1 2 0 0j numpy round iterate_function eval_quadratic_polynomial 0 3 numpy array 0 1 2 1 1 0j numpy round iterate_function eval_quadratic_polynomial 0 3 numpy array 0 1 2 2 256 0j plots of whether the absolute value of z_final is greater than the value of escape_radius adds the function_label and function_params to the title show_results 80 0 1 numpy array 0 1 5 4 2 1 1 2 1 1 3 ignore some overflow and invalid value warnings ignore_overflow_warnings see file header for explanations
import warnings from collections.abc import Callable from typing import Any import numpy from matplotlib import pyplot c_cauliflower = 0.25 + 0.0j c_polynomial_1 = -0.4 + 0.6j c_polynomial_2 = -0.1 + 0.651j c_exponential = -2.0 nb_iterations = 56 window_size = 2.0 nb_pixels = 666 def eval_exponential(c_parameter: complex, z_values: numpy.ndarray) -> numpy.ndarray: return numpy.exp(z_values) + c_parameter def eval_quadratic_polynomial( c_parameter: complex, z_values: numpy.ndarray ) -> numpy.ndarray: return z_values * z_values + c_parameter def prepare_grid(window_size: float, nb_pixels: int) -> numpy.ndarray: x = numpy.linspace(-window_size, window_size, nb_pixels) x = x.reshape((nb_pixels, 1)) y = numpy.linspace(-window_size, window_size, nb_pixels) y = y.reshape((1, nb_pixels)) return x + 1.0j * y def iterate_function( eval_function: Callable[[Any, numpy.ndarray], numpy.ndarray], function_params: Any, nb_iterations: int, z_0: numpy.ndarray, infinity: float | None = None, ) -> numpy.ndarray: z_n = z_0.astype("complex64") for _ in range(nb_iterations): z_n = eval_function(function_params, z_n) if infinity is not None: numpy.nan_to_num(z_n, copy=False, nan=infinity) z_n[abs(z_n) == numpy.inf] = infinity return z_n def show_results( function_label: str, function_params: Any, escape_radius: float, z_final: numpy.ndarray, ) -> None: abs_z_final = (abs(z_final)).transpose() abs_z_final[:, :] = abs_z_final[::-1, :] pyplot.matshow(abs_z_final < escape_radius) pyplot.title(f"Julia set of ${function_label}$, $c={function_params}$") pyplot.show() def ignore_overflow_warnings() -> None: warnings.filterwarnings( "ignore", category=RuntimeWarning, message="overflow encountered in multiply" ) warnings.filterwarnings( "ignore", category=RuntimeWarning, message="invalid value encountered in multiply", ) warnings.filterwarnings( "ignore", category=RuntimeWarning, message="overflow encountered in absolute" ) warnings.filterwarnings( "ignore", category=RuntimeWarning, message="overflow encountered in exp" ) if __name__ == "__main__": z_0 = prepare_grid(window_size, nb_pixels) ignore_overflow_warnings() nb_iterations = 24 escape_radius = 2 * abs(c_cauliflower) + 1 z_final = iterate_function( eval_quadratic_polynomial, c_cauliflower, nb_iterations, z_0, infinity=1.1 * escape_radius, ) show_results("z^2+c", c_cauliflower, escape_radius, z_final) nb_iterations = 64 escape_radius = 2 * abs(c_polynomial_1) + 1 z_final = iterate_function( eval_quadratic_polynomial, c_polynomial_1, nb_iterations, z_0, infinity=1.1 * escape_radius, ) show_results("z^2+c", c_polynomial_1, escape_radius, z_final) nb_iterations = 161 escape_radius = 2 * abs(c_polynomial_2) + 1 z_final = iterate_function( eval_quadratic_polynomial, c_polynomial_2, nb_iterations, z_0, infinity=1.1 * escape_radius, ) show_results("z^2+c", c_polynomial_2, escape_radius, z_final) nb_iterations = 12 escape_radius = 10000.0 z_final = iterate_function( eval_exponential, c_exponential, nb_iterations, z_0 + 2, infinity=1.0e10, ) show_results("e^z+c", c_exponential, escape_radius, z_final)
description the koch snowflake is a fractal curve and one of the earliest fractals to have been described the koch snowflake can be built up iteratively in a sequence of stages the first stage is an equilateral triangle and each successive stage is formed by adding outward bends to each side of the previous stage making smaller equilateral triangles this can be achieved through the following steps for each line 1 divide the line segment into three segments of equal length 2 draw an equilateral triangle that has the middle segment from step 1 as its base and points outward 3 remove the line segment that is the base of the triangle from step 2 description adapted from https en wikipedia orgwikikochsnowflake for a more detailed explanation and an implementation in the processing language see https natureofcode combookchapter8fractals 84thekochcurveandthearraylisttechnique requirements pip matplotlib numpy initial triangle of koch snowflake uncomment for simple koch curve instead of koch snowflake initialvectors vector1 vector3 go through the number of iterations determined by the argument steps be careful with high values above 5 since the time to calculate increases exponentially iteratenumpy array0 0 numpy array1 0 1 array0 0 array0 33333333 0 array0 5 0 28867513 array0 66666667 0 array1 0 loops through each pair of adjacent vectors each line between two adjacent vectors is divided into 4 segments by adding 3 additional vectors inbetween the original two vectors the vector in the middle is constructed through a 60 degree rotation so it is bent outwards iterationstepnumpy array0 0 numpy array1 0 array0 0 array0 33333333 0 array0 5 0 28867513 array0 66666667 0 array1 0 standard rotation of a 2d vector with a rotation matrix see https en wikipedia orgwikirotationmatrix rotatenumpy array1 0 60 array0 5 0 8660254 rotatenumpy array1 0 90 array6 123234e17 1 000000e00 utility function to plot the vectors using matplotlib pyplot no doctest was implemented since this function does not have a return value avoid stretched display of graph matplotlib pyplot plot takes a list of all xcoordinates and a list of all ycoordinates as inputs which are constructed from the vectorlist using zip type ignore initial triangle of koch snowflake uncomment for simple koch curve instead of koch snowflake initial_vectors vector_1 vector_3 go through the number of iterations determined by the argument steps be careful with high values above 5 since the time to calculate increases exponentially iterate numpy array 0 0 numpy array 1 0 1 array 0 0 array 0 33333333 0 array 0 5 0 28867513 array 0 66666667 0 array 1 0 loops through each pair of adjacent vectors each line between two adjacent vectors is divided into 4 segments by adding 3 additional vectors in between the original two vectors the vector in the middle is constructed through a 60 degree rotation so it is bent outwards iteration_step numpy array 0 0 numpy array 1 0 array 0 0 array 0 33333333 0 array 0 5 0 28867513 array 0 66666667 0 array 1 0 standard rotation of a 2d vector with a rotation matrix see https en wikipedia org wiki rotation_matrix rotate numpy array 1 0 60 array 0 5 0 8660254 rotate numpy array 1 0 90 array 6 123234e 17 1 000000e 00 utility function to plot the vectors using matplotlib pyplot no doctest was implemented since this function does not have a return value avoid stretched display of graph matplotlib pyplot plot takes a list of all x coordinates and a list of all y coordinates as inputs which are constructed from the vector list using zip
from __future__ import annotations import matplotlib.pyplot as plt import numpy VECTOR_1 = numpy.array([0, 0]) VECTOR_2 = numpy.array([0.5, 0.8660254]) VECTOR_3 = numpy.array([1, 0]) INITIAL_VECTORS = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] def iterate(initial_vectors: list[numpy.ndarray], steps: int) -> list[numpy.ndarray]: vectors = initial_vectors for _ in range(steps): vectors = iteration_step(vectors) return vectors def iteration_step(vectors: list[numpy.ndarray]) -> list[numpy.ndarray]: new_vectors = [] for i, start_vector in enumerate(vectors[:-1]): end_vector = vectors[i + 1] new_vectors.append(start_vector) difference_vector = end_vector - start_vector new_vectors.append(start_vector + difference_vector / 3) new_vectors.append( start_vector + difference_vector / 3 + rotate(difference_vector / 3, 60) ) new_vectors.append(start_vector + difference_vector * 2 / 3) new_vectors.append(vectors[-1]) return new_vectors def rotate(vector: numpy.ndarray, angle_in_degrees: float) -> numpy.ndarray: theta = numpy.radians(angle_in_degrees) c, s = numpy.cos(theta), numpy.sin(theta) rotation_matrix = numpy.array(((c, -s), (s, c))) return numpy.dot(rotation_matrix, vector) def plot(vectors: list[numpy.ndarray]) -> None: axes = plt.gca() axes.set_aspect("equal") x_coordinates, y_coordinates = zip(*vectors) plt.plot(x_coordinates, y_coordinates) plt.show() if __name__ == "__main__": import doctest doctest.testmod() processed_vectors = iterate(INITIAL_VECTORS, 5) plot(processed_vectors)