Description
stringlengths
18
161k
Code
stringlengths
15
300k
conversion of volume units available units cubic metre litre kilolitre gallon cubic yard cubic foot cup usage import this file into their respective project use the function lengthconversion for conversion of volume units parameters value the number of from units you want to convert fromtype from which type you want to convert totype to which type you want to convert references wikipedia reference https en wikipedia orgwikicubicmetre wikipedia reference https en wikipedia orgwikilitre wikipedia reference https en wiktionary orgwikikilolitre wikipedia reference https en wikipedia orgwikigallon wikipedia reference https en wikipedia orgwikicubicyard wikipedia reference https en wikipedia orgwikicubicfoot wikipedia reference https en wikipedia orgwikicupunit conversion between volume units volumeconversion4 cubic meter litre 4000 volumeconversion1 litre gallon 0 264172 volumeconversion1 kilolitre cubic meter 1 volumeconversion3 gallon cubic yard 0 017814279 volumeconversion2 cubic yard litre 1529 1 volumeconversion4 cubic foot cup 473 396 volumeconversion1 cup kilolitre 0 000236588 volumeconversion4 wrongunit litre traceback most recent call last valueerror invalid fromtype value wrongunit supported values are cubic meter litre kilolitre gallon cubic yard cubic foot cup conversion between volume units volume_conversion 4 cubic meter litre 4000 volume_conversion 1 litre gallon 0 264172 volume_conversion 1 kilolitre cubic meter 1 volume_conversion 3 gallon cubic yard 0 017814279 volume_conversion 2 cubic yard litre 1529 1 volume_conversion 4 cubic foot cup 473 396 volume_conversion 1 cup kilolitre 0 000236588 volume_conversion 4 wrongunit litre traceback most recent call last valueerror invalid from_type value wrongunit supported values are cubic meter litre kilolitre gallon cubic yard cubic foot cup
from typing import NamedTuple class FromTo(NamedTuple): from_factor: float to_factor: float METRIC_CONVERSION = { "cubic meter": FromTo(1, 1), "litre": FromTo(0.001, 1000), "kilolitre": FromTo(1, 1), "gallon": FromTo(0.00454, 264.172), "cubic yard": FromTo(0.76455, 1.30795), "cubic foot": FromTo(0.028, 35.3147), "cup": FromTo(0.000236588, 4226.75), } def volume_conversion(value: float, from_type: str, to_type: str) -> float: if from_type not in METRIC_CONVERSION: raise ValueError( f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + ", ".join(METRIC_CONVERSION) ) if to_type not in METRIC_CONVERSION: raise ValueError( f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + ", ".join(METRIC_CONVERSION) ) return ( value * METRIC_CONVERSION[from_type].from_factor * METRIC_CONVERSION[to_type].to_factor ) if __name__ == "__main__": import doctest doctest.testmod()
conversion of weight units anubhav solanki license mit version 1 1 0 maintainer anubhav solanki email anubhavsolanki0gmail com usage import this file into their respective project use the function weightconversion for conversion of weight units parameters fromtype from which type you want to convert totype to which type you want to convert value the value which you want to convert references wikipedia reference https en wikipedia orgwikikilogram wikipedia reference https en wikipedia orgwikigram wikipedia reference https en wikipedia orgwikimillimetre wikipedia reference https en wikipedia orgwikitonne wikipedia reference https en wikipedia orgwikilongton wikipedia reference https en wikipedia orgwikishortton wikipedia reference https en wikipedia orgwikipound wikipedia reference https en wikipedia orgwikiounce wikipedia reference https en wikipedia orgwikifinenesskarat wikipedia reference https en wikipedia orgwikidaltonunit wikipedia reference https en wikipedia orgwikistoneunit conversion of weight unit with the help of kilogramchart kilogram 1 gram pow10 3 milligram pow10 6 metricton pow10 3 longton 0 0009842073 shortton 0 0011023122 pound 2 2046244202 stone 0 1574731728 ounce 35 273990723 carrat 5000 atomicmassunit 6 022136652e26 weightconversionkilogram kilogram 4 4 weightconversionkilogram gram 1 1000 weightconversionkilogram milligram 4 4000000 weightconversionkilogram metricton 4 0 004 weightconversionkilogram longton 3 0 0029526219 weightconversionkilogram shortton 1 0 0011023122 weightconversionkilogram pound 4 8 8184976808 weightconversionkilogram stone 5 0 7873658640000001 weightconversionkilogram ounce 4 141 095962892 weightconversionkilogram carrat 3 15000 weightconversionkilogram atomicmassunit 1 6 022136652e26 weightconversiongram kilogram 1 0 001 weightconversiongram gram 3 3 0 weightconversiongram milligram 2 2000 0 weightconversiongram metricton 4 4e06 weightconversiongram longton 3 2 9526219e06 weightconversiongram shortton 3 3 3069366000000003e06 weightconversiongram pound 3 0 0066138732606 weightconversiongram stone 4 0 0006298926912000001 weightconversiongram ounce 1 0 035273990723 weightconversiongram carrat 2 10 0 weightconversiongram atomicmassunit 1 6 022136652e23 weightconversionmilligram kilogram 1 1e06 weightconversionmilligram gram 2 0 002 weightconversionmilligram milligram 3 3 0 weightconversionmilligram metricton 3 3e09 weightconversionmilligram longton 3 2 9526219e09 weightconversionmilligram shortton 1 1 1023122e09 weightconversionmilligram pound 3 6 6138732605999995e06 weightconversionmilligram ounce 2 7 054798144599999e05 weightconversionmilligram carrat 1 0 005 weightconversionmilligram atomicmassunit 1 6 022136652e20 weightconversionmetricton kilogram 2 2000 weightconversionmetricton gram 2 2000000 weightconversionmetricton milligram 3 3000000000 weightconversionmetricton metricton 2 2 0 weightconversionmetricton longton 3 2 9526219 weightconversionmetricton shortton 2 2 2046244 weightconversionmetricton pound 3 6613 8732606 weightconversionmetricton ounce 4 141095 96289199998 weightconversionmetricton carrat 4 20000000 weightconversionmetricton atomicmassunit 1 6 022136652e29 weightconversionlongton kilogram 4 4064 18432 weightconversionlongton gram 4 4064184 32 weightconversionlongton milligram 3 3048138240 0 weightconversionlongton metricton 4 4 06418432 weightconversionlongton longton 3 2 999999907217152 weightconversionlongton shortton 1 1 119999989746176 weightconversionlongton pound 3 6720 000000049448 weightconversionlongton ounce 1 35840 000000060514 weightconversionlongton carrat 4 20320921 599999998 weightconversionlongton atomicmassunit 4 2 4475073353955697e30 weightconversionshortton kilogram 3 2721 5519999999997 weightconversionshortton gram 3 2721552 0 weightconversionshortton milligram 1 907184000 0 weightconversionshortton metricton 4 3 628736 weightconversionshortton longton 3 2 6785713457296 weightconversionshortton shortton 3 2 9999999725344 weightconversionshortton pound 2 4000 0000000294335 weightconversionshortton ounce 4 128000 00000021611 weightconversionshortton carrat 4 18143680 0 weightconversionshortton atomicmassunit 1 5 463186016507968e29 weightconversionpound kilogram 4 1 814368 weightconversionpound gram 2 907 184 weightconversionpound milligram 3 1360776 0 weightconversionpound metricton 3 0 001360776 weightconversionpound longton 2 0 0008928571152432 weightconversionpound shortton 1 0 0004999999954224 weightconversionpound pound 3 3 0000000000220752 weightconversionpound ounce 1 16 000000000027015 weightconversionpound carrat 1 2267 96 weightconversionpound atomicmassunit 4 1 0926372033015936e27 weightconversionstone kilogram 5 31 751450000000002 weightconversionstone gram 2 12700 58 weightconversionstone milligram 3 19050870 0 weightconversionstone metricton 3 0 01905087 weightconversionstone longton 3 0 018750005325351003 weightconversionstone shortton 3 0 021000006421614002 weightconversionstone pound 2 28 00000881870372 weightconversionstone ounce 1 224 00007054835967 weightconversionstone carrat 2 63502 9 weightconversionounce kilogram 3 0 0850485 weightconversionounce gram 3 85 0485 weightconversionounce milligram 4 113398 0 weightconversionounce metricton 4 0 000113398 weightconversionounce longton 4 0 0001116071394054 weightconversionounce shortton 4 0 0001249999988556 weightconversionounce pound 1 0 0625000000004599 weightconversionounce ounce 2 2 000000000003377 weightconversionounce carrat 1 141 7475 weightconversionounce atomicmassunit 1 1 70724563015874e25 weightconversioncarrat kilogram 1 0 0002 weightconversioncarrat gram 4 0 8 weightconversioncarrat milligram 2 400 0 weightconversioncarrat metricton 2 4 0000000000000003e07 weightconversioncarrat longton 3 5 9052438e07 weightconversioncarrat shortton 4 8 818497600000002e07 weightconversioncarrat pound 1 0 00044092488404000004 weightconversioncarrat ounce 2 0 0141095962892 weightconversioncarrat carrat 4 4 0 weightconversioncarrat atomicmassunit 4 4 8177093216e23 weightconversionatomicmassunit kilogram 4 6 642160796e27 weightconversionatomicmassunit gram 2 3 321080398e24 weightconversionatomicmassunit milligram 2 3 3210803980000002e21 weightconversionatomicmassunit metricton 3 4 9816205970000004e30 weightconversionatomicmassunit longton 3 4 9029473573977584e30 weightconversionatomicmassunit shortton 1 1 830433719948128e30 weightconversionatomicmassunit pound 3 1 0982602420317504e26 weightconversionatomicmassunit ounce 2 1 1714775914938915e25 weightconversionatomicmassunit carrat 2 1 660540199e23 weightconversionatomicmassunit atomicmassunit 2 1 999999998903455 conversion of weight unit with the help of kilogram_chart kilogram 1 gram pow 10 3 milligram pow 10 6 metric ton pow 10 3 long ton 0 0009842073 short ton 0 0011023122 pound 2 2046244202 stone 0 1574731728 ounce 35 273990723 carrat 5000 atomic mass unit 6 022136652e 26 weight_conversion kilogram kilogram 4 4 weight_conversion kilogram gram 1 1000 weight_conversion kilogram milligram 4 4000000 weight_conversion kilogram metric ton 4 0 004 weight_conversion kilogram long ton 3 0 0029526219 weight_conversion kilogram short ton 1 0 0011023122 weight_conversion kilogram pound 4 8 8184976808 weight_conversion kilogram stone 5 0 7873658640000001 weight_conversion kilogram ounce 4 141 095962892 weight_conversion kilogram carrat 3 15000 weight_conversion kilogram atomic mass unit 1 6 022136652e 26 weight_conversion gram kilogram 1 0 001 weight_conversion gram gram 3 3 0 weight_conversion gram milligram 2 2000 0 weight_conversion gram metric ton 4 4e 06 weight_conversion gram long ton 3 2 9526219e 06 weight_conversion gram short ton 3 3 3069366000000003e 06 weight_conversion gram pound 3 0 0066138732606 weight_conversion gram stone 4 0 0006298926912000001 weight_conversion gram ounce 1 0 035273990723 weight_conversion gram carrat 2 10 0 weight_conversion gram atomic mass unit 1 6 022136652e 23 weight_conversion milligram kilogram 1 1e 06 weight_conversion milligram gram 2 0 002 weight_conversion milligram milligram 3 3 0 weight_conversion milligram metric ton 3 3e 09 weight_conversion milligram long ton 3 2 9526219e 09 weight_conversion milligram short ton 1 1 1023122e 09 weight_conversion milligram pound 3 6 6138732605999995e 06 weight_conversion milligram ounce 2 7 054798144599999e 05 weight_conversion milligram carrat 1 0 005 weight_conversion milligram atomic mass unit 1 6 022136652e 20 weight_conversion metric ton kilogram 2 2000 weight_conversion metric ton gram 2 2000000 weight_conversion metric ton milligram 3 3000000000 weight_conversion metric ton metric ton 2 2 0 weight_conversion metric ton long ton 3 2 9526219 weight_conversion metric ton short ton 2 2 2046244 weight_conversion metric ton pound 3 6613 8732606 weight_conversion metric ton ounce 4 141095 96289199998 weight_conversion metric ton carrat 4 20000000 weight_conversion metric ton atomic mass unit 1 6 022136652e 29 weight_conversion long ton kilogram 4 4064 18432 weight_conversion long ton gram 4 4064184 32 weight_conversion long ton milligram 3 3048138240 0 weight_conversion long ton metric ton 4 4 06418432 weight_conversion long ton long ton 3 2 999999907217152 weight_conversion long ton short ton 1 1 119999989746176 weight_conversion long ton pound 3 6720 000000049448 weight_conversion long ton ounce 1 35840 000000060514 weight_conversion long ton carrat 4 20320921 599999998 weight_conversion long ton atomic mass unit 4 2 4475073353955697e 30 weight_conversion short ton kilogram 3 2721 5519999999997 weight_conversion short ton gram 3 2721552 0 weight_conversion short ton milligram 1 907184000 0 weight_conversion short ton metric ton 4 3 628736 weight_conversion short ton long ton 3 2 6785713457296 weight_conversion short ton short ton 3 2 9999999725344 weight_conversion short ton pound 2 4000 0000000294335 weight_conversion short ton ounce 4 128000 00000021611 weight_conversion short ton carrat 4 18143680 0 weight_conversion short ton atomic mass unit 1 5 463186016507968e 29 weight_conversion pound kilogram 4 1 814368 weight_conversion pound gram 2 907 184 weight_conversion pound milligram 3 1360776 0 weight_conversion pound metric ton 3 0 001360776 weight_conversion pound long ton 2 0 0008928571152432 weight_conversion pound short ton 1 0 0004999999954224 weight_conversion pound pound 3 3 0000000000220752 weight_conversion pound ounce 1 16 000000000027015 weight_conversion pound carrat 1 2267 96 weight_conversion pound atomic mass unit 4 1 0926372033015936e 27 weight_conversion stone kilogram 5 31 751450000000002 weight_conversion stone gram 2 12700 58 weight_conversion stone milligram 3 19050870 0 weight_conversion stone metric ton 3 0 01905087 weight_conversion stone long ton 3 0 018750005325351003 weight_conversion stone short ton 3 0 021000006421614002 weight_conversion stone pound 2 28 00000881870372 weight_conversion stone ounce 1 224 00007054835967 weight_conversion stone carrat 2 63502 9 weight_conversion ounce kilogram 3 0 0850485 weight_conversion ounce gram 3 85 0485 weight_conversion ounce milligram 4 113398 0 weight_conversion ounce metric ton 4 0 000113398 weight_conversion ounce long ton 4 0 0001116071394054 weight_conversion ounce short ton 4 0 0001249999988556 weight_conversion ounce pound 1 0 0625000000004599 weight_conversion ounce ounce 2 2 000000000003377 weight_conversion ounce carrat 1 141 7475 weight_conversion ounce atomic mass unit 1 1 70724563015874e 25 weight_conversion carrat kilogram 1 0 0002 weight_conversion carrat gram 4 0 8 weight_conversion carrat milligram 2 400 0 weight_conversion carrat metric ton 2 4 0000000000000003e 07 weight_conversion carrat long ton 3 5 9052438e 07 weight_conversion carrat short ton 4 8 818497600000002e 07 weight_conversion carrat pound 1 0 00044092488404000004 weight_conversion carrat ounce 2 0 0141095962892 weight_conversion carrat carrat 4 4 0 weight_conversion carrat atomic mass unit 4 4 8177093216e 23 weight_conversion atomic mass unit kilogram 4 6 642160796e 27 weight_conversion atomic mass unit gram 2 3 321080398e 24 weight_conversion atomic mass unit milligram 2 3 3210803980000002e 21 weight_conversion atomic mass unit metric ton 3 4 9816205970000004e 30 weight_conversion atomic mass unit long ton 3 4 9029473573977584e 30 weight_conversion atomic mass unit short ton 1 1 830433719948128e 30 weight_conversion atomic mass unit pound 3 1 0982602420317504e 26 weight_conversion atomic mass unit ounce 2 1 1714775914938915e 25 weight_conversion atomic mass unit carrat 2 1 660540199e 23 weight_conversion atomic mass unit atomic mass unit 2 1 999999998903455
KILOGRAM_CHART: dict[str, float] = { "kilogram": 1, "gram": pow(10, 3), "milligram": pow(10, 6), "metric-ton": pow(10, -3), "long-ton": 0.0009842073, "short-ton": 0.0011023122, "pound": 2.2046244202, "stone": 0.1574731728, "ounce": 35.273990723, "carrat": 5000, "atomic-mass-unit": 6.022136652e26, } WEIGHT_TYPE_CHART: dict[str, float] = { "kilogram": 1, "gram": pow(10, -3), "milligram": pow(10, -6), "metric-ton": pow(10, 3), "long-ton": 1016.04608, "short-ton": 907.184, "pound": 0.453592, "stone": 6.35029, "ounce": 0.0283495, "carrat": 0.0002, "atomic-mass-unit": 1.660540199e-27, } def weight_conversion(from_type: str, to_type: str, value: float) -> float: if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART: msg = ( f"Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n" f"Supported values are: {', '.join(WEIGHT_TYPE_CHART)}" ) raise ValueError(msg) return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type] if __name__ == "__main__": import doctest doctest.testmod()
find the equilibrium index of an array reference https www geeksforgeeks orgequilibriumindexofanarray python doctest can be run with the following command python m doctest v equilibriumindex py given a sequence arr of size n this function returns an equilibrium index if any or 1 if no equilibrium index exists the equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes example input arr 7 1 5 2 4 3 0 output 3 find the equilibrium index of an array args arr listint the input array of integers returns int the equilibrium index or 1 if no equilibrium index exists examples equilibriumindex7 1 5 2 4 3 0 3 equilibriumindex1 2 3 4 5 1 equilibriumindex1 1 1 1 1 2 equilibriumindex2 4 6 8 10 3 1 find the equilibrium index of an array args arr list int the input array of integers returns int the equilibrium index or 1 if no equilibrium index exists examples equilibrium_index 7 1 5 2 4 3 0 3 equilibrium_index 1 2 3 4 5 1 equilibrium_index 1 1 1 1 1 2 equilibrium_index 2 4 6 8 10 3 1
def equilibrium_index(arr: list[int]) -> int: total_sum = sum(arr) left_sum = 0 for i, value in enumerate(arr): total_sum -= value if left_sum == total_sum: return i left_sum += value return -1 if __name__ == "__main__": import doctest doctest.testmod()
given a list of integers return elements a b c such that a b c 0 args nums list of integers returns list of lists of integers where sumeachlist 0 examples findtripletswith0sum1 0 1 2 1 4 1 1 2 1 0 1 findtripletswith0sum findtripletswith0sum0 0 0 0 0 0 findtripletswith0sum1 2 3 0 1 2 3 3 0 3 3 1 2 2 1 3 2 0 2 1 0 1 function for finding the triplets with a given sum in the array using hashing given a list of integers return elements a b c such that a b c 0 args nums list of integers returns list of lists of integers where sumeachlist 0 examples findtripletswith0sumhashing1 0 1 2 1 4 1 0 1 1 1 2 findtripletswith0sumhashing findtripletswith0sumhashing0 0 0 0 0 0 findtripletswith0sumhashing1 2 3 0 1 2 3 1 0 1 3 1 2 2 0 2 2 1 3 3 0 3 time complexity on2 auxiliary space on initialize the final output array with blank set the initial element as arri to store second elements that can complement the final sum current sum needed for reaching the target sum traverse the subarray arri1 required value for the second element verify if the desired value exists in the set finding triplet elements combination include the current element in the set for subsequent complement verification return all the triplet combinations given a list of integers return elements a b c such that a b c 0 args nums list of integers returns list of lists of integers where sum each_list 0 examples find_triplets_with_0_sum 1 0 1 2 1 4 1 1 2 1 0 1 find_triplets_with_0_sum find_triplets_with_0_sum 0 0 0 0 0 0 find_triplets_with_0_sum 1 2 3 0 1 2 3 3 0 3 3 1 2 2 1 3 2 0 2 1 0 1 function for finding the triplets with a given sum in the array using hashing given a list of integers return elements a b c such that a b c 0 args nums list of integers returns list of lists of integers where sum each_list 0 examples find_triplets_with_0_sum_hashing 1 0 1 2 1 4 1 0 1 1 1 2 find_triplets_with_0_sum_hashing find_triplets_with_0_sum_hashing 0 0 0 0 0 0 find_triplets_with_0_sum_hashing 1 2 3 0 1 2 3 1 0 1 3 1 2 2 0 2 2 1 3 3 0 3 time complexity o n 2 auxiliary space o n initialize the final output array with blank set the initial element as arr i to store second elements that can complement the final sum current sum needed for reaching the target sum traverse the subarray arr i 1 required value for the second element verify if the desired value exists in the set finding triplet elements combination include the current element in the set for subsequent complement verification return all the triplet combinations
from itertools import combinations def find_triplets_with_0_sum(nums: list[int]) -> list[list[int]]: return [ list(x) for x in sorted({abc for abc in combinations(sorted(nums), 3) if not sum(abc)}) ] def find_triplets_with_0_sum_hashing(arr: list[int]) -> list[list[int]]: target_sum = 0 output_arr = [] for index, item in enumerate(arr[:-2]): set_initialize = set() current_sum = target_sum - item for other_item in arr[index + 1 :]: required_value = current_sum - other_item if required_value in set_initialize: combination_array = sorted([item, other_item, required_value]) if combination_array not in output_arr: output_arr.append(combination_array) set_initialize.add(other_item) return output_arr if __name__ == "__main__": from doctest import testmod testmod()
retrieves the value of an 0indexed 1d index from a 2d array there are two ways to retrieve values 1 index2darrayiteratormatrix iteratorint this iterator allows you to iterate through a 2d array by passing in the matrix and calling nextyouriterator you can also use the iterator in a loop examples listindex2darrayiteratormatrix setindex2darrayiteratormatrix tupleindex2darrayiteratormatrix sumindex2darrayiteratormatrix 5 in index2darrayiteratormatrix 2 index2darrayin1darray listint index int int this function allows you to provide a 2d array and a 0indexed 1d integer index and retrieves the integer value at that index python doctests can be run using this command python3 m doctest v index2darrayin1d py tupleindex2darrayiterator5 523 1 34 0 5 523 1 34 0 tupleindex2darrayiterator5 523 1 34 0 5 523 1 34 0 tupleindex2darrayiterator5 523 1 34 0 5 523 1 34 0 t index2darrayiterator5 2 25 23 14 5 324 1 0 tuplet 5 2 25 23 14 5 324 1 0 listt 5 2 25 23 14 5 324 1 0 sortedt 1 0 2 5 5 14 23 25 324 tuplet3 23 sumt 397 1 in t true t iterindex2darrayiterator5 523 1 34 0 nextt 5 nextt 523 retrieves the value of the onedimensional index from a twodimensional array args array a 2d array of integers where all rows are the same size and all columns are the same size index a 1d index returns int the 0indexed value of the 1d index in the array examples index2darrayin1d0 1 2 3 4 5 6 7 8 9 10 11 5 5 index2darrayin1d0 1 2 3 4 5 6 7 8 9 10 11 1 traceback most recent call last valueerror index out of range index2darrayin1d0 1 2 3 4 5 6 7 8 9 10 11 12 traceback most recent call last valueerror index out of range index2darrayin1d 0 traceback most recent call last valueerror no items in array tuple index2darrayiterator 5 523 1 34 0 5 523 1 34 0 tuple index2darrayiterator 5 523 1 34 0 5 523 1 34 0 tuple index2darrayiterator 5 523 1 34 0 5 523 1 34 0 t index2darrayiterator 5 2 25 23 14 5 324 1 0 tuple t 5 2 25 23 14 5 324 1 0 list t 5 2 25 23 14 5 324 1 0 sorted t 1 0 2 5 5 14 23 25 324 tuple t 3 23 sum t 397 1 in t true t iter index2darrayiterator 5 523 1 34 0 next t 5 next t 523 retrieves the value of the one dimensional index from a two dimensional array args array a 2d array of integers where all rows are the same size and all columns are the same size index a 1d index returns int the 0 indexed value of the 1d index in the array examples index_2d_array_in_1d 0 1 2 3 4 5 6 7 8 9 10 11 5 5 index_2d_array_in_1d 0 1 2 3 4 5 6 7 8 9 10 11 1 traceback most recent call last valueerror index out of range index_2d_array_in_1d 0 1 2 3 4 5 6 7 8 9 10 11 12 traceback most recent call last valueerror index out of range index_2d_array_in_1d 0 traceback most recent call last valueerror no items in array
from collections.abc import Iterator from dataclasses import dataclass @dataclass class Index2DArrayIterator: matrix: list[list[int]] def __iter__(self) -> Iterator[int]: for row in self.matrix: yield from row def index_2d_array_in_1d(array: list[list[int]], index: int) -> int: rows = len(array) cols = len(array[0]) if rows == 0 or cols == 0: raise ValueError("no items in array") if index < 0 or index >= rows * cols: raise ValueError("index out of range") return array[index // cols][index % cols] if __name__ == "__main__": import doctest doctest.testmod()
given an array of integers and an integer k find the kth largest element in the array https stackoverflow comquestions251781 partitions list based on the pivot element this function rearranges the elements in the input list elements such that all elements greater than or equal to the chosen pivot are on the right side of the pivot and all elements smaller than the pivot are on the left side args arr the list to be partitioned low the lower index of the list high the higher index of the list returns int the index of pivot element after partitioning examples partition3 1 4 5 9 2 6 5 3 5 0 9 4 partition7 1 4 5 9 2 6 5 8 0 8 1 partition apple cherry date banana 0 3 2 partition3 1 1 2 5 6 4 7 0 3 1 finds the kth largest element in a list should deliver similar results to python def kthlargestelementarr position return sortedarrposition args nums the list of numbers k the position of the desired kth largest element returns int the kth largest element examples kthlargestelement3 1 4 1 5 9 2 6 5 3 5 3 5 kthlargestelement2 5 6 1 9 3 8 4 7 3 5 1 9 kthlargestelement2 5 6 1 9 3 8 4 7 3 5 2 traceback most recent call last valueerror invalid value of position kthlargestelement9 1 3 6 7 9 8 4 2 4 9 110 traceback most recent call last valueerror invalid value of position kthlargestelement1 2 4 3 5 9 7 6 5 9 3 0 traceback most recent call last valueerror invalid value of position kthlargestelement apple cherry date banana 2 cherry kthlargestelement3 1 1 2 5 6 4 7 7 9 5 0 2 5 6 kthlargestelement2 5 4 1 1 1 kthlargestelement 1 1 kthlargestelement3 1 1 2 5 6 4 7 7 9 5 0 1 5 traceback most recent call last valueerror the position should be an integer kthlargestelement4 6 1 2 4 traceback most recent call last typeerror tuple object does not support item assignment partitions list based on the pivot element this function rearranges the elements in the input list elements such that all elements greater than or equal to the chosen pivot are on the right side of the pivot and all elements smaller than the pivot are on the left side args arr the list to be partitioned low the lower index of the list high the higher index of the list returns int the index of pivot element after partitioning examples partition 3 1 4 5 9 2 6 5 3 5 0 9 4 partition 7 1 4 5 9 2 6 5 8 0 8 1 partition apple cherry date banana 0 3 2 partition 3 1 1 2 5 6 4 7 0 3 1 finds the kth largest element in a list should deliver similar results to python def kth_largest_element arr position return sorted arr position args nums the list of numbers k the position of the desired kth largest element returns int the kth largest element examples kth_largest_element 3 1 4 1 5 9 2 6 5 3 5 3 5 kth_largest_element 2 5 6 1 9 3 8 4 7 3 5 1 9 kth_largest_element 2 5 6 1 9 3 8 4 7 3 5 2 traceback most recent call last valueerror invalid value of position kth_largest_element 9 1 3 6 7 9 8 4 2 4 9 110 traceback most recent call last valueerror invalid value of position kth_largest_element 1 2 4 3 5 9 7 6 5 9 3 0 traceback most recent call last valueerror invalid value of position kth_largest_element apple cherry date banana 2 cherry kth_largest_element 3 1 1 2 5 6 4 7 7 9 5 0 2 5 6 kth_largest_element 2 5 4 1 1 1 kth_largest_element 1 1 kth_largest_element 3 1 1 2 5 6 4 7 7 9 5 0 1 5 traceback most recent call last valueerror the position should be an integer kth_largest_element 4 6 1 2 4 traceback most recent call last typeerror tuple object does not support item assignment
def partition(arr: list[int], low: int, high: int) -> int: pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] >= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 def kth_largest_element(arr: list[int], position: int) -> int: if not arr: return -1 if not isinstance(position, int): raise ValueError("The position should be an integer") if not 1 <= position <= len(arr): raise ValueError("Invalid value of 'position'") low, high = 0, len(arr) - 1 while low <= high: if low > len(arr) - 1 or high < 0: return -1 pivot_index = partition(arr, low, high) if pivot_index == position - 1: return arr[pivot_index] elif pivot_index > position - 1: high = pivot_index - 1 else: low = pivot_index + 1 return -1 if __name__ == "__main__": import doctest doctest.testmod()
https www enjoyalgorithms comblogmedianoftwosortedarrays find the median of two arrays args nums1 the first array nums2 the second array returns the median of the two arrays examples findmediansortedarrays1 3 2 2 0 findmediansortedarrays1 2 3 4 2 5 findmediansortedarrays0 0 0 0 0 0 findmediansortedarrays traceback most recent call last valueerror both input arrays are empty findmediansortedarrays 1 1 0 findmediansortedarrays1000 1000 0 0 findmediansortedarrays1 1 2 2 3 3 4 4 2 75 merge the arrays into a single sorted array if the total number of elements is even calculate the average of the two middle elements as the median find the median of two arrays args nums1 the first array nums2 the second array returns the median of the two arrays examples find_median_sorted_arrays 1 3 2 2 0 find_median_sorted_arrays 1 2 3 4 2 5 find_median_sorted_arrays 0 0 0 0 0 0 find_median_sorted_arrays traceback most recent call last valueerror both input arrays are empty find_median_sorted_arrays 1 1 0 find_median_sorted_arrays 1000 1000 0 0 find_median_sorted_arrays 1 1 2 2 3 3 4 4 2 75 merge the arrays into a single sorted array if the total number of elements is odd then return the middle element if the total number of elements is even calculate the average of the two middle elements as the median
def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float: if not nums1 and not nums2: raise ValueError("Both input arrays are empty.") merged = sorted(nums1 + nums2) total = len(merged) if total % 2 == 1: return float(merged[total // 2]) middle1 = merged[total // 2 - 1] middle2 = merged[total // 2] return (float(middle1) + float(middle2)) / 2.0 if __name__ == "__main__": import doctest doctest.testmod()
https leetcode comproblemsmonotonicarray check if a list is monotonic ismonotonic1 2 2 3 true ismonotonic6 5 4 4 true ismonotonic1 3 2 false test the function with your examples test the function with your examples https leetcode com problems monotonic array check if a list is monotonic is_monotonic 1 2 2 3 true is_monotonic 6 5 4 4 true is_monotonic 1 3 2 false test the function with your examples test the function with your examples output true output true output false
def is_monotonic(nums: list[int]) -> bool: return all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1)) or all( nums[i] >= nums[i + 1] for i in range(len(nums) - 1) ) if __name__ == "__main__": print(is_monotonic([1, 2, 2, 3])) print(is_monotonic([6, 5, 4, 4])) print(is_monotonic([1, 3, 2]))
usrbinenv python3 given an array of integers and an integer reqsum find the number of pairs of array elements whose sum is equal to reqsum https practice geeksforgeeks orgproblemscountpairswithgivensum50220 return the no of pairs with sum sum pairswithsum1 5 7 1 6 2 pairswithsum1 1 1 1 1 1 1 1 2 28 pairswithsum1 7 6 2 5 4 3 1 9 8 7 4 usr bin env python3 given an array of integers and an integer req_sum find the number of pairs of array elements whose sum is equal to req_sum https practice geeksforgeeks org problems count pairs with given sum5022 0 return the no of pairs with sum sum pairs_with_sum 1 5 7 1 6 2 pairs_with_sum 1 1 1 1 1 1 1 1 2 28 pairs_with_sum 1 7 6 2 5 4 3 1 9 8 7 4
from itertools import combinations def pairs_with_sum(arr: list, req_sum: int) -> int: return len([1 for a, b in combinations(arr, 2) if a + b == req_sum]) if __name__ == "__main__": from doctest import testmod testmod()
return all permutations permuterecursive1 2 3 3 2 1 2 3 1 1 3 2 3 1 2 2 1 3 1 2 3 return all permutations of the given list permutebacktrack1 2 3 1 2 3 1 3 2 2 1 3 2 3 1 3 2 1 3 1 2 return all permutations permute_recursive 1 2 3 3 2 1 2 3 1 1 3 2 3 1 2 2 1 3 1 2 3 return all permutations of the given list permute_backtrack 1 2 3 1 2 3 1 3 2 2 1 3 2 3 1 3 2 1 3 1 2 backtrack
def permute_recursive(nums: list[int]) -> list[list[int]]: result: list[list[int]] = [] if len(nums) == 0: return [[]] for _ in range(len(nums)): n = nums.pop(0) permutations = permute_recursive(nums.copy()) for perm in permutations: perm.append(n) result.extend(permutations) nums.append(n) return result def permute_backtrack(nums: list[int]) -> list[list[int]]: def backtrack(start: int) -> None: if start == len(nums) - 1: output.append(nums[:]) else: for i in range(start, len(nums)): nums[start], nums[i] = nums[i], nums[start] backtrack(start + 1) nums[start], nums[i] = nums[i], nums[start] output: list[list[int]] = [] backtrack(0) return output if __name__ == "__main__": import doctest result = permute_backtrack([1, 2, 3]) print(result) doctest.testmod()
alexander pantyukhin date november 3 2022 implement the class of prefix sum with useful functions based on it the function returns the sum of array from the start to the end indexes runtime o1 space o1 prefixsum1 2 3 getsum0 2 6 prefixsum1 2 3 getsum1 2 5 prefixsum1 2 3 getsum2 2 3 prefixsum1 2 3 getsum2 3 traceback most recent call last indexerror list index out of range the function returns true if array contains the targetsum false otherwise runtime on space on prefixsum1 2 3 containssum6 true prefixsum1 2 3 containssum5 true prefixsum1 2 3 containssum3 true prefixsum1 2 3 containssum4 false prefixsum1 2 3 containssum7 false prefixsum1 2 3 containssum2 true the function returns the sum of array from the start to the end indexes runtime o 1 space o 1 prefixsum 1 2 3 get_sum 0 2 6 prefixsum 1 2 3 get_sum 1 2 5 prefixsum 1 2 3 get_sum 2 2 3 prefixsum 1 2 3 get_sum 2 3 traceback most recent call last indexerror list index out of range the function returns true if array contains the target_sum false otherwise runtime o n space o n prefixsum 1 2 3 contains_sum 6 true prefixsum 1 2 3 contains_sum 5 true prefixsum 1 2 3 contains_sum 3 true prefixsum 1 2 3 contains_sum 4 false prefixsum 1 2 3 contains_sum 7 false prefixsum 1 2 3 contains_sum 2 true
class PrefixSum: def __init__(self, array: list[int]) -> None: len_array = len(array) self.prefix_sum = [0] * len_array if len_array > 0: self.prefix_sum[0] = array[0] for i in range(1, len_array): self.prefix_sum[i] = self.prefix_sum[i - 1] + array[i] def get_sum(self, start: int, end: int) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def contains_sum(self, target_sum: int) -> bool: sums = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(sum_item) return False if __name__ == "__main__": import doctest doctest.testmod()
calculate the product sum from a special array reference https dev tosfrasicaalgorithmsproductsumfromanarraydc6 python doctests can be run with the following command python m doctest v productsum py calculate the product sum of a special array which can contain integers or nested arrays the product sum is obtained by adding all elements and multiplying by their respective depths for example in the array x y the product sum is x y in the array x y z the product sum is x 2 y z in the array x y z the product sum is x 2 y 3z example input 5 2 7 1 3 6 13 8 4 output 12 recursively calculates the product sum of an array the product sum of an array is defined as the sum of its elements multiplied by their respective depths if an element is a list its product sum is calculated recursively by multiplying the sum of its elements with its depth plus one args arr the array of integers and nested lists depth the current depth level returns int the product sum of the array examples productsum1 2 3 1 6 productsum1 2 3 4 2 8 productsum1 2 3 1 6 productsum1 2 3 0 0 productsum1 2 3 7 42 productsum1 2 3 7 42 productsum1 2 3 7 42 productsum1 1 1 0 productsum1 2 1 1 productsum3 5 1 0 5 1 1 5 calculates the product sum of an array args array listunionint list the array of integers and nested lists returns int the product sum of the array examples productsumarray1 2 3 6 productsumarray1 2 3 11 productsumarray1 2 3 4 47 productsumarray0 0 productsumarray3 5 1 0 5 1 5 productsumarray1 2 1 recursively calculates the product sum of an array the product sum of an array is defined as the sum of its elements multiplied by their respective depths if an element is a list its product sum is calculated recursively by multiplying the sum of its elements with its depth plus one args arr the array of integers and nested lists depth the current depth level returns int the product sum of the array examples product_sum 1 2 3 1 6 product_sum 1 2 3 4 2 8 product_sum 1 2 3 1 6 product_sum 1 2 3 0 0 product_sum 1 2 3 7 42 product_sum 1 2 3 7 42 product_sum 1 2 3 7 42 product_sum 1 1 1 0 product_sum 1 2 1 1 product_sum 3 5 1 0 5 1 1 5 calculates the product sum of an array args array list union int list the array of integers and nested lists returns int the product sum of the array examples product_sum_array 1 2 3 6 product_sum_array 1 2 3 11 product_sum_array 1 2 3 4 47 product_sum_array 0 0 product_sum_array 3 5 1 0 5 1 5 product_sum_array 1 2 1
def product_sum(arr: list[int | list], depth: int) -> int: total_sum = 0 for ele in arr: total_sum += product_sum(ele, depth + 1) if isinstance(ele, list) else ele return total_sum * depth def product_sum_array(array: list[int | list]) -> int: return product_sum(array, 1) if __name__ == "__main__": import doctest doctest.testmod()
sparse table is a data structure that allows answering range queries on a static number list i e the elements do not change throughout all the queries the implementation below will solve the problem of range minimum query finding the minimum value of a subset l r of a static number list overall time complexity onlogn overall space complexity onlogn wikipedia link https en wikipedia orgwikirangeminimumquery precompute range minimum queries with power of two length and store the precomputed values in a table buildsparsetable8 1 0 3 4 9 3 8 1 0 3 4 9 3 1 0 0 3 4 3 0 0 0 0 3 0 0 0 buildsparsetable3 1 9 3 1 9 1 1 0 buildsparsetable traceback most recent call last valueerror empty number list not allowed initialise sparsetable sparsetableji represents the minimum value of the subset of length 2 j of numberlist starting from index i smallest power of 2 subset length that fully covers numberlist minimum of subset of length 1 is that value itself compute the minimum value for all intervals with size 2 j while subset starting from i still have at least 2 j elements split range i i 2 j and find minimum of 2 halves querybuildsparsetable8 1 0 3 4 9 3 0 4 0 querybuildsparsetable8 1 0 3 4 9 3 4 6 3 querybuildsparsetable3 1 9 2 2 9 querybuildsparsetable3 1 9 0 1 1 querybuildsparsetable8 1 0 3 4 9 3 0 11 traceback most recent call last indexerror list index out of range querybuildsparsetable 0 0 traceback most recent call last valueerror empty number list not allowed highest subset length of power of 2 that is within range leftbound rightbound minimum of 2 overlapping smaller subsets leftbound leftbound 2 j 1 and rightbound 2 j 1 rightbound precompute range minimum queries with power of two length and store the precomputed values in a table build_sparse_table 8 1 0 3 4 9 3 8 1 0 3 4 9 3 1 0 0 3 4 3 0 0 0 0 3 0 0 0 build_sparse_table 3 1 9 3 1 9 1 1 0 build_sparse_table traceback most recent call last valueerror empty number list not allowed initialise sparse_table sparse_table j i represents the minimum value of the subset of length 2 j of number_list starting from index i smallest power of 2 subset length that fully covers number_list minimum of subset of length 1 is that value itself compute the minimum value for all intervals with size 2 j while subset starting from i still have at least 2 j elements split range i i 2 j and find minimum of 2 halves query build_sparse_table 8 1 0 3 4 9 3 0 4 0 query build_sparse_table 8 1 0 3 4 9 3 4 6 3 query build_sparse_table 3 1 9 2 2 9 query build_sparse_table 3 1 9 0 1 1 query build_sparse_table 8 1 0 3 4 9 3 0 11 traceback most recent call last indexerror list index out of range query build_sparse_table 0 0 traceback most recent call last valueerror empty number list not allowed highest subset length of power of 2 that is within range left_bound right_bound minimum of 2 overlapping smaller subsets left_bound left_bound 2 j 1 and right_bound 2 j 1 right_bound
from math import log2 def build_sparse_table(number_list: list[int]) -> list[list[int]]: if not number_list: raise ValueError("empty number list not allowed") length = len(number_list) row = int(log2(length)) + 1 sparse_table = [[0 for i in range(length)] for j in range(row)] for i, value in enumerate(number_list): sparse_table[0][i] = value j = 1 while (1 << j) <= length: i = 0 while (i + (1 << j) - 1) < length: sparse_table[j][i] = min( sparse_table[j - 1][i + (1 << (j - 1))], sparse_table[j - 1][i] ) i += 1 j += 1 return sparse_table def query(sparse_table: list[list[int]], left_bound: int, right_bound: int) -> int: if left_bound < 0 or right_bound >= len(sparse_table[0]): raise IndexError("list index out of range") j = int(log2(right_bound - left_bound + 1)) return min(sparse_table[j][right_bound - (1 << j) + 1], sparse_table[j][left_bound]) if __name__ == "__main__": from doctest import testmod testmod() print(f"{query(build_sparse_table([3, 1, 9]), 2, 2) = }")
please do not modify this file it is published at https norvig comsudoku html with only minimal changes to work with modern versions of python if you have improvements please make them in a separate file fmt off fmt on convert grid to a dict of possible values square digits or return false if a contradiction is detected to start every square can be any digit then assign values from the grid values s digits for s in squares for s d in gridvaluesgrid items if d in digits and not assignvalues s d return false fail if we can t assign d to square s return values def gridvaluesgrid convert grid into a dict of square char with 0 or for empties chars c for c in grid if c in digits or c in 0 assert lenchars 81 return dictzipsquares chars def assignvalues s d eliminate d from valuess propagate when values or places 2 return values except return false if a contradiction is detected if d not in valuess return values already eliminated valuess valuess replaced 1 if a square s is reduced to one value d2 then eliminate d2 from the peers if lenvaluess 0 return false contradiction removed last value elif lenvaluess 1 d2 valuess if not alleliminatevalues s2 d2 for s2 in peerss return false 2 if a unit u is reduced to only one place for a value d then put it there for u in unitss dplaces s for s in u if d in valuess if lendplaces 0 return false contradiction no place for this value elif lendplaces 1 d can only be in one place in unit assign it there if not assignvalues dplaces0 d return false return values def displayvalues display these values as a 2d grid width 1 maxlenvaluess for s in squares line join width 3 3 for r in rows print join valuesr c centerwidth if c in 36 else for c in cols if r in cf printline print def solvegrid return searchparsegridgrid def someseq return some element of seq that is true for e in seq if e return e return false def searchvalues using depthfirst search and propagation try all possible values if values is false return false failed earlier if alllenvaluess 1 for s in squares return values solved chose the unfilled square s with the fewest possibilities n s minlenvaluess s for s in squares if lenvaluess 1 return somesearchassignvalues copy s d for d in valuess def solveallgrids name showif0 0 display puzzles that take long enough make a random puzzle with n or more assignments restart on contradictions note the resulting puzzle is not guaranteed to be solvable but empirically about 99 8 of them are solvable some have multiple solutions values s digits for s in squares for s in shuffledsquares if not assignvalues s random choicevaluess break ds valuess for s in squares if lenvaluess 1 if lends assignments and lensetds 8 return joinvaluess if lenvaluess 1 else for s in squares return randompuzzleassignments give up and make a new puzzle def shuffledseq return a randomly shuffled copy of the input sequence seq listseq random shuffleseq return seq grid1 003020600900305001001806400008102900700000008006708200002609500800203009005010300 grid2 4 8 5 3 7 2 6 8 4 1 6 3 7 5 2 1 4 hard1 6 59 82 8 45 3 6 3 54 325 6 if name main test solveallfromfileeasy50 txt easy none solveallfromfiletop95 txt hard none solveallfromfilehardest txt hardest none solveallrandompuzzle for in range99 random 100 0 for puzzle in grid1 grid2 hard1 takes 22 sec to solve on my m1 mac displayparsegridpuzzle start time monotonic solvepuzzle t time monotonic start printsolved 5f sec t fmt off fmt on convert grid to a dict of possible values square digits or return false if a contradiction is detected to start every square can be any digit then assign values from the grid fail if we can t assign d to square s eliminate all the other values except d from values s and propagate return values except return false if a contradiction is detected eliminate d from values s propagate when values or places 2 return values except return false if a contradiction is detected already eliminated 1 if a square s is reduced to one value d2 then eliminate d2 from the peers contradiction removed last value 2 if a unit u is reduced to only one place for a value d then put it there contradiction no place for this value d can only be in one place in unit assign it there failed earlier solved chose the unfilled square s with the fewest possibilities attempt to solve a sequence of grids report results when showif is a number of seconds display puzzles that take longer when showif is none don t display any puzzles display puzzles that take long enough noqa sim115 make a random puzzle with n or more assignments restart on contradictions note the resulting puzzle is not guaranteed to be solvable but empirically about 99 8 of them are solvable some have multiple solutions give up and make a new puzzle solve_all from_file easy50 txt easy none solve_all from_file top95 txt hard none solve_all from_file hardest txt hardest none hard1 takes 22 sec to solve on my m1 mac
import random import time def cross(items_a, items_b): "Cross product of elements in A and elements in B." return [a + b for a in items_a for b in items_b] digits = "123456789" rows = "ABCDEFGHI" cols = digits squares = cross(rows, cols) unitlist = ( [cross(rows, c) for c in cols] + [cross(r, cols) for r in rows] + [cross(rs, cs) for rs in ("ABC", "DEF", "GHI") for cs in ("123", "456", "789")] ) units = {s: [u for u in unitlist if s in u] for s in squares} peers = {s: set(sum(units[s], [])) - {s} for s in squares} def test(): "A set of unit tests." assert len(squares) == 81 assert len(unitlist) == 27 assert all(len(units[s]) == 3 for s in squares) assert all(len(peers[s]) == 20 for s in squares) assert units["C2"] == [ ["A2", "B2", "C2", "D2", "E2", "F2", "G2", "H2", "I2"], ["C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"], ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"], ] assert peers["C2"] == { "A2", "B2", "D2", "E2", "F2", "G2", "H2", "I2", "C1", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "A1", "A3", "B1", "B3" } print("All tests pass.") def parse_grid(grid): values = {s: digits for s in squares} for s, d in grid_values(grid).items(): if d in digits and not assign(values, s, d): return False return values def grid_values(grid): "Convert grid into a dict of {square: char} with '0' or '.' for empties." chars = [c for c in grid if c in digits or c in "0."] assert len(chars) == 81 return dict(zip(squares, chars)) def assign(values, s, d): other_values = values[s].replace(d, "") if all(eliminate(values, s, d2) for d2 in other_values): return values else: return False def eliminate(values, s, d): if d not in values[s]: return values values[s] = values[s].replace(d, "") if len(values[s]) == 0: return False elif len(values[s]) == 1: d2 = values[s] if not all(eliminate(values, s2, d2) for s2 in peers[s]): return False for u in units[s]: dplaces = [s for s in u if d in values[s]] if len(dplaces) == 0: return False elif len(dplaces) == 1: if not assign(values, dplaces[0], d): return False return values def display(values): "Display these values as a 2-D grid." width = 1 + max(len(values[s]) for s in squares) line = "+".join(["-" * (width * 3)] * 3) for r in rows: print( "".join( values[r + c].center(width) + ("|" if c in "36" else "") for c in cols ) ) if r in "CF": print(line) print() def solve(grid): return search(parse_grid(grid)) def some(seq): "Return some element of seq that is true." for e in seq: if e: return e return False def search(values): "Using depth-first search and propagation, try all possible values." if values is False: return False if all(len(values[s]) == 1 for s in squares): return values n, s = min((len(values[s]), s) for s in squares if len(values[s]) > 1) return some(search(assign(values.copy(), s, d)) for d in values[s]) def solve_all(grids, name="", showif=0.0): def time_solve(grid): start = time.monotonic() values = solve(grid) t = time.monotonic() - start if showif is not None and t > showif: display(grid_values(grid)) if values: display(values) print("(%.5f seconds)\n" % t) return (t, solved(values)) times, results = zip(*[time_solve(grid) for grid in grids]) if (n := len(grids)) > 1: print( "Solved %d of %d %s puzzles (avg %.2f secs (%d Hz), max %.2f secs)." % (sum(results), n, name, sum(times) / n, n / sum(times), max(times)) ) def solved(values): "A puzzle is solved if each unit is a permutation of the digits 1 to 9." def unitsolved(unit): return {values[s] for s in unit} == set(digits) return values is not False and all(unitsolved(unit) for unit in unitlist) def from_file(filename, sep="\n"): "Parse a file into a list of strings, separated by sep." return open(filename).read().strip().split(sep) def random_puzzle(assignments=17): values = {s: digits for s in squares} for s in shuffled(squares): if not assign(values, s, random.choice(values[s])): break ds = [values[s] for s in squares if len(values[s]) == 1] if len(ds) >= assignments and len(set(ds)) >= 8: return "".join(values[s] if len(values[s]) == 1 else "." for s in squares) return random_puzzle(assignments) def shuffled(seq): "Return a randomly shuffled copy of the input sequence." seq = list(seq) random.shuffle(seq) return seq grid1 = ( "003020600900305001001806400008102900700000008006708200002609500800203009005010300" ) grid2 = ( "4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......" ) hard1 = ( ".....6....59.....82....8....45........3........6..3.54...325..6.................." ) if __name__ == "__main__": test() solve_all([random_puzzle() for _ in range(99)], "random", 100.0) for puzzle in (grid1, grid2): display(parse_grid(puzzle)) start = time.monotonic() solve(puzzle) t = time.monotonic() - start print("Solved: %.5f sec" % t)
implementation of an autobalanced binary tree for doctests run following command python3 m doctest v avltree py for testing run python avltree py printleft rotation node node getdata ret node getleft assert ret is not none node setleftret getright ret setrightnode h1 mymaxgetheightnode getright getheightnode getleft 1 node setheighth1 h2 mymaxgetheightret getright getheightret getleft 1 ret setheighth2 return ret def leftrotationnode mynode mynode printright rotation node node getdata ret node getright assert ret is not none node setrightret getleft ret setleftnode h1 mymaxgetheightnode getright getheightnode getleft 1 node setheighth1 h2 mymaxgetheightret getright getheightret getleft 1 ret setheighth2 return ret def lrrotationnode mynode mynode r a a br b c lr br c rr b a bl br b ub bl ub c ub bl rr rightrotation lr leftrotation an avl tree doctest examples t avltree t insert4 insert 4 printstrt replace n n 4 t insert2 insert 2 printstrt replace n n replace n n 4 2 t insert3 insert 3 right rotation node 2 left rotation node 4 printstrt replace n n replace n n 3 2 4 t getheight 2 t delnode3 delete 3 printstrt replace n n replace n n 4 2 a b b c bl a bl br ub br c ub ub unbalanced node a mirror symmetry rotation of the left_rotation a a br b c lr br c rr b a bl br b ub bl ub c ub bl rr right_rotation lr left_rotation an unbalance detected new node is the left child of the left child root get_data data an avl tree doctest examples t avltree t insert 4 insert 4 print str t replace n n 4 t insert 2 insert 2 print str t replace n n replace n n 4 2 t insert 3 insert 3 right rotation node 2 left rotation node 4 print str t replace n n replace n n 3 2 4 t get_height 2 t del_node 3 delete 3 print str t replace n n replace n n 4 2 a level traversale gives a more intuitive look on the tree
from __future__ import annotations import math import random from typing import Any class MyQueue: def __init__(self) -> None: self.data: list[Any] = [] self.head: int = 0 self.tail: int = 0 def is_empty(self) -> bool: return self.head == self.tail def push(self, data: Any) -> None: self.data.append(data) self.tail = self.tail + 1 def pop(self) -> Any: ret = self.data[self.head] self.head = self.head + 1 return ret def count(self) -> int: return self.tail - self.head def print_queue(self) -> None: print(self.data) print("**************") print(self.data[self.head : self.tail]) class MyNode: def __init__(self, data: Any) -> None: self.data = data self.left: MyNode | None = None self.right: MyNode | None = None self.height: int = 1 def get_data(self) -> Any: return self.data def get_left(self) -> MyNode | None: return self.left def get_right(self) -> MyNode | None: return self.right def get_height(self) -> int: return self.height def set_data(self, data: Any) -> None: self.data = data def set_left(self, node: MyNode | None) -> None: self.left = node def set_right(self, node: MyNode | None) -> None: self.right = node def set_height(self, height: int) -> None: self.height = height def get_height(node: MyNode | None) -> int: if node is None: return 0 return node.get_height() def my_max(a: int, b: int) -> int: if a > b: return a return b def right_rotation(node: MyNode) -> MyNode: r print("left rotation node:", node.get_data()) ret = node.get_left() assert ret is not None node.set_left(ret.get_right()) ret.set_right(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret def left_rotation(node: MyNode) -> MyNode: print("right rotation node:", node.get_data()) ret = node.get_right() assert ret is not None node.set_right(ret.get_left()) ret.set_left(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1 ret.set_height(h2) return ret def lr_rotation(node: MyNode) -> MyNode: r left_child = node.get_left() assert left_child is not None node.set_left(left_rotation(left_child)) return right_rotation(node) def rl_rotation(node: MyNode) -> MyNode: right_child = node.get_right() assert right_child is not None node.set_right(right_rotation(right_child)) return left_rotation(node) def insert_node(node: MyNode | None, data: Any) -> MyNode | None: if node is None: return MyNode(data) if data < node.get_data(): node.set_left(insert_node(node.get_left(), data)) if ( get_height(node.get_left()) - get_height(node.get_right()) == 2 ): left_child = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): node = right_rotation(node) else: node = lr_rotation(node) else: node.set_right(insert_node(node.get_right(), data)) if get_height(node.get_right()) - get_height(node.get_left()) == 2: right_child = node.get_right() assert right_child is not None if data < right_child.get_data(): node = rl_rotation(node) else: node = left_rotation(node) h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1 node.set_height(h1) return node def get_right_most(root: MyNode) -> Any: while True: right_child = root.get_right() if right_child is None: break root = right_child return root.get_data() def get_left_most(root: MyNode) -> Any: while True: left_child = root.get_left() if left_child is None: break root = left_child return root.get_data() def del_node(root: MyNode, data: Any) -> MyNode | None: left_child = root.get_left() right_child = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: temp_data = get_left_most(right_child) root.set_data(temp_data) root.set_right(del_node(right_child, temp_data)) elif left_child is not None: root = left_child elif right_child is not None: root = right_child else: return None elif root.get_data() > data: if left_child is None: print("No such data") return root else: root.set_left(del_node(left_child, data)) else: if right_child is None: return root else: root.set_right(del_node(right_child, data)) if get_height(right_child) - get_height(left_child) == 2: assert right_child is not None if get_height(right_child.get_right()) > get_height(right_child.get_left()): root = left_rotation(root) else: root = rl_rotation(root) elif get_height(right_child) - get_height(left_child) == -2: assert left_child is not None if get_height(left_child.get_left()) > get_height(left_child.get_right()): root = right_rotation(root) else: root = lr_rotation(root) height = my_max(get_height(root.get_right()), get_height(root.get_left())) + 1 root.set_height(height) return root class AVLtree: def __init__(self) -> None: self.root: MyNode | None = None def get_height(self) -> int: return get_height(self.root) def insert(self, data: Any) -> None: print("insert:" + str(data)) self.root = insert_node(self.root, data) def del_node(self, data: Any) -> None: print("delete:" + str(data)) if self.root is None: print("Tree is empty!") return self.root = del_node(self.root, data) def __str__( self, ) -> str: output = "" q = MyQueue() q.push(self.root) layer = self.get_height() if layer == 0: return output cnt = 0 while not q.is_empty(): node = q.pop() space = " " * int(math.pow(2, layer - 1)) output += space if node is None: output += "*" q.push(None) q.push(None) else: output += str(node.get_data()) q.push(node.get_left()) q.push(node.get_right()) output += space cnt = cnt + 1 for i in range(100): if cnt == math.pow(2, i) - 1: layer = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def _test() -> None: import doctest doctest.testmod() if __name__ == "__main__": _test() t = AVLtree() lst = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
return a small binary tree with 3 nodes binarytree binarytree smalltree lenbinarytree 3 listbinarytree 1 2 3 return a medium binary tree with 3 nodes binarytree binarytree mediumtree lenbinarytree 7 listbinarytree 1 2 3 4 5 6 7 returns the depth of the tree binarytreenode1 depth 1 binarytree smalltree depth 2 binarytree mediumtree depth 4 returns true if the tree is full binarytreenode1 isfull true binarytree smalltree isfull true binarytree mediumtree isfull false return a small binary tree with 3 nodes binary_tree binarytree small_tree len binary_tree 3 list binary_tree 1 2 3 return a medium binary tree with 3 nodes binary_tree binarytree medium_tree len binary_tree 7 list binary_tree 1 2 3 4 5 6 7 returns the depth of the tree binarytree node 1 depth 1 binarytree small_tree depth 2 binarytree medium_tree depth 4 noqa up007 returns true if the tree is full binarytree node 1 is_full true binarytree small_tree is_full true binarytree medium_tree is_full false
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass @dataclass class Node: data: int left: Node | None = None right: Node | None = None def __iter__(self) -> Iterator[int]: if self.left: yield from self.left yield self.data if self.right: yield from self.right def __len__(self) -> int: return sum(1 for _ in self) def is_full(self) -> bool: if not self or (not self.left and not self.right): return True if self.left and self.right: return self.left.is_full() and self.right.is_full() return False @dataclass class BinaryTree: root: Node def __iter__(self) -> Iterator[int]: return iter(self.root) def __len__(self) -> int: return len(self.root) @classmethod def small_tree(cls) -> BinaryTree: binary_tree = BinaryTree(Node(2)) binary_tree.root.left = Node(1) binary_tree.root.right = Node(3) return binary_tree @classmethod def medium_tree(cls) -> BinaryTree: binary_tree = BinaryTree(Node(4)) binary_tree.root.left = two = Node(2) two.left = Node(1) two.right = Node(3) binary_tree.root.right = five = Node(5) five.right = six = Node(6) six.right = Node(7) return binary_tree def depth(self) -> int: return self._depth(self.root) def _depth(self, node: Node | None) -> int: if not node: return 0 return 1 + max(self._depth(node.left), self._depth(node.right)) def is_full(self) -> bool: return self.root.is_full() if __name__ == "__main__": import doctest doctest.testmod()
this is a python3 implementation of binary search tree using recursion to run tests python m unittest binarysearchtreerecursive py to run an example python binarysearchtreerecursive py empties the tree t binarysearchtree assert t root is none t put8 assert t root is not none checks if the tree is empty t binarysearchtree t isempty true t put8 t isempty false put a new node in the tree t binarysearchtree t put8 assert t root parent is none assert t root label 8 t put10 assert t root right parent t root assert t root right label 10 t put3 assert t root left parent t root assert t root left label 3 searches a node in the tree t binarysearchtree t put8 t put10 node t search8 assert node label 8 node t search3 traceback most recent call last valueerror node with label 3 does not exist removes a node in the tree t binarysearchtree t put8 t put10 t remove8 assert t root label 10 t remove3 traceback most recent call last valueerror node with label 3 does not exist checks if a node exists in the tree t binarysearchtree t put8 t put10 t exists8 true t exists3 false gets the max label inserted in the tree t binarysearchtree t getmaxlabel traceback most recent call last valueerror binary search tree is empty t put8 t put10 t getmaxlabel 10 gets the min label inserted in the tree t binarysearchtree t getminlabel traceback most recent call last valueerror binary search tree is empty t put8 t put10 t getminlabel 8 return the inorder traversal of the tree t binarysearchtree i label for i in t inordertraversal t put8 t put10 t put9 i label for i in t inordertraversal 8 9 10 return the preorder traversal of the tree t binarysearchtree i label for i in t preordertraversal t put8 t put10 t put9 i label for i in t preordertraversal 8 10 9 t binarysearchtree t put8 t put3 t put6 t put1 t put10 t put14 t put13 t put4 t put7 t put5 return t def testputself none t binarysearchtree assert t isempty t put8 r 8 assert t root right is not none assert t root right parent t root assert t root right label 10 t put3 r 8 3 10 assert t root left right is not none assert t root left right parent t root left assert t root left right label 6 t put1 r 8 3 10 1 6 assert t root is not none assert t root right is not none assert t root right right is not none assert t root right right right is none assert t root right right left is none t remove7 r 8 3 10 1 6 14 4 5 assert t root left left is not none assert t root left right right is not none assert t root left left label 1 assert t root left right label 4 assert t root left right right label 5 assert t root left right left is none assert t root left left parent t root left assert t root left right parent t root left t remove3 r 8 4 10 1 5 14 assert t root left is not none assert t root left left is not none assert t root left label 5 assert t root left right is none assert t root left left label 1 assert t root left parent t root assert t root left left parent t root left def testremove2self none t self getbinarysearchtree t remove3 r 8 4 10 1 6 14 5 7 13 t binarysearchtree t put8 t put3 t put6 t put1 t put10 t put14 t put13 t put4 t put7 t put5 print printlabel 6 exists t exists6 printlabel 13 exists t exists13 printlabel 1 exists t exists1 printlabel 12 exists t exists12 prints all the elements of the list in inorder traversal inordertraversalnodes i label for i in t inordertraversal printinorder traversal inordertraversalnodes prints all the elements of the list in preorder traversal preordertraversalnodes i label for i in t preordertraversal printpreorder traversal preordertraversalnodes printmax label t getmaxlabel printmin label t getminlabel delete elements printndeleting elements 13 10 8 3 6 14 print t remove13 t remove10 t remove8 t remove3 t remove6 t remove14 prints all the elements of the list in inorder traversal after delete inordertraversalnodes i label for i in t inordertraversal printinorder traversal after delete inordertraversalnodes prints all the elements of the list in preorder traversal after delete preordertraversalnodes i label for i in t preordertraversal printpreorder traversal after delete preordertraversalnodes printmax label t getmaxlabel printmin label t getminlabel if name main binarysearchtreeexample empties the tree t binarysearchtree assert t root is none t put 8 assert t root is not none checks if the tree is empty t binarysearchtree t is_empty true t put 8 t is_empty false put a new node in the tree t binarysearchtree t put 8 assert t root parent is none assert t root label 8 t put 10 assert t root right parent t root assert t root right label 10 t put 3 assert t root left parent t root assert t root left label 3 searches a node in the tree t binarysearchtree t put 8 t put 10 node t search 8 assert node label 8 node t search 3 traceback most recent call last valueerror node with label 3 does not exist removes a node in the tree t binarysearchtree t put 8 t put 10 t remove 8 assert t root label 10 t remove 3 traceback most recent call last valueerror node with label 3 does not exist checks if a node exists in the tree t binarysearchtree t put 8 t put 10 t exists 8 true t exists 3 false gets the max label inserted in the tree t binarysearchtree t get_max_label traceback most recent call last valueerror binary search tree is empty t put 8 t put 10 t get_max_label 10 gets the min label inserted in the tree t binarysearchtree t get_min_label traceback most recent call last valueerror binary search tree is empty t put 8 t put 10 t get_min_label 8 return the inorder traversal of the tree t binarysearchtree i label for i in t inorder_traversal t put 8 t put 10 t put 9 i label for i in t inorder_traversal 8 9 10 return the preorder traversal of the tree t binarysearchtree i label for i in t preorder_traversal t put 8 t put 10 t put 9 i label for i in t preorder_traversal 8 10 9 8 3 10 1 6 14 4 7 13 5 8 8 10 8 3 10 8 3 10 6 8 3 10 1 6 8 3 10 1 6 14 4 7 5 8 3 10 1 6 14 4 5 8 3 10 1 4 14 5 8 4 10 1 5 14 8 5 10 1 14 8 4 10 1 6 14 5 7 13 example 8 3 10 1 6 14 4 7 13 5 example after deletion 4 1 7 5 8 3 10 1 6 14 4 7 13 5 prints all the elements of the list in inorder traversal prints all the elements of the list in preorder traversal delete elements 4 1 7 5 prints all the elements of the list in inorder traversal after delete prints all the elements of the list in preorder traversal after delete
from __future__ import annotations import unittest from collections.abc import Iterator import pytest class Node: def __init__(self, label: int, parent: Node | None) -> None: self.label = label self.parent = parent self.left: Node | None = None self.right: Node | None = None class BinarySearchTree: def __init__(self) -> None: self.root: Node | None = None def empty(self) -> None: self.root = None def is_empty(self) -> bool: return self.root is None def put(self, label: int) -> None: self.root = self._put(self.root, label) def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Node: if node is None: node = Node(label, parent) else: if label < node.label: node.left = self._put(node.left, label, node) elif label > node.label: node.right = self._put(node.right, label, node) else: msg = f"Node with label {label} already exists" raise ValueError(msg) return node def search(self, label: int) -> Node: return self._search(self.root, label) def _search(self, node: Node | None, label: int) -> Node: if node is None: msg = f"Node with label {label} does not exist" raise ValueError(msg) else: if label < node.label: node = self._search(node.left, label) elif label > node.label: node = self._search(node.right, label) return node def remove(self, label: int) -> None: node = self.search(label) if node.right and node.left: lowest_node = self._get_lowest_node(node.right) lowest_node.left = node.left lowest_node.right = node.right node.left.parent = lowest_node if node.right: node.right.parent = lowest_node self._reassign_nodes(node, lowest_node) elif not node.right and node.left: self._reassign_nodes(node, node.left) elif node.right and not node.left: self._reassign_nodes(node, node.right) else: self._reassign_nodes(node, None) def _reassign_nodes(self, node: Node, new_children: Node | None) -> None: if new_children: new_children.parent = node.parent if node.parent: if node.parent.right == node: node.parent.right = new_children else: node.parent.left = new_children else: self.root = new_children def _get_lowest_node(self, node: Node) -> Node: if node.left: lowest_node = self._get_lowest_node(node.left) else: lowest_node = node self._reassign_nodes(node, node.right) return lowest_node def exists(self, label: int) -> bool: try: self.search(label) return True except ValueError: return False def get_max_label(self) -> int: if self.root is None: raise ValueError("Binary search tree is empty") node = self.root while node.right is not None: node = node.right return node.label def get_min_label(self) -> int: if self.root is None: raise ValueError("Binary search tree is empty") node = self.root while node.left is not None: node = node.left return node.label def inorder_traversal(self) -> Iterator[Node]: return self._inorder_traversal(self.root) def _inorder_traversal(self, node: Node | None) -> Iterator[Node]: if node is not None: yield from self._inorder_traversal(node.left) yield node yield from self._inorder_traversal(node.right) def preorder_traversal(self) -> Iterator[Node]: return self._preorder_traversal(self.root) def _preorder_traversal(self, node: Node | None) -> Iterator[Node]: if node is not None: yield node yield from self._preorder_traversal(node.left) yield from self._preorder_traversal(node.right) class BinarySearchTreeTest(unittest.TestCase): @staticmethod def _get_binary_search_tree() -> BinarySearchTree: r t = BinarySearchTree() t.put(8) t.put(3) t.put(6) t.put(1) t.put(10) t.put(14) t.put(13) t.put(4) t.put(7) t.put(5) return t def test_put(self) -> None: t = BinarySearchTree() assert t.is_empty() t.put(8) r assert t.root is not None assert t.root.parent is None assert t.root.label == 8 t.put(10) r assert t.root.right is not None assert t.root.right.parent == t.root assert t.root.right.label == 10 t.put(3) r assert t.root.left is not None assert t.root.left.parent == t.root assert t.root.left.label == 3 t.put(6) r assert t.root.left.right is not None assert t.root.left.right.parent == t.root.left assert t.root.left.right.label == 6 t.put(1) r assert t.root.left.left is not None assert t.root.left.left.parent == t.root.left assert t.root.left.left.label == 1 with pytest.raises(ValueError): t.put(1) def test_search(self) -> None: t = self._get_binary_search_tree() node = t.search(6) assert node.label == 6 node = t.search(13) assert node.label == 13 with pytest.raises(ValueError): t.search(2) def test_remove(self) -> None: t = self._get_binary_search_tree() t.remove(13) r assert t.root is not None assert t.root.right is not None assert t.root.right.right is not None assert t.root.right.right.right is None assert t.root.right.right.left is None t.remove(7) r assert t.root.left is not None assert t.root.left.right is not None assert t.root.left.right.left is not None assert t.root.left.right.right is None assert t.root.left.right.left.label == 4 t.remove(6) r assert t.root.left.left is not None assert t.root.left.right.right is not None assert t.root.left.left.label == 1 assert t.root.left.right.label == 4 assert t.root.left.right.right.label == 5 assert t.root.left.right.left is None assert t.root.left.left.parent == t.root.left assert t.root.left.right.parent == t.root.left t.remove(3) r assert t.root is not None assert t.root.left.label == 4 assert t.root.left.right.label == 5 assert t.root.left.left.label == 1 assert t.root.left.parent == t.root assert t.root.left.left.parent == t.root.left assert t.root.left.right.parent == t.root.left t.remove(4) r assert t.root.left is not None assert t.root.left.left is not None assert t.root.left.label == 5 assert t.root.left.right is None assert t.root.left.left.label == 1 assert t.root.left.parent == t.root assert t.root.left.left.parent == t.root.left def test_remove_2(self) -> None: t = self._get_binary_search_tree() t.remove(3) r assert t.root is not None assert t.root.left is not None assert t.root.left.left is not None assert t.root.left.right is not None assert t.root.left.right.left is not None assert t.root.left.right.right is not None assert t.root.left.label == 4 assert t.root.left.right.label == 6 assert t.root.left.left.label == 1 assert t.root.left.right.right.label == 7 assert t.root.left.right.left.label == 5 assert t.root.left.parent == t.root assert t.root.left.right.parent == t.root.left assert t.root.left.left.parent == t.root.left assert t.root.left.right.left.parent == t.root.left.right def test_empty(self) -> None: t = self._get_binary_search_tree() t.empty() assert t.root is None def test_is_empty(self) -> None: t = self._get_binary_search_tree() assert not t.is_empty() t.empty() assert t.is_empty() def test_exists(self) -> None: t = self._get_binary_search_tree() assert t.exists(6) assert not t.exists(-1) def test_get_max_label(self) -> None: t = self._get_binary_search_tree() assert t.get_max_label() == 14 t.empty() with pytest.raises(ValueError): t.get_max_label() def test_get_min_label(self) -> None: t = self._get_binary_search_tree() assert t.get_min_label() == 1 t.empty() with pytest.raises(ValueError): t.get_min_label() def test_inorder_traversal(self) -> None: t = self._get_binary_search_tree() inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] assert inorder_traversal_nodes == [1, 3, 4, 5, 6, 7, 8, 10, 13, 14] def test_preorder_traversal(self) -> None: t = self._get_binary_search_tree() preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] assert preorder_traversal_nodes == [8, 3, 1, 6, 4, 5, 7, 10, 14, 13] def binary_search_tree_example() -> None: r t = BinarySearchTree() t.put(8) t.put(3) t.put(6) t.put(1) t.put(10) t.put(14) t.put(13) t.put(4) t.put(7) t.put(5) print( ) print("Label 6 exists:", t.exists(6)) print("Label 13 exists:", t.exists(13)) print("Label -1 exists:", t.exists(-1)) print("Label 12 exists:", t.exists(12)) inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] print("Inorder traversal:", inorder_traversal_nodes) preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] print("Preorder traversal:", preorder_traversal_nodes) print("Max. label:", t.get_max_label()) print("Min. label:", t.get_min_label()) print("\nDeleting elements 13, 10, 8, 3, 6, 14") print( ) t.remove(13) t.remove(10) t.remove(8) t.remove(3) t.remove(6) t.remove(14) inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] print("Inorder traversal after delete:", inorder_traversal_nodes) preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] print("Preorder traversal after delete:", preorder_traversal_nodes) print("Max. label:", t.get_max_label()) print("Min. label:", t.get_min_label()) if __name__ == "__main__": binary_search_tree_example()
problem description given a binary tree return its mirror binarytreemirror 1 2 3 2 4 5 3 6 7 7 8 9 1 1 3 2 2 5 4 3 7 6 7 9 8 binarytreemirror 1 2 3 2 4 5 3 6 7 4 10 11 1 1 3 2 2 5 4 3 7 6 4 11 10 binarytreemirror 1 2 3 2 4 5 3 6 7 4 10 11 5 traceback most recent call last valueerror root 5 is not present in the binarytree binarytreemirror 5 traceback most recent call last valueerror binary tree cannot be empty binary_tree_mirror 1 2 3 2 4 5 3 6 7 7 8 9 1 1 3 2 2 5 4 3 7 6 7 9 8 binary_tree_mirror 1 2 3 2 4 5 3 6 7 4 10 11 1 1 3 2 2 5 4 3 7 6 4 11 10 binary_tree_mirror 1 2 3 2 4 5 3 6 7 4 10 11 5 traceback most recent call last valueerror root 5 is not present in the binary_tree binary_tree_mirror 5 traceback most recent call last valueerror binary tree cannot be empty
def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int): if not root or root not in binary_tree_mirror_dictionary: return left_child, right_child = binary_tree_mirror_dictionary[root][:2] binary_tree_mirror_dictionary[root] = [right_child, left_child] binary_tree_mirror_dict(binary_tree_mirror_dictionary, left_child) binary_tree_mirror_dict(binary_tree_mirror_dictionary, right_child) def binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict: if not binary_tree: raise ValueError("binary tree cannot be empty") if root not in binary_tree: msg = f"root {root} is not present in the binary_tree" raise ValueError(msg) binary_tree_mirror_dictionary = dict(binary_tree) binary_tree_mirror_dict(binary_tree_mirror_dictionary, root) return binary_tree_mirror_dictionary if __name__ == "__main__": binary_tree = {1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]} print(f"Binary tree: {binary_tree}") binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 5) print(f"Binary tree mirror: {binary_tree_mirror_dictionary}")
sum of all nodes in a binary tree python implementation on time complexity recurses through meth depthfirstsearch with each element on space complexity at any point in time maximum number of stack frames that could be in memory is n a node has a value variable and pointers to nodes to its left and right def initself tree node none self tree tree def depthfirstsearchself node node none int if node is none return 0 return node value self depthfirstsearchnode left self depthfirstsearchnode right def iterself iteratorint yield self depthfirstsearchself tree if name main import doctest doctest testmod a node has a value variable and pointers to nodes to its left and right the below tree looks like this 10 5 3 12 8 0 tree node 10 sum binarytreenodesum tree 10 tree left node 5 sum binarytreenodesum tree 15 tree right node 3 sum binarytreenodesum tree 12 tree left left node 12 sum binarytreenodesum tree 24 tree right left node 8 tree right right node 0 sum binarytreenodesum tree 32
from __future__ import annotations from collections.abc import Iterator class Node: def __init__(self, value: int) -> None: self.value = value self.left: Node | None = None self.right: Node | None = None class BinaryTreeNodeSum: r def __init__(self, tree: Node) -> None: self.tree = tree def depth_first_search(self, node: Node | None) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left) + self.depth_first_search(node.right) ) def __iter__(self) -> Iterator[int]: yield self.depth_first_search(self.tree) if __name__ == "__main__": import doctest doctest.testmod()
given the root of a binary tree and an integer target find the number of paths where the sum of the values along the path equals target leetcode reference https leetcode comproblemspathsumiii a node has value variable and pointers to nodes to its left and right target int def initself none self paths 0 def depthfirstsearchself node node none pathsum int none if node is none return if pathsum self target self paths 1 if node left self depthfirstsearchnode left pathsum node left value if node right self depthfirstsearchnode right pathsum node right value def pathsumself node node none target int none none int if node is none return 0 if target is not none self target target self depthfirstsearchnode node value self pathsumnode left self pathsumnode right return self paths if name main import doctest doctest testmod a node has value variable and pointers to nodes to its left and right the below tree looks like this 10 5 3 3 2 11 3 2 1 tree node 10 tree left node 5 tree right node 3 tree left left node 3 tree left right node 2 tree right right node 11 tree left left left node 3 tree left left right node 2 tree left right right node 1 binarytreepathsum path_sum tree 8 3 binarytreepathsum path_sum tree 7 2 tree right right node 10 binarytreepathsum path_sum tree 8 2
from __future__ import annotations class Node: def __init__(self, value: int) -> None: self.value = value self.left: Node | None = None self.right: Node | None = None class BinaryTreePathSum: r target: int def __init__(self) -> None: self.paths = 0 def depth_first_search(self, node: Node | None, path_sum: int) -> None: if node is None: return if path_sum == self.target: self.paths += 1 if node.left: self.depth_first_search(node.left, path_sum + node.left.value) if node.right: self.depth_first_search(node.right, path_sum + node.right.value) def path_sum(self, node: Node | None, target: int | None = None) -> int: if node is None: return 0 if target is not None: self.target = target self.depth_first_search(node, node.value) self.path_sum(node.left) self.path_sum(node.right) return self.paths if __name__ == "__main__": import doctest doctest.testmod()
https en wikipedia orgwikitreetraversal tree node1 tree left node2 tree right node3 tree left left node4 tree left right node5 return tree def preorderroot node none generatorint none none if not root return yield root data yield from preorderroot left yield from preorderroot right def postorderroot node none generatorint none none if not root return yield from postorderroot left yield from postorderroot right yield root data def inorderroot node none generatorint none none if not root return yield from inorderroot left yield root data yield from inorderroot right def reverseinorderroot node none generatorint none none if not root return yield from reverseinorderroot right yield root data yield from reverseinorderroot left def heightroot node none int return maxheightroot left heightroot right 1 if root else 0 def levelorderroot node none generatorint none none if root is none return processqueue dequeroot while processqueue node processqueue popleft yield node data if node left processqueue appendnode left if node right processqueue appendnode right def getnodesfromlefttoright root node none level int generatorint none none def populateoutputroot node none level int generatorint none none if not root return if level 1 yield root data elif level 1 yield from populateoutputroot left level 1 yield from populateoutputroot right level 1 yield from populateoutputroot level def getnodesfromrighttoleft root node none level int generatorint none none def populateoutputroot node none level int generatorint none none if root is none return if level 1 yield root data elif level 1 yield from populateoutputroot right level 1 yield from populateoutputroot left level 1 yield from populateoutputroot level def zigzagroot node none generatorint none none if root is none return flag 0 heighttree heightroot for h in range1 heighttree 1 if not flag yield from getnodesfromlefttorightroot h flag 1 else yield from getnodesfromrighttoleftroot h flag 0 def main none main function for testing create binary tree root maketree all traversals of the binary are as follows printfinorder traversal listinorderroot printfreverse inorder traversal listreverseinorderroot printfpreorder traversal listpreorderroot printfpostorder traversal listpostorderroot n printfheight of tree heightroot n printcomplete level order traversal printflistlevelorderroot n printlevelwise order traversal for level in range1 heightroot 1 printflevel level listgetnodesfromlefttorightroot levellevel printnzigzag order traversal printflistzigzagroot if name main import doctest doctest testmod main https en wikipedia org wiki tree_traversal the below tree 1 2 3 4 5 pre order traversal visits root node left subtree right subtree list preorder make_tree 1 2 4 5 3 post order traversal visits left subtree right subtree root node list postorder make_tree 4 5 2 3 1 in order traversal visits left subtree root node right subtree list inorder make_tree 4 2 5 1 3 reverse in order traversal visits right subtree root node left subtree list reverse_inorder make_tree 3 1 5 2 4 recursive function for calculating the height of the binary tree height none 0 height make_tree 3 returns a list of nodes value from a whole binary tree in level order traverse level order traverse visit nodes of the tree level by level returns a list of nodes value from a particular level left to right direction of the binary tree returns a list of nodes value from a particular level right to left direction of the binary tree zigzag traverse returns a list of nodes value from left to right and right to left alternatively main function for testing create binary tree all traversals of the binary are as follows
from __future__ import annotations from collections import deque from collections.abc import Generator from dataclasses import dataclass @dataclass class Node: data: int left: Node | None = None right: Node | None = None def make_tree() -> Node | None: r tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) return tree def preorder(root: Node | None) -> Generator[int, None, None]: if not root: return yield root.data yield from preorder(root.left) yield from preorder(root.right) def postorder(root: Node | None) -> Generator[int, None, None]: if not root: return yield from postorder(root.left) yield from postorder(root.right) yield root.data def inorder(root: Node | None) -> Generator[int, None, None]: if not root: return yield from inorder(root.left) yield root.data yield from inorder(root.right) def reverse_inorder(root: Node | None) -> Generator[int, None, None]: if not root: return yield from reverse_inorder(root.right) yield root.data yield from reverse_inorder(root.left) def height(root: Node | None) -> int: return (max(height(root.left), height(root.right)) + 1) if root else 0 def level_order(root: Node | None) -> Generator[int, None, None]: if root is None: return process_queue = deque([root]) while process_queue: node = process_queue.popleft() yield node.data if node.left: process_queue.append(node.left) if node.right: process_queue.append(node.right) def get_nodes_from_left_to_right( root: Node | None, level: int ) -> Generator[int, None, None]: def populate_output(root: Node | None, level: int) -> Generator[int, None, None]: if not root: return if level == 1: yield root.data elif level > 1: yield from populate_output(root.left, level - 1) yield from populate_output(root.right, level - 1) yield from populate_output(root, level) def get_nodes_from_right_to_left( root: Node | None, level: int ) -> Generator[int, None, None]: def populate_output(root: Node | None, level: int) -> Generator[int, None, None]: if root is None: return if level == 1: yield root.data elif level > 1: yield from populate_output(root.right, level - 1) yield from populate_output(root.left, level - 1) yield from populate_output(root, level) def zigzag(root: Node | None) -> Generator[int, None, None]: if root is None: return flag = 0 height_tree = height(root) for h in range(1, height_tree + 1): if not flag: yield from get_nodes_from_left_to_right(root, h) flag = 1 else: yield from get_nodes_from_right_to_left(root, h) flag = 0 def main() -> None: root = make_tree() print(f"In-order Traversal: {list(inorder(root))}") print(f"Reverse In-order Traversal: {list(reverse_inorder(root))}") print(f"Pre-order Traversal: {list(preorder(root))}") print(f"Post-order Traversal: {list(postorder(root))}", "\n") print(f"Height of Tree: {height(root)}", "\n") print("Complete Level Order Traversal: ") print(f"{list(level_order(root))} \n") print("Level-wise order Traversal: ") for level in range(1, height(root) + 1): print(f"Level {level}:", list(get_nodes_from_left_to_right(root, level=level))) print("\nZigZag order Traversal: ") print(f"{list(zigzag(root))}") if __name__ == "__main__": import doctest doctest.testmod() main()
the diameterwidth of a tree is defined as the number of nodes on the longest path between two end nodes root node1 root depth 1 root left node2 root depth 2 root left depth 1 root right node3 root depth 2 root node1 root diameter 1 root left node2 root diameter 2 root left diameter 1 root right node3 root diameter 3 printfroot diameter 4 printfroot left diameter 3 printfroot right diameter 1 root node 1 root depth 1 root left node 2 root depth 2 root left depth 1 root right node 3 root depth 2 root node 1 root diameter 1 root left node 2 root diameter 2 root left diameter 1 root right node 3 root diameter 3 constructed binary tree is 1 2 3 4 5 4 3 1
from __future__ import annotations from dataclasses import dataclass @dataclass class Node: data: int left: Node | None = None right: Node | None = None def depth(self) -> int: left_depth = self.left.depth() if self.left else 0 right_depth = self.right.depth() if self.right else 0 return max(left_depth, right_depth) + 1 def diameter(self) -> int: left_depth = self.left.depth() if self.left else 0 right_depth = self.right.depth() if self.right else 0 return left_depth + right_depth + 1 if __name__ == "__main__": from doctest import testmod testmod() root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) r print(f"{root.diameter() = }") print(f"{root.left.diameter() = }") print(f"{root.right.diameter() = }")
alexander pantyukhin date november 7 2022 task you are given a tree root of a binary tree with n nodes where each node has node data coins there are exactly n coins in whole tree in one move we may choose two adjacent nodes and move one coin from one node to another a move may be from parent to child or from child to parent return the minimum number of moves required to make every node have exactly one coin example 1 3 0 0 result 2 example 2 0 3 0 result 3 leetcode https leetcode comproblemsdistributecoinsinbinarytree implementation notes user depthfirst search approach let n is the number of nodes in tree runtime on space o1 distributecoinstreenode3 treenode0 treenode0 2 distributecoinstreenode0 treenode3 treenode0 3 distributecoinstreenode0 treenode0 treenode3 3 distributecoinsnone 0 distributecoinstreenode0 treenode0 treenode0 traceback most recent call last valueerror the nodes number should be same as the number of coins distributecoinstreenode0 treenode1 treenode1 traceback most recent call last valueerror the nodes number should be same as the number of coins validation countnodesnone 0 countcoinsnone 0 main calculation getdistribnone namedtuplecoinsdistribresult 0 2 distribute_coins treenode 3 treenode 0 treenode 0 2 distribute_coins treenode 0 treenode 3 treenode 0 3 distribute_coins treenode 0 treenode 0 treenode 3 3 distribute_coins none 0 distribute_coins treenode 0 treenode 0 treenode 0 traceback most recent call last valueerror the nodes number should be same as the number of coins distribute_coins treenode 0 treenode 1 treenode 1 traceback most recent call last valueerror the nodes number should be same as the number of coins validation count_nodes none 0 count_coins none 0 main calculation get_distrib none namedtuple coinsdistribresult 0 2
from __future__ import annotations from dataclasses import dataclass from typing import NamedTuple @dataclass class TreeNode: data: int left: TreeNode | None = None right: TreeNode | None = None class CoinsDistribResult(NamedTuple): moves: int excess: int def distribute_coins(root: TreeNode | None) -> int: if root is None: return 0 def count_nodes(node: TreeNode | None) -> int: if node is None: return 0 return count_nodes(node.left) + count_nodes(node.right) + 1 def count_coins(node: TreeNode | None) -> int: if node is None: return 0 return count_coins(node.left) + count_coins(node.right) + node.data if count_nodes(root) != count_coins(root): raise ValueError("The nodes number should be same as the number of coins") def get_distrib(node: TreeNode | None) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0, 1) left_distrib_moves, left_distrib_excess = get_distrib(node.left) right_distrib_moves, right_distrib_excess = get_distrib(node.right) coins_to_left = 1 - left_distrib_excess coins_to_right = 1 - right_distrib_excess result_moves = ( left_distrib_moves + right_distrib_moves + abs(coins_to_left) + abs(coins_to_right) ) result_excess = node.data - coins_to_left - coins_to_right return CoinsDistribResult(result_moves, result_excess) return get_distrib(root)[0] if __name__ == "__main__": import doctest doctest.testmod()
fenwick tree more info https en wikipedia orgwikifenwicktree constructor for the fenwick tree parameters arr list list of elements to initialize the tree with optional size int size of the fenwick tree if arr is none initialize the fenwick tree with arr in on parameters arr list list of elements to initialize the tree with returns none a 1 2 3 4 5 f1 fenwicktreea f2 fenwicktreesizelena for index value in enumeratea f2 addindex value f1 tree f2 tree true get the normal array of the fenwick tree in on returns list normal array of the fenwick tree a i for i in range128 f fenwicktreea f getarray a true add a value to index in olg n parameters index int index to add value to value int value to add to index returns none f fenwicktree1 2 3 4 5 f add0 1 f add1 2 f add2 3 f add3 4 f add4 5 f getarray 2 4 6 8 10 set the value of index in olg n parameters index int index to set value to value int value to set in index returns none f fenwicktree5 4 3 2 1 f update0 1 f update1 2 f update2 3 f update3 4 f update4 5 f getarray 1 2 3 4 5 prefix sum of all elements in 0 right in olg n parameters right int right bound of the query exclusive returns int sum of all elements in 0 right a i for i in range128 f fenwicktreea res true for i in rangelena res res and f prefixi suma i res true query the sum of all elements in left right in olg n parameters left int left bound of the query inclusive right int right bound of the query exclusive returns int sum of all elements in left right a i for i in range128 f fenwicktreea res true for i in rangelena for j in rangei 1 lena res res and f queryi j sumai j res true get value at index in olg n parameters index int index to get the value returns int value of element at index a i for i in range128 f fenwicktreea res true for i in rangelena res res and f geti ai res true find the largest index with prefixi value in olg n note requires that all values are nonnegative parameters value int value to find the largest index of returns 1 if value is smaller than all elements in prefix sum int largest index with prefixi value f fenwicktree1 2 0 3 0 5 f rankquery0 1 f rankquery2 0 f rankquery1 0 f rankquery3 2 f rankquery5 2 f rankquery6 4 f rankquery11 5 fenwick tree more info https en wikipedia org wiki fenwick_tree constructor for the fenwick tree parameters arr list list of elements to initialize the tree with optional size int size of the fenwick tree if arr is none initialize the fenwick tree with arr in o n parameters arr list list of elements to initialize the tree with returns none a 1 2 3 4 5 f1 fenwicktree a f2 fenwicktree size len a for index value in enumerate a f2 add index value f1 tree f2 tree true get the normal array of the fenwick tree in o n returns list normal array of the fenwick tree a i for i in range 128 f fenwicktree a f get_array a true add a value to index in o lg n parameters index int index to add value to value int value to add to index returns none f fenwicktree 1 2 3 4 5 f add 0 1 f add 1 2 f add 2 3 f add 3 4 f add 4 5 f get_array 2 4 6 8 10 set the value of index in o lg n parameters index int index to set value to value int value to set in index returns none f fenwicktree 5 4 3 2 1 f update 0 1 f update 1 2 f update 2 3 f update 3 4 f update 4 5 f get_array 1 2 3 4 5 prefix sum of all elements in 0 right in o lg n parameters right int right bound of the query exclusive returns int sum of all elements in 0 right a i for i in range 128 f fenwicktree a res true for i in range len a res res and f prefix i sum a i res true make right inclusive query the sum of all elements in left right in o lg n parameters left int left bound of the query inclusive right int right bound of the query exclusive returns int sum of all elements in left right a i for i in range 128 f fenwicktree a res true for i in range len a for j in range i 1 len a res res and f query i j sum a i j res true get value at index in o lg n parameters index int index to get the value returns int value of element at index a i for i in range 128 f fenwicktree a res true for i in range len a res res and f get i a i res true find the largest index with prefix i value in o lg n note requires that all values are non negative parameters value int value to find the largest index of returns 1 if value is smaller than all elements in prefix sum int largest index with prefix i value f fenwicktree 1 2 0 3 0 5 f rank_query 0 1 f rank_query 2 0 f rank_query 1 0 f rank_query 3 2 f rank_query 5 2 f rank_query 6 4 f rank_query 11 5 largest power of 2 size
from copy import deepcopy class FenwickTree: def __init__(self, arr: list[int] | None = None, size: int | None = None) -> None: if arr is None and size is not None: self.size = size self.tree = [0] * size elif arr is not None: self.init(arr) else: raise ValueError("Either arr or size must be specified") def init(self, arr: list[int]) -> None: self.size = len(arr) self.tree = deepcopy(arr) for i in range(1, self.size): j = self.next_(i) if j < self.size: self.tree[j] += self.tree[i] def get_array(self) -> list[int]: arr = self.tree[:] for i in range(self.size - 1, 0, -1): j = self.next_(i) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def next_(index: int) -> int: return index + (index & (-index)) @staticmethod def prev(index: int) -> int: return index - (index & (-index)) def add(self, index: int, value: int) -> None: if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value index = self.next_(index) def update(self, index: int, value: int) -> None: self.add(index, value - self.get(index)) def prefix(self, right: int) -> int: if right == 0: return 0 result = self.tree[0] right -= 1 while right > 0: result += self.tree[right] right = self.prev(right) return result def query(self, left: int, right: int) -> int: return self.prefix(right) - self.prefix(left) def get(self, index: int) -> int: return self.query(index, index + 1) def rank_query(self, value: int) -> int: value -= self.tree[0] if value < 0: return -1 j = 1 while j * 2 < self.size: j *= 2 i = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
binary tree flattening algorithm this code defines an algorithm to flatten a binary tree into a linked list represented using the right pointers of the tree nodes it uses inplace flattening and demonstrates the flattening process along with a display function to visualize the flattened linked list https www geeksforgeeks orgflattenabinarytreeintolinkedlist arunkumar a date 04092023 a treenode has data variable and pointers to treenode objects for its left and right children build and return a sample binary tree returns treenode the root of the binary tree examples root buildtree root data 1 root left data 2 root right data 5 root left left data 3 root left right data 4 root right right data 6 flatten a binary tree into a linked list inplace where the linked list is represented using the right pointers of the tree nodes args root treenode the root of the binary tree to be flattened examples root treenode1 root left treenode2 root right treenode5 root left left treenode3 root left right treenode4 root right right treenode6 flattenroot root data 1 root right right is none false root right right treenode3 root right right right is none true flatten the left subtree save the right subtree make the left subtree the new right subtree find the end of the new right subtree append the original right subtree to the end flatten the updated right subtree display the flattened linked list args root treenode none the root of the flattened linked list examples root treenode1 root right treenode2 root right right treenode3 displaylinkedlistroot 1 2 3 root none displaylinkedlistroot a treenode has data variable and pointers to treenode objects for its left and right children build and return a sample binary tree returns treenode the root of the binary tree examples root build_tree root data 1 root left data 2 root right data 5 root left left data 3 root left right data 4 root right right data 6 flatten a binary tree into a linked list in place where the linked list is represented using the right pointers of the tree nodes args root treenode the root of the binary tree to be flattened examples root treenode 1 root left treenode 2 root right treenode 5 root left left treenode 3 root left right treenode 4 root right right treenode 6 flatten root root data 1 root right right is none false root right right treenode 3 root right right right is none true flatten the left subtree save the right subtree make the left subtree the new right subtree find the end of the new right subtree append the original right subtree to the end flatten the updated right subtree display the flattened linked list args root treenode none the root of the flattened linked list examples root treenode 1 root right treenode 2 root right right treenode 3 display_linked_list root 1 2 3 root none display_linked_list root
from __future__ import annotations class TreeNode: def __init__(self, data: int) -> None: self.data = data self.left: TreeNode | None = None self.right: TreeNode | None = None def build_tree() -> TreeNode: root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(5) root.left.left = TreeNode(3) root.left.right = TreeNode(4) root.right.right = TreeNode(6) return root def flatten(root: TreeNode | None) -> None: if not root: return flatten(root.left) right_subtree = root.right root.right = root.left root.left = None current = root while current.right: current = current.right current.right = right_subtree flatten(right_subtree) def display_linked_list(root: TreeNode | None) -> None: current = root while current: if current.right is None: print(current.data, end="") break print(current.data, end=" ") current = current.right if __name__ == "__main__": print("Flattened Linked List:") root = build_tree() flatten(root) display_linked_list(root)
in a binary search tree bst the floor of key k is the maximum value that is smaller than or equal to k the ceiling of key k is the minimum value that is greater than or equal to k reference https bit ly46ub0a2 arunkumar date 14th october 2023 find the floor and ceiling values for a given key in a binary search tree bst args root the root of the binary search tree key the key for which to find the floor and ceiling returns a tuple containing the floor and ceiling values respectively examples root node10 root left node5 root right node20 root left left node3 root left right node7 root right left node15 root right right node25 tupleroot 3 5 7 10 15 20 25 floorceilingroot 8 7 10 floorceilingroot 14 10 15 floorceilingroot 1 none 3 floorceilingroot 30 25 none find the floor and ceiling values for a given key in a binary search tree bst args root the root of the binary search tree key the key for which to find the floor and ceiling returns a tuple containing the floor and ceiling values respectively examples root node 10 root left node 5 root right node 20 root left left node 3 root left right node 7 root right left node 15 root right right node 25 tuple root 3 5 7 10 15 20 25 floor_ceiling root 8 7 10 floor_ceiling root 14 10 15 floor_ceiling root 1 none 3 floor_ceiling root 30 25 none
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass @dataclass class Node: key: int left: Node | None = None right: Node | None = None def __iter__(self) -> Iterator[int]: if self.left: yield from self.left yield self.key if self.right: yield from self.right def __len__(self) -> int: return sum(1 for _ in self) def floor_ceiling(root: Node | None, key: int) -> tuple[int | None, int | None]: floor_val = None ceiling_val = None while root: if root.key == key: floor_val = root.key ceiling_val = root.key break if key < root.key: ceiling_val = root.key root = root.left else: floor_val = root.key root = root.right return floor_val, ceiling_val if __name__ == "__main__": import doctest doctest.testmod()
illustrate how to implement inorder traversal in binary search tree gurneet singh https www geeksforgeeks orgtreetraversalsinorderpreorderandpostorder defining the structure of binarytreenode def initself data int none self data data self leftchild binarytreenode none none self rightchild binarytreenode none none def insertnode binarytreenode none newvalue int binarytreenode none if node is none node binarytreenodenewvalue return node binary search tree is not empty so we will insert it into the tree if newvalue is less than value of data in node add it to left subtree and proceed recursively if newvalue node data node leftchild insertnode leftchild newvalue else if newvalue is greater than value of data in node add it to right subtree and proceed recursively node rightchild insertnode rightchild newvalue return node def inordernode none binarytreenode listint if node is none return if node inorderarray inordernode leftchild inorderarray inorderarray node data inorderarray inorderarray inordernode rightchild else inorderarray return inorderarray def maketree binarytreenode none root insertnone 15 insertroot 10 insertroot 25 insertroot 6 insertroot 14 insertroot 20 insertroot 60 return root def main none main function root maketree printprinting values of binary search tree in inorder traversal inorderroot if name main import doctest doctest testmod main defining the structure of binarytreenode if the binary search tree is empty make a new node and declare it as root node_a binarytreenode 12345 node_b insert node_a 67890 node_a left_child node_b left_child true node_a right_child node_b right_child true node_a data node_b data true binary search tree is not empty so we will insert it into the tree if new_value is less than value of data in node add it to left subtree and proceed recursively if new_value is greater than value of data in node add it to right subtree and proceed recursively if node is none return inorder make_tree 6 10 14 15 20 25 60 main function
class BinaryTreeNode: def __init__(self, data: int) -> None: self.data = data self.left_child: BinaryTreeNode | None = None self.right_child: BinaryTreeNode | None = None def insert(node: BinaryTreeNode | None, new_value: int) -> BinaryTreeNode | None: if node is None: node = BinaryTreeNode(new_value) return node if new_value < node.data: node.left_child = insert(node.left_child, new_value) else: node.right_child = insert(node.right_child, new_value) return node def inorder(node: None | BinaryTreeNode) -> list[int]: if node: inorder_array = inorder(node.left_child) inorder_array = [*inorder_array, node.data] inorder_array = inorder_array + inorder(node.right_child) else: inorder_array = [] return inorder_array def make_tree() -> BinaryTreeNode | None: root = insert(None, 15) insert(root, 10) insert(root, 25) insert(root, 6) insert(root, 14) insert(root, 20) insert(root, 60) return root def main() -> None: root = make_tree() print("Printing values of binary search tree in Inorder Traversal.") inorder(root) if __name__ == "__main__": import doctest doctest.testmod() main()
given the root of a binary tree determine if it is a valid binary search tree bst a valid binary search tree is defined as follows the left subtree of a node contains only nodes with keys less than the node s key the right subtree of a node contains only nodes with keys greater than the node s key both the left and right subtrees must also be binary search trees in effect a binary tree is a valid bst if its nodes are sorted in ascending order leetcode https leetcode comproblemsvalidatebinarysearchtree if n is the number of nodes in the tree then runtime on space o1 root nodedata2 1 listroot 2 1 root leftnodedata2 0 listroot 2 0 2 1 root rightnodedata2 2 listroot 2 0 2 1 2 2 nodedata abc issorted true nodedata2 leftnodedata1 999 rightnodedata3 issorted true nodedata0 leftnodedata0 rightnodedata0 issorted true nodedata0 leftnodedata11 rightnodedata3 issorted true nodedata5 leftnodedata1 rightnodedata4 leftnodedata3 issorted false nodedata a leftnodedata1 rightnodedata4 leftnodedata3 issorted traceback most recent call last typeerror not supported between instances of str and int nodedata2 leftnode rightnodedata4 leftnodedata3 issorted traceback most recent call last typeerror not supported between instances of int and list root node data 2 1 list root 2 1 root left node data 2 0 list root 2 0 2 1 root right node data 2 2 list root 2 0 2 1 2 2 node data abc is_sorted true node data 2 left node data 1 999 right node data 3 is_sorted true node data 0 left node data 0 right node data 0 is_sorted true node data 0 left node data 11 right node data 3 is_sorted true node data 5 left node data 1 right node data 4 left node data 3 is_sorted false node data a left node data 1 right node data 4 left node data 3 is_sorted traceback most recent call last typeerror not supported between instances of str and int node data 2 left node right node data 4 left node data 3 is_sorted traceback most recent call last typeerror not supported between instances of int and list
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass @dataclass class Node: data: float left: Node | None = None right: Node | None = None def __iter__(self) -> Iterator[float]: if self.left: yield from self.left yield self.data if self.right: yield from self.right @property def is_sorted(self) -> bool: if self.left and (self.data < self.left.data or not self.left.is_sorted): return False if self.right and (self.data > self.right.data or not self.right.is_sorted): return False return True if __name__ == "__main__": import doctest doctest.testmod() tree = Node(data=2.1, left=Node(data=2.0), right=Node(data=2.2)) print(f"Tree {list(tree)} is sorted: {tree.is_sorted = }.") assert tree.right tree.right.data = 2.0 print(f"Tree {list(tree)} is sorted: {tree.is_sorted = }.") tree.right.data = 2.1 print(f"Tree {list(tree)} is sorted: {tree.is_sorted = }.")
is a binary tree a sum tree where the value of every nonleaf node is equal to the sum of the values of its left and right subtrees https www geeksforgeeks orgcheckifagivenbinarytreeissumtree root node2 listroot 2 root left node1 tupleroot 1 2 root node2 lenroot 1 root left node1 lenroot 2 root node3 root issumnode true root left node1 root issumnode false root right node2 root issumnode true listbinarytree buildatree 1 2 7 11 15 29 35 40 lenbinarytree buildatree 8 returns a string representation of the inorder traversal of the binary tree strlistbinarytree buildatree 1 2 7 11 15 29 35 40 binarytree buildatree issumtree false binarytree buildasumtree issumtree true tree binarytreenode11 root tree root root left node2 root right node29 root left left node1 root left right node7 root right left node15 root right right node40 root right right left node35 return tree classmethod def buildasumtreecls binarytree r create a binary tree with the specified structure 26 10 3 4 6 3 listbinarytree buildasumtree 4 10 6 26 3 3 root node 2 list root 2 root left node 1 tuple root 1 2 root node 2 len root 1 root left node 1 len root 2 root node 3 root is_sum_node true root left node 1 root is_sum_node false root right node 2 root is_sum_node true leaf nodes are considered sum nodes list binarytree build_a_tree 1 2 7 11 15 29 35 40 len binarytree build_a_tree 8 returns a string representation of the inorder traversal of the binary tree str list binarytree build_a_tree 1 2 7 11 15 29 35 40 binarytree build_a_tree is_sum_tree false binarytree build_a_sum_tree is_sum_tree true create a binary tree with the specified structure 11 2 29 1 7 15 40 35 list binarytree build_a_tree 1 2 7 11 15 29 35 40 create a binary tree with the specified structure 26 10 3 4 6 3 list binarytree build_a_sum_tree 4 10 6 26 3 3
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass @dataclass class Node: data: int left: Node | None = None right: Node | None = None def __iter__(self) -> Iterator[int]: if self.left: yield from self.left yield self.data if self.right: yield from self.right def __len__(self) -> int: return sum(1 for _ in self) @property def is_sum_node(self) -> bool: if not self.left and not self.right: return True left_sum = sum(self.left) if self.left else 0 right_sum = sum(self.right) if self.right else 0 return all( ( self.data == left_sum + right_sum, self.left.is_sum_node if self.left else True, self.right.is_sum_node if self.right else True, ) ) @dataclass class BinaryTree: root: Node def __iter__(self) -> Iterator[int]: return iter(self.root) def __len__(self) -> int: return len(self.root) def __str__(self) -> str: return str(list(self)) @property def is_sum_tree(self) -> bool: return self.root.is_sum_node @classmethod def build_a_tree(cls) -> BinaryTree: r tree = BinaryTree(Node(11)) root = tree.root root.left = Node(2) root.right = Node(29) root.left.left = Node(1) root.left.right = Node(7) root.right.left = Node(15) root.right.right = Node(40) root.right.right.left = Node(35) return tree @classmethod def build_a_sum_tree(cls) -> BinaryTree: r tree = BinaryTree(Node(26)) root = tree.root root.left = Node(10) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(6) root.right.right = Node(3) return tree if __name__ == "__main__": from doctest import testmod testmod() tree = BinaryTree.build_a_tree() print(f"{tree} has {len(tree)} nodes and {tree.is_sum_tree = }.") tree = BinaryTree.build_a_sum_tree() print(f"{tree} has {len(tree)} nodes and {tree.is_sum_tree = }.")
approximate the overall size of segment tree with given value create array to store lazy update segmenttree segmenttree15 segmenttree left1 2 segmenttree left2 4 segmenttree left12 24 segmenttree segmenttree15 segmenttree right1 3 segmenttree right2 5 segmenttree right12 25 update with olg n normal segment tree without lazy update will take onlg n for each update update1 1 size a b v for update val v to a b query with olg n query1 1 size a b for query max of a b a 1 2 4 7 3 5 6 11 20 9 14 15 5 2 8 segmenttree segmenttree15 segmenttree build1 1 15 a segmenttree query1 1 15 4 6 7 segmenttree query1 1 15 7 11 14 segmenttree query1 1 15 7 12 15 approximate the overall size of segment tree with given value create array to store lazy update flag for lazy update segment_tree segmenttree 15 segment_tree left 1 2 segment_tree left 2 4 segment_tree left 12 24 segment_tree segmenttree 15 segment_tree right 1 3 segment_tree right 2 5 segment_tree right 12 25 update with o lg n normal segment tree without lazy update will take o nlg n for each update update 1 1 size a b v for update val v to a b query with o lg n query 1 1 size a b for query max of a b a 1 2 4 7 3 5 6 11 20 9 14 15 5 2 8 segment_tree segmenttree 15 segment_tree build 1 1 15 a segment_tree query 1 1 15 4 6 7 segment_tree query 1 1 15 7 11 14 segment_tree query 1 1 15 7 12 15
from __future__ import annotations import math class SegmentTree: def __init__(self, size: int) -> None: self.size = size self.segment_tree = [0 for i in range(4 * size)] self.lazy = [0 for i in range(4 * size)] self.flag = [0 for i in range(4 * size)] def left(self, idx: int) -> int: return idx * 2 def right(self, idx: int) -> int: return idx * 2 + 1 def build( self, idx: int, left_element: int, right_element: int, a: list[int] ) -> None: if left_element == right_element: self.segment_tree[idx] = a[left_element - 1] else: mid = (left_element + right_element) // 2 self.build(self.left(idx), left_element, mid, a) self.build(self.right(idx), mid + 1, right_element, a) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] ) def update( self, idx: int, left_element: int, right_element: int, a: int, b: int, val: int ) -> bool: if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: self.segment_tree[idx] = val if left_element != right_element: self.lazy[self.left(idx)] = val self.lazy[self.right(idx)] = val self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True return True mid = (left_element + right_element) // 2 self.update(self.left(idx), left_element, mid, a, b, val) self.update(self.right(idx), mid + 1, right_element, a, b, val) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] ) return True def query( self, idx: int, left_element: int, right_element: int, a: int, b: int ) -> int | float: if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] mid = (left_element + right_element) // 2 q1 = self.query(self.left(idx), left_element, mid, a, b) q2 = self.query(self.right(idx), mid + 1, right_element, a, b) return max(q1, q2) def __str__(self) -> str: return str([self.query(1, 1, self.size, i, i) for i in range(1, self.size + 1)]) if __name__ == "__main__": A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] size = 15 segt = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
https en wikipedia orgwikilowestcommonancestor https en wikipedia orgwikibreadthfirstsearch return a tuple b a when given two integers a and b swap2 3 3 2 swap3 4 4 3 swap67 12 12 67 creating sparse table which saves each nodes 2ith parent returns lca of node u v u must be deeper in the tree than v making depth of u same as depth of v at the same depth if uv that mean lca is found moving both nodes upwards till lca in found returning longest common ancestor of u v runs a breadth first search from root node of the tree sets every nodes direct parent parent of root node is set to 0 calculates depth of each node from root node initializing with 0 initializing with 1 which means every node is unvisited https en wikipedia org wiki lowest_common_ancestor https en wikipedia org wiki breadth first_search return a tuple b a when given two integers a and b swap 2 3 3 2 swap 3 4 4 3 swap 67 12 12 67 creating sparse table which saves each nodes 2 i th parent returns lca of node u v u must be deeper in the tree than v making depth of u same as depth of v at the same depth if u v that mean lca is found moving both nodes upwards till lca in found returning longest common ancestor of u v runs a breadth first search from root node of the tree sets every nodes direct parent parent of root node is set to 0 calculates depth of each node from root node initializing with 0 initializing with 1 which means every node is unvisited
from __future__ import annotations from queue import Queue def swap(a: int, b: int) -> tuple[int, int]: a ^= b b ^= a a ^= b return a, b def create_sparse(max_node: int, parent: list[list[int]]) -> list[list[int]]: j = 1 while (1 << j) < max_node: for i in range(1, max_node + 1): parent[j][i] = parent[j - 1][parent[j - 1][i]] j += 1 return parent def lowest_common_ancestor( u: int, v: int, level: list[int], parent: list[list[int]] ) -> int: if level[u] < level[v]: u, v = swap(u, v) for i in range(18, -1, -1): if level[u] - (1 << i) >= level[v]: u = parent[i][u] if u == v: return u for i in range(18, -1, -1): if parent[i][u] not in [0, parent[i][v]]: u, v = parent[i][u], parent[i][v] return parent[0][u] def breadth_first_search( level: list[int], parent: list[list[int]], max_node: int, graph: dict[int, list[int]], root: int = 1, ) -> tuple[list[int], list[list[int]]]: level[root] = 0 q: Queue[int] = Queue(maxsize=max_node) q.put(root) while q.qsize() != 0: u = q.get() for v in graph[u]: if level[v] == -1: level[v] = level[u] + 1 q.put(v) parent[0][v] = u return level, parent def main() -> None: max_node = 13 parent = [[0 for _ in range(max_node + 10)] for _ in range(20)] level = [-1 for _ in range(max_node + 10)] graph: dict[int, list[int]] = { 1: [2, 3, 4], 2: [5], 3: [6, 7], 4: [8], 5: [9, 10], 6: [11], 7: [], 8: [12, 13], 9: [], 10: [], 11: [], 12: [], 13: [], } level, parent = breadth_first_search(level, parent, max_node, graph, 1) parent = create_sparse(max_node, parent) print("LCA of node 1 and 3 is: ", lowest_common_ancestor(1, 3, level, parent)) print("LCA of node 5 and 6 is: ", lowest_common_ancestor(5, 6, level, parent)) print("LCA of node 7 and 11 is: ", lowest_common_ancestor(7, 11, level, parent)) print("LCA of node 6 and 7 is: ", lowest_common_ancestor(6, 7, level, parent)) print("LCA of node 4 and 12 is: ", lowest_common_ancestor(4, 12, level, parent)) print("LCA of node 8 and 8 is: ", lowest_common_ancestor(8, 8, level, parent)) if __name__ == "__main__": main()
maximum fenwick tree more info https cpalgorithms comdatastructuresfenwick html ft maxfenwicktree5 ft query0 5 0 ft update4 100 ft query0 5 100 ft update4 0 ft update2 20 ft query0 5 20 ft update4 10 ft query2 5 20 ft query1 5 20 ft update2 0 ft query0 5 10 ft maxfenwicktree10000 ft update255 30 ft query0 10000 30 ft maxfenwicktree6 ft update5 1 ft query5 6 1 ft maxfenwicktree6 ft update0 1000 ft query0 1 1000 create empty maximum fenwick tree with specified size parameters size size of array returns none get next index in o1 get previous index in o1 set index to value in olg2 n parameters index index to update value value to set returns none answer the query of maximum range l r in olg2 n parameters left left index of query range inclusive right right index of query range exclusive returns maximum value of range left right maximum fenwick tree more info https cp algorithms com data_structures fenwick html ft maxfenwicktree 5 ft query 0 5 0 ft update 4 100 ft query 0 5 100 ft update 4 0 ft update 2 20 ft query 0 5 20 ft update 4 10 ft query 2 5 20 ft query 1 5 20 ft update 2 0 ft query 0 5 10 ft maxfenwicktree 10000 ft update 255 30 ft query 0 10000 30 ft maxfenwicktree 6 ft update 5 1 ft query 5 6 1 ft maxfenwicktree 6 ft update 0 1000 ft query 0 1 1000 create empty maximum fenwick tree with specified size parameters size size of array returns none get next index in o 1 get previous index in o 1 set index to value in o lg 2 n parameters index index to update value value to set returns none answer the query of maximum range l r in o lg 2 n parameters left left index of query range inclusive right right index of query range exclusive returns maximum value of range left right because of right is exclusive
class MaxFenwickTree: def __init__(self, size: int) -> None: self.size = size self.arr = [0] * size self.tree = [0] * size @staticmethod def get_next(index: int) -> int: return index | (index + 1) @staticmethod def get_prev(index: int) -> int: return (index & (index + 1)) - 1 def update(self, index: int, value: int) -> None: self.arr[index] = value while index < self.size: current_left_border = self.get_prev(index) + 1 if current_left_border == index: self.tree[index] = value else: self.tree[index] = max(value, current_left_border, index) index = self.get_next(index) def query(self, left: int, right: int) -> int: right -= 1 result = 0 while left <= right: current_left = self.get_prev(right) if left <= current_left: result = max(result, self.tree[right]) right = current_left else: result = max(result, self.arr[right]) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
usrlocalbinpython3 problem description given two binary tree return the merged tree the rule for merging is that if two nodes overlap then put the value sum of both nodes to the new value of the merged node otherwise the not null node will be used as the node of new tree a binary node has value variable and pointers to its left and right node returns root node of the merged tree tree1 node5 tree1 left node6 tree1 right node7 tree1 left left node2 tree2 node4 tree2 left node5 tree2 right node8 tree2 left right node1 tree2 right right node4 mergedtree mergetwobinarytreestree1 tree2 printpreordermergedtree 9 11 2 1 15 4 print preorder traversal of the tree root node1 root left node2 root right node3 printpreorderroot 1 2 3 printpreorderroot right 3 usr local bin python3 problem description given two binary tree return the merged tree the rule for merging is that if two nodes overlap then put the value sum of both nodes to the new value of the merged node otherwise the not null node will be used as the node of new tree a binary node has value variable and pointers to its left and right node returns root node of the merged tree tree1 node 5 tree1 left node 6 tree1 right node 7 tree1 left left node 2 tree2 node 4 tree2 left node 5 tree2 right node 8 tree2 left right node 1 tree2 right right node 4 merged_tree merge_two_binary_trees tree1 tree2 print_preorder merged_tree 9 11 2 1 15 4 print pre order traversal of the tree root node 1 root left node 2 root right node 3 print_preorder root 1 2 3 print_preorder root right 3
from __future__ import annotations class Node: def __init__(self, value: int = 0) -> None: self.value = value self.left: Node | None = None self.right: Node | None = None def merge_two_binary_trees(tree1: Node | None, tree2: Node | None) -> Node | None: if tree1 is None: return tree2 if tree2 is None: return tree1 tree1.value = tree1.value + tree2.value tree1.left = merge_two_binary_trees(tree1.left, tree2.left) tree1.right = merge_two_binary_trees(tree1.right, tree2.right) return tree1 def print_preorder(root: Node | None) -> None: if root: print(root.value) print_preorder(root.left) print_preorder(root.right) if __name__ == "__main__": tree1 = Node(1) tree1.left = Node(2) tree1.right = Node(3) tree1.left.left = Node(4) tree2 = Node(2) tree2.left = Node(4) tree2.right = Node(6) tree2.left.right = Node(9) tree2.right.right = Node(5) print("Tree1 is: ") print_preorder(tree1) print("Tree2 is: ") print_preorder(tree2) merged_tree = merge_two_binary_trees(tree1, tree2) print("Merged Tree is: ") print_preorder(merged_tree)
given the root of a binary tree mirror the tree and return its root leetcode problem reference https leetcode comproblemsmirrorbinarytree a node has value variable and pointers to nodes to its left and right mirror the binary tree rooted at this node by swapping left and right children tree node0 listtree 0 listtree mirror 0 tree node1 node0 node3 node2 node4 none node5 tupletree 0 1 2 3 4 5 tupletree mirror 5 4 3 2 1 0 tree node1 tree left node2 tree right node3 tree left left node4 tree left right node5 tree right left node6 tree right right node7 return tree def maketreenine node r return a binary tree with 9 nodes that looks like this 1 2 3 4 5 6 7 8 9 treenine maketreenine lentreenine 9 listtreenine 7 4 8 2 5 9 1 3 6 trees zero node0 seven maketreeseven nine maketreenine for name tree in trees items printf the name tree tupletree 0 4 2 5 1 6 3 7 7 4 8 2 5 9 1 3 6 printfmirror of name tree tupletree mirror 0 7 3 6 1 5 2 4 6 3 1 9 5 2 8 4 7 if name main import doctest doctest testmod main a node has value variable and pointers to nodes to its left and right mirror the binary tree rooted at this node by swapping left and right children tree node 0 list tree 0 list tree mirror 0 tree node 1 node 0 node 3 node 2 node 4 none node 5 tuple tree 0 1 2 3 4 5 tuple tree mirror 5 4 3 2 1 0 return a binary tree with 7 nodes that looks like this 1 2 3 4 5 6 7 tree_seven make_tree_seven len tree_seven 7 list tree_seven 4 2 5 1 6 3 7 return a binary tree with 9 nodes that looks like this 1 2 3 4 5 6 7 8 9 tree_nine make_tree_nine len tree_nine 9 list tree_nine 7 4 8 2 5 9 1 3 6 mirror binary trees with the given root and returns the root tree make_tree_nine tuple tree 7 4 8 2 5 9 1 3 6 tuple tree mirror 6 3 1 9 5 2 8 4 7 nine_tree 1 2 3 4 5 6 7 8 9 the mirrored tree looks like this 1 3 2 6 5 4 9 8 7 0 4 2 5 1 6 3 7 7 4 8 2 5 9 1 3 6 0 7 3 6 1 5 2 4 6 3 1 9 5 2 8 4 7
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass @dataclass class Node: value: int left: Node | None = None right: Node | None = None def __iter__(self) -> Iterator[int]: if self.left: yield from self.left yield self.value if self.right: yield from self.right def __len__(self) -> int: return sum(1 for _ in self) def mirror(self) -> Node: self.left, self.right = self.right, self.left if self.left: self.left.mirror() if self.right: self.right.mirror() return self def make_tree_seven() -> Node: r tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) tree.right.left = Node(6) tree.right.right = Node(7) return tree def make_tree_nine() -> Node: r tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) tree.right.right = Node(6) tree.left.left.left = Node(7) tree.left.left.right = Node(8) tree.left.right.right = Node(9) return tree def main() -> None: r trees = {"zero": Node(0), "seven": make_tree_seven(), "nine": make_tree_nine()} for name, tree in trees.items(): print(f" The {name} tree: {tuple(tree)}") print(f"Mirror of {name} tree: {tuple(tree.mirror())}") if __name__ == "__main__": import doctest doctest.testmod() main()
a nonrecursive segment tree implementation with range query and single element update works virtually with any list of the same type of elements with a commutative combiner explanation https www geeksforgeeks orgiterativesegmenttreerangeminimumquery https www geeksforgeeks orgsegmenttreeefficientimplementation segmenttree1 2 3 lambda a b a b query0 2 6 segmenttree3 1 2 min query0 2 1 segmenttree2 3 1 max query0 2 3 st segmenttree1 5 7 1 6 lambda a b a b st update1 1 st update2 3 st query1 2 2 st query1 1 1 st update4 1 st query3 4 0 st segmenttree1 2 3 3 2 1 1 1 1 lambda a b ai bi for i in rangelena st query0 1 4 4 4 st query1 2 4 3 2 st update1 1 1 1 st query1 2 0 0 0 st query0 2 1 2 3 segment tree constructor it works just with commutative combiner param arr list of elements for the segment tree param fnc commutative function for combine two elements segmenttree a b c lambda a b f ab query0 2 abc segmenttree1 2 2 3 3 4 lambda a b a0 b0 a1 b1 query0 2 6 9 update an element in logn time param p position to be update param v new value st segmenttree3 1 2 4 min st query0 3 1 st update2 1 st query0 3 1 get range query value in logn time param l left element index param r right element index return element combined in the range l r st segmenttree1 2 3 4 lambda a b a b st query0 2 6 st query1 2 5 st query0 3 10 st query2 3 7 test all possible segments segment tree constructor it works just with commutative combiner param arr list of elements for the segment tree param fnc commutative function for combine two elements segmenttree a b c lambda a b f a b query 0 2 abc segmenttree 1 2 2 3 3 4 lambda a b a 0 b 0 a 1 b 1 query 0 2 6 9 update an element in log n time param p position to be update param v new value st segmenttree 3 1 2 4 min st query 0 3 1 st update 2 1 st query 0 3 1 noqa e741 get range query value in log n time param l left element index param r right element index return element combined in the range l r st segmenttree 1 2 3 4 lambda a b a b st query 0 2 6 st query 1 2 5 st query 0 3 10 st query 2 3 7 test all possible segments
from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar T = TypeVar("T") class SegmentTree(Generic[T]): def __init__(self, arr: list[T], fnc: Callable[[T, T], T]) -> None: any_type: Any | T = None self.N: int = len(arr) self.st: list[T] = [any_type for _ in range(self.N)] + arr self.fn = fnc self.build() def build(self) -> None: for p in range(self.N - 1, 0, -1): self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1]) def update(self, p: int, v: T) -> None: p += self.N self.st[p] = v while p > 1: p = p // 2 self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1]) def query(self, l: int, r: int) -> T | None: l, r = l + self.N, r + self.N res: T | None = None while l <= r: if l % 2 == 1: res = self.st[l] if res is None else self.fn(res, self.st[l]) if r % 2 == 0: res = self.st[r] if res is None else self.fn(res, self.st[r]) l, r = (l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce test_array = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12] test_updates = { 0: 7, 1: 2, 2: 6, 3: -14, 4: 5, 5: 4, 6: 7, 7: -10, 8: 9, 9: 10, 10: 12, 11: 1, } min_segment_tree = SegmentTree(test_array, min) max_segment_tree = SegmentTree(test_array, max) sum_segment_tree = SegmentTree(test_array, lambda a, b: a + b) def test_all_segments() -> None: for i in range(len(test_array)): for j in range(i, len(test_array)): min_range = reduce(min, test_array[i : j + 1]) max_range = reduce(max, test_array[i : j + 1]) sum_range = reduce(lambda a, b: a + b, test_array[i : j + 1]) assert min_range == min_segment_tree.query(i, j) assert max_range == max_segment_tree.query(i, j) assert sum_range == sum_segment_tree.query(i, j) test_all_segments() for index, value in test_updates.items(): test_array[index] = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
hey we are going to find an exciting number called catalan number which is use to find the number of possible binary search trees from tree of a given number of nodes we will use the formula tn summationi 1 to nti1tni further details at wikipedia https en wikipedia orgwikicatalannumber our contribution basically we create the 2 function 1 catalannumbernodecount int int returns the number of possible binary search trees for n nodes 2 binarytreecountnodecount int int returns the number of possible binary trees for n nodes since here we find the binomial coefficient https en wikipedia orgwikibinomialcoefficient cn k n k nk param n 2 times of number of nodes param k number of nodes return integer value binomialcoefficient4 2 6 since cn k cn nk calculate cn k we can find catalan number many ways but here we use binomial coefficient because it does the job in on return the catalan number of n using 2ncnn1 param n number of nodes return catalan number of n nodes catalannumber5 42 catalannumber6 132 return the factorial of a number param n number to find the factorial of return factorial of n import math allfactoriali math factoriali for i in range10 true factorial5 doctest ellipsis traceback most recent call last valueerror factorial not defined for negative values return the number of possible of binary trees param n number of nodes return number of possible binary trees binarytreecount5 5040 binarytreecount6 95040 our contribution basically we create the 2 function 1 catalan_number node_count int int returns the number of possible binary search trees for n nodes 2 binary_tree_count node_count int int returns the number of possible binary trees for n nodes since here we find the binomial coefficient https en wikipedia org wiki binomial_coefficient c n k n k n k param n 2 times of number of nodes param k number of nodes return integer value binomial_coefficient 4 2 6 to kept the calculated value since c n k c n n k calculate c n k we can find catalan number many ways but here we use binomial coefficient because it does the job in o n return the catalan number of n using 2ncn n 1 param n number of nodes return catalan number of n nodes catalan_number 5 42 catalan_number 6 132 return the factorial of a number param n number to find the factorial of return factorial of n import math all factorial i math factorial i for i in range 10 true factorial 5 doctest ellipsis traceback most recent call last valueerror factorial not defined for negative values return the number of possible of binary trees param n number of nodes return number of possible binary trees binary_tree_count 5 5040 binary_tree_count 6 95040
def binomial_coefficient(n: int, k: int) -> int: result = 1 if k > (n - k): k = n - k for i in range(k): result *= n - i result //= i + 1 return result def catalan_number(node_count: int) -> int: return binomial_coefficient(2 * node_count, node_count) // (node_count + 1) def factorial(n: int) -> int: if n < 0: raise ValueError("factorial() not defined for negative values") result = 1 for i in range(1, n + 1): result *= i return result def binary_tree_count(node_count: int) -> int: return catalan_number(node_count) * factorial(node_count) if __name__ == "__main__": node_count = int(input("Enter the number of nodes: ").strip() or 0) if node_count <= 0: raise ValueError("We need some nodes to work with.") print( f"Given {node_count} nodes, there are {binary_tree_count(node_count)} " f"binary trees and {catalan_number(node_count)} binary search trees." )
psfblack true ruff passed a redblack tree which is a selfbalancing bst binary search tree this tree has similar performance to avl trees but the balancing is less strict so it will perform faster for writingdeleting nodes and slower for reading in the average case though because they re both balanced binary search trees both will get the same asymptotic performance to read more about them https en wikipedia orgwikiredblacktree unless otherwise specified all asymptotic runtimes are specified in terms of the size of the tree initialize a new redblack tree node with the given values label the value associated with this node color 0 if black 1 if red parent the parent to this node left this node s left child right this node s right child here are functions which are specific to redblack trees rotate the subtree rooted at this node to the left and returns the new root to this subtree performing one rotation can be done in o1 rotate the subtree rooted at this node to the right and returns the new root to this subtree performing one rotation can be done in o1 inserts label into the subtree rooted at self performs any rotations necessary to maintain balance and then returns the new root to this subtree likely self this is guaranteed to run in ologn time only possible with an empty tree repair the coloring from inserting into a tree if self parent is none this node is the root so it just needs to be black self color 0 elif colorself parent 0 if the parent is black then it just needs to be red self color 1 else uncle self parent sibling if coloruncle 0 if self isleft and self parent isright self parent rotateright if self right self right insertrepair elif self isright and self parent isleft self parent rotateleft if self left self left insertrepair elif self isleft if self grandparent self grandparent rotateright self parent color 0 if self parent right self parent right color 1 else if self grandparent self grandparent rotateleft self parent color 0 if self parent left self parent left color 1 else self parent color 0 if uncle and self grandparent uncle color 0 self grandparent color 1 self grandparent insertrepair def removeself label int redblacktree noqa plr0912 it s easier to balance a node with at most one child so we replace this node with the greatest one less than it and remove that this node has at most one nonnone child so we don t need to replace this node is red and its child is black the only way this happens to a node with one child is if both children are none leaves we can just remove this node and call it a day the node is black this node and its child are black the tree is now empty this node is black and its child is red move the child node here and make it black repair the coloring of the tree that may have been messed up if self parent is none or self sibling is none or self parent sibling is none or self grandparent is none return if colorself sibling 1 self sibling color 0 self parent color 1 if self isleft self parent rotateleft else self parent rotateright if colorself parent 0 and colorself sibling 0 and colorself sibling left 0 and colorself sibling right 0 self sibling color 1 self parent removerepair return if colorself parent 1 and colorself sibling 0 and colorself sibling left 0 and colorself sibling right 0 self sibling color 1 self parent color 0 return if self isleft and colorself sibling 0 and colorself sibling right 0 and colorself sibling left 1 self sibling rotateright self sibling color 0 if self sibling right self sibling right color 1 if self isright and colorself sibling 0 and colorself sibling right 1 and colorself sibling left 0 self sibling rotateleft self sibling color 0 if self sibling left self sibling left color 1 if self isleft and colorself sibling 0 and colorself sibling right 1 self parent rotateleft self grandparent color self parent color self parent color 0 self parent sibling color 0 if self isright and colorself sibling 0 and colorself sibling left 1 self parent rotateright self grandparent color self parent color self parent color 0 self parent sibling color 0 def checkcolorpropertiesself bool i assume property 1 to hold because there is nothing that can make the color be anything other than 0 or 1 property 2 if self color the root was red printproperty 2 return false property 3 does not need to be checked because none is assumed to be black and is all the leaves property 4 if not self checkcoloring printproperty 4 return false property 5 if self blackheight is none printproperty 5 return false all properties were met return true def checkcoloringself bool if self color 1 and 1 in colorself left colorself right return false if self left and not self left checkcoloring return false if self right and not self right checkcoloring return false return true def blackheightself int none if self is none or self left is none or self right is none if we re already at a leaf there is no path return 1 left redblacktree blackheightself left right redblacktree blackheightself right if left is none or right is none there are issues with coloring below children nodes return none if left right the two children have unequal depths return none return the black depth of children plus one if this node is black return left 1 self color here are functions which are general to all binary search trees def containsself label int bool return self searchlabel is not none def searchself label int redblacktree none if self label label return self elif self label is not none and label self label if self right is none return none else return self right searchlabel else if self left is none return none else return self left searchlabel def floorself label int int none returns the smallest element in this tree which is at least label this method is guaranteed to run in ologn time returns the largest element in this tree this method is guaranteed to run in ologn time go as far right as possible returns the smallest element in this tree this method is guaranteed to run in ologn time go as far left as possible get the current node s grandparent or none if it doesn t exist if self parent is none return none else return self parent parent property def siblingself redblacktree none returns true iff this node is the left child of its parent if self parent is none return false return self parent left is self parent left is self def isrightself bool return the number of nodes in this tree test if two trees are equal if not isinstanceother redblacktree return notimplemented if self label other label return self left other left and self right other right else return false def colornode redblacktree none int code for testing the various functions of the redblack tree test that the rotateleft and rotateright functions work make a tree to test on tree redblacktree0 tree left redblacktree10 parenttree tree right redblacktree10 parenttree tree left left redblacktree20 parenttree left tree left right redblacktree5 parenttree left tree right left redblacktree5 parenttree right tree right right redblacktree20 parenttree right make the right rotation leftrot redblacktree10 leftrot left redblacktree0 parentleftrot leftrot left left redblacktree10 parentleftrot left leftrot left right redblacktree5 parentleftrot left leftrot left left left redblacktree20 parentleftrot left left leftrot left left right redblacktree5 parentleftrot left left leftrot right redblacktree20 parentleftrot tree tree rotateleft if tree leftrot return false tree tree rotateright tree tree rotateright make the left rotation rightrot redblacktree10 rightrot left redblacktree20 parentrightrot rightrot right redblacktree0 parentrightrot rightrot right left redblacktree5 parentrightrot right rightrot right right redblacktree10 parentrightrot right rightrot right right left redblacktree5 parentrightrot right right rightrot right right right redblacktree20 parentrightrot right right if tree rightrot return false return true def testinsertionspeed bool tree redblacktree1 for i in range300000 tree tree inserti return true def testinsert bool tree redblacktree0 tree insert8 tree insert8 tree insert4 tree insert12 tree insert10 tree insert11 ans redblacktree0 0 ans left redblacktree8 0 ans ans right redblacktree8 1 ans ans right left redblacktree4 0 ans right ans right right redblacktree11 0 ans right ans right right left redblacktree10 1 ans right right ans right right right redblacktree12 1 ans right right return tree ans def testinsertandsearch bool found something not in there didn t find something in there test the insert and delete method of the tree verifying the insertion and removal of elements and the balancing of the tree tests the floor and ceiling functions in the tree tree redblacktree0 tree insert16 tree insert16 tree insert8 tree insert24 tree insert20 tree insert22 tuples 20 none 16 10 16 0 8 8 8 50 24 none for val floor ceil in tuples if tree floorval floor or tree ceilval ceil return false return true def testminmax bool tests the three different tree traversal functions tree redblacktree0 tree tree insert16 tree insert16 tree insert8 tree insert24 tree insert20 tree insert22 if listtree inordertraverse 16 0 8 16 20 22 24 return false if listtree preordertraverse 0 16 16 8 22 20 24 return false if listtree postordertraverse 16 8 20 24 22 16 0 return false return true def testtreechaining bool pytests a red black tree which is a self balancing bst binary search tree this tree has similar performance to avl trees but the balancing is less strict so it will perform faster for writing deleting nodes and slower for reading in the average case though because they re both balanced binary search trees both will get the same asymptotic performance to read more about them https en wikipedia org wiki red black_tree unless otherwise specified all asymptotic runtimes are specified in terms of the size of the tree initialize a new red black tree node with the given values label the value associated with this node color 0 if black 1 if red parent the parent to this node left this node s left child right this node s right child here are functions which are specific to red black trees rotate the subtree rooted at this node to the left and returns the new root to this subtree performing one rotation can be done in o 1 rotate the subtree rooted at this node to the right and returns the new root to this subtree performing one rotation can be done in o 1 inserts label into the subtree rooted at self performs any rotations necessary to maintain balance and then returns the new root to this subtree likely self this is guaranteed to run in o log n time only possible with an empty tree repair the coloring from inserting into a tree this node is the root so it just needs to be black if the parent is black then it just needs to be red noqa plr0912 remove label from this tree it s easier to balance a node with at most one child so we replace this node with the greatest one less than it and remove that this node has at most one non none child so we don t need to replace this node is red and its child is black the only way this happens to a node with one child is if both children are none leaves we can just remove this node and call it a day the node is black this node and its child are black the tree is now empty this node is black and its child is red move the child node here and make it black repair the coloring of the tree that may have been messed up check the coloring of the tree and return true iff the tree is colored in a way which matches these five properties wording stolen from wikipedia article 1 each node is either red or black 2 the root node is black 3 all leaves are black 4 if a node is red then both its children are black 5 every path from any node to all of its descendent nil nodes has the same number of black nodes this function runs in o n time because properties 4 and 5 take that long to check i assume property 1 to hold because there is nothing that can make the color be anything other than 0 or 1 property 2 the root was red property 3 does not need to be checked because none is assumed to be black and is all the leaves property 4 property 5 all properties were met a helper function to recursively check property 4 of a red black tree see check_color_properties for more info returns the number of black nodes from this node to the leaves of the tree or none if there isn t one such value the tree is color incorrectly if we re already at a leaf there is no path there are issues with coloring below children nodes the two children have unequal depths return the black depth of children plus one if this node is black here are functions which are general to all binary search trees search through the tree for label returning true iff it is found somewhere in the tree guaranteed to run in o log n time search through the tree for label returning its node if it s found and none otherwise this method is guaranteed to run in o log n time returns the largest element in this tree which is at most label this method is guaranteed to run in o log n time returns the smallest element in this tree which is at least label this method is guaranteed to run in o log n time returns the largest element in this tree this method is guaranteed to run in o log n time go as far right as possible returns the smallest element in this tree this method is guaranteed to run in o log n time go as far left as possible get the current node s grandparent or none if it doesn t exist get the current node s sibling or none if it doesn t exist returns true iff this node is the left child of its parent returns true iff this node is the right child of its parent return the number of nodes in this tree test if two trees are equal returns the color of a node allowing for none leaves code for testing the various functions of the red black tree test that the rotate_left and rotate_right functions work make a tree to test on make the right rotation make the left rotation test that the tree balances inserts to o log n by doing a lot of them test the insert method of the tree correctly balances colors and inserts tests searching through the tree for values found something not in there didn t find something in there test the insert and delete method of the tree verifying the insertion and removal of elements and the balancing of the tree tests the floor and ceiling functions in the tree tests the min and max functions in the tree tests the three different tree traversal functions tests the three different tree chaining functions pytests
from __future__ import annotations from collections.abc import Iterator class RedBlackTree: def __init__( self, label: int | None = None, color: int = 0, parent: RedBlackTree | None = None, left: RedBlackTree | None = None, right: RedBlackTree | None = None, ) -> None: self.label = label self.parent = parent self.left = left self.right = right self.color = color def rotate_left(self) -> RedBlackTree: parent = self.parent right = self.right if right is None: return self self.right = right.left if self.right: self.right.parent = self self.parent = right right.left = self if parent is not None: if parent.left == self: parent.left = right else: parent.right = right right.parent = parent return right def rotate_right(self) -> RedBlackTree: if self.left is None: return self parent = self.parent left = self.left self.left = left.right if self.left: self.left.parent = self self.parent = left left.right = self if parent is not None: if parent.right is self: parent.right = left else: parent.left = left left.parent = parent return left def insert(self, label: int) -> RedBlackTree: if self.label is None: self.label = label return self if self.label == label: return self elif self.label > label: if self.left: self.left.insert(label) else: self.left = RedBlackTree(label, 1, self) self.left._insert_repair() else: if self.right: self.right.insert(label) else: self.right = RedBlackTree(label, 1, self) self.right._insert_repair() return self.parent or self def _insert_repair(self) -> None: if self.parent is None: self.color = 0 elif color(self.parent) == 0: self.color = 1 else: uncle = self.parent.sibling if color(uncle) == 0: if self.is_left() and self.parent.is_right(): self.parent.rotate_right() if self.right: self.right._insert_repair() elif self.is_right() and self.parent.is_left(): self.parent.rotate_left() if self.left: self.left._insert_repair() elif self.is_left(): if self.grandparent: self.grandparent.rotate_right() self.parent.color = 0 if self.parent.right: self.parent.right.color = 1 else: if self.grandparent: self.grandparent.rotate_left() self.parent.color = 0 if self.parent.left: self.parent.left.color = 1 else: self.parent.color = 0 if uncle and self.grandparent: uncle.color = 0 self.grandparent.color = 1 self.grandparent._insert_repair() def remove(self, label: int) -> RedBlackTree: if self.label == label: if self.left and self.right: value = self.left.get_max() if value is not None: self.label = value self.left.remove(value) else: child = self.left or self.right if self.color == 1: if self.parent: if self.is_left(): self.parent.left = None else: self.parent.right = None else: if child is None: if self.parent is None: return RedBlackTree(None) else: self._remove_repair() if self.is_left(): self.parent.left = None else: self.parent.right = None self.parent = None else: self.label = child.label self.left = child.left self.right = child.right if self.left: self.left.parent = self if self.right: self.right.parent = self elif self.label is not None and self.label > label: if self.left: self.left.remove(label) else: if self.right: self.right.remove(label) return self.parent or self def _remove_repair(self) -> None: if ( self.parent is None or self.sibling is None or self.parent.sibling is None or self.grandparent is None ): return if color(self.sibling) == 1: self.sibling.color = 0 self.parent.color = 1 if self.is_left(): self.parent.rotate_left() else: self.parent.rotate_right() if ( color(self.parent) == 0 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent._remove_repair() return if ( color(self.parent) == 1 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent.color = 0 return if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 0 and color(self.sibling.left) == 1 ): self.sibling.rotate_right() self.sibling.color = 0 if self.sibling.right: self.sibling.right.color = 1 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.right) == 1 and color(self.sibling.left) == 0 ): self.sibling.rotate_left() self.sibling.color = 0 if self.sibling.left: self.sibling.left.color = 1 if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 1 ): self.parent.rotate_left() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.left) == 1 ): self.parent.rotate_right() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 def check_color_properties(self) -> bool: if self.color: print("Property 2") return False if not self.check_coloring(): print("Property 4") return False if self.black_height() is None: print("Property 5") return False return True def check_coloring(self) -> bool: if self.color == 1 and 1 in (color(self.left), color(self.right)): return False if self.left and not self.left.check_coloring(): return False if self.right and not self.right.check_coloring(): return False return True def black_height(self) -> int | None: if self is None or self.left is None or self.right is None: return 1 left = RedBlackTree.black_height(self.left) right = RedBlackTree.black_height(self.right) if left is None or right is None: return None if left != right: return None return left + (1 - self.color) def __contains__(self, label: int) -> bool: return self.search(label) is not None def search(self, label: int) -> RedBlackTree | None: if self.label == label: return self elif self.label is not None and label > self.label: if self.right is None: return None else: return self.right.search(label) else: if self.left is None: return None else: return self.left.search(label) def floor(self, label: int) -> int | None: if self.label == label: return self.label elif self.label is not None and self.label > label: if self.left: return self.left.floor(label) else: return None else: if self.right: attempt = self.right.floor(label) if attempt is not None: return attempt return self.label def ceil(self, label: int) -> int | None: if self.label == label: return self.label elif self.label is not None and self.label < label: if self.right: return self.right.ceil(label) else: return None else: if self.left: attempt = self.left.ceil(label) if attempt is not None: return attempt return self.label def get_max(self) -> int | None: if self.right: return self.right.get_max() else: return self.label def get_min(self) -> int | None: if self.left: return self.left.get_min() else: return self.label @property def grandparent(self) -> RedBlackTree | None: if self.parent is None: return None else: return self.parent.parent @property def sibling(self) -> RedBlackTree | None: if self.parent is None: return None elif self.parent.left is self: return self.parent.right else: return self.parent.left def is_left(self) -> bool: if self.parent is None: return False return self.parent.left is self.parent.left is self def is_right(self) -> bool: if self.parent is None: return False return self.parent.right is self def __bool__(self) -> bool: return True def __len__(self) -> int: ln = 1 if self.left: ln += len(self.left) if self.right: ln += len(self.right) return ln def preorder_traverse(self) -> Iterator[int | None]: yield self.label if self.left: yield from self.left.preorder_traverse() if self.right: yield from self.right.preorder_traverse() def inorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.inorder_traverse() yield self.label if self.right: yield from self.right.inorder_traverse() def postorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.postorder_traverse() if self.right: yield from self.right.postorder_traverse() yield self.label def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.label} {(self.color and 'red') or 'blk'}'" return pformat( { f"{self.label} {(self.color and 'red') or 'blk'}": ( self.left, self.right, ) }, indent=1, ) def __eq__(self, other: object) -> bool: if not isinstance(other, RedBlackTree): return NotImplemented if self.label == other.label: return self.left == other.left and self.right == other.right else: return False def color(node: RedBlackTree | None) -> int: if node is None: return 0 else: return node.color def test_rotations() -> bool: tree = RedBlackTree(0) tree.left = RedBlackTree(-10, parent=tree) tree.right = RedBlackTree(10, parent=tree) tree.left.left = RedBlackTree(-20, parent=tree.left) tree.left.right = RedBlackTree(-5, parent=tree.left) tree.right.left = RedBlackTree(5, parent=tree.right) tree.right.right = RedBlackTree(20, parent=tree.right) left_rot = RedBlackTree(10) left_rot.left = RedBlackTree(0, parent=left_rot) left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) left_rot.left.right = RedBlackTree(5, parent=left_rot.left) left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) left_rot.right = RedBlackTree(20, parent=left_rot) tree = tree.rotate_left() if tree != left_rot: return False tree = tree.rotate_right() tree = tree.rotate_right() right_rot = RedBlackTree(-10) right_rot.left = RedBlackTree(-20, parent=right_rot) right_rot.right = RedBlackTree(0, parent=right_rot) right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) right_rot.right.right = RedBlackTree(10, parent=right_rot.right) right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) if tree != right_rot: return False return True def test_insertion_speed() -> bool: tree = RedBlackTree(-1) for i in range(300000): tree = tree.insert(i) return True def test_insert() -> bool: tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) ans = RedBlackTree(0, 0) ans.left = RedBlackTree(-8, 0, ans) ans.right = RedBlackTree(8, 1, ans) ans.right.left = RedBlackTree(4, 0, ans.right) ans.right.right = RedBlackTree(11, 0, ans.right) ans.right.right.left = RedBlackTree(10, 1, ans.right.right) ans.right.right.right = RedBlackTree(12, 1, ans.right.right) return tree == ans def test_insert_and_search() -> bool: tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) if 5 in tree or -6 in tree or -10 in tree or 13 in tree: return False if not (11 in tree and 12 in tree and -8 in tree and 0 in tree): return False return True def test_insert_delete() -> bool: tree = RedBlackTree(0) tree = tree.insert(-12) tree = tree.insert(8) tree = tree.insert(-8) tree = tree.insert(15) tree = tree.insert(4) tree = tree.insert(12) tree = tree.insert(10) tree = tree.insert(9) tree = tree.insert(11) tree = tree.remove(15) tree = tree.remove(-12) tree = tree.remove(9) if not tree.check_color_properties(): return False if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]: return False return True def test_floor_ceil() -> bool: tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] for val, floor, ceil in tuples: if tree.floor(val) != floor or tree.ceil(val) != ceil: return False return True def test_min_max() -> bool: tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if tree.get_max() != 22 or tree.get_min() != -16: return False return True def test_tree_traversal() -> bool: tree = RedBlackTree(0) tree = tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def test_tree_chaining() -> bool: tree = RedBlackTree(0) tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_rotations() assert test_insert() assert test_insert_and_search() assert test_insert_delete() assert test_floor_ceil() assert test_tree_traversal() assert test_tree_chaining() def main() -> None: print_results("Rotating right and left", test_rotations()) print_results("Inserting", test_insert()) print_results("Searching", test_insert_and_search()) print_results("Deleting", test_insert_delete()) print_results("Floor and ceil", test_floor_ceil()) print_results("Tree traversal", test_tree_traversal()) print_results("Tree traversal", test_tree_chaining()) print("Testing tree balancing...") print("This should only be a few seconds.") test_insertion_speed() print("Done!") if __name__ == "__main__": main()
returns the left child index for a given index in a binary tree s segmenttree1 2 3 s left1 2 s left2 4 returns the right child index for a given index in a binary tree s segmenttree1 2 3 s right1 3 s right2 5 update the values in the segment tree in the range a b with the given value s segmenttree1 2 3 4 5 s update2 4 10 true s query1 5 10 update1 1 n a b v for update val v to a b query the maximum value in the range a b s segmenttree1 2 3 4 5 s query1 3 3 s query1 5 5 query1 1 n a b for query max of a b approximate the overall size of segment tree with array n returns the left child index for a given index in a binary tree s segmenttree 1 2 3 s left 1 2 s left 2 4 returns the right child index for a given index in a binary tree s segmenttree 1 2 3 s right 1 3 s right 2 5 noqa e741 update the values in the segment tree in the range a b with the given value s segmenttree 1 2 3 4 5 s update 2 4 10 true s query 1 5 10 noqa e741 update 1 1 n a b v for update val v to a b query the maximum value in the range a b s segmenttree 1 2 3 4 5 s query 1 3 3 s query 1 5 5 noqa e741 query 1 1 n a b for query max of a b
import math class SegmentTree: def __init__(self, a): self.A = a self.N = len(self.A) self.st = [0] * ( 4 * self.N ) if self.N: self.build(1, 0, self.N - 1) def left(self, idx): return idx * 2 def right(self, idx): return idx * 2 + 1 def build(self, idx, l, r): if l == r: self.st[idx] = self.A[l] else: mid = (l + r) // 2 self.build(self.left(idx), l, mid) self.build(self.right(idx), mid + 1, r) self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)]) def update(self, a, b, val): return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val) def update_recursive(self, idx, l, r, a, b, val): if r < a or l > b: return True if l == r: self.st[idx] = val return True mid = (l + r) // 2 self.update_recursive(self.left(idx), l, mid, a, b, val) self.update_recursive(self.right(idx), mid + 1, r, a, b, val) self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)]) return True def query(self, a, b): return self.query_recursive(1, 0, self.N - 1, a - 1, b - 1) def query_recursive(self, idx, l, r, a, b): if r < a or l > b: return -math.inf if l >= a and r <= b: return self.st[idx] mid = (l + r) // 2 q1 = self.query_recursive(self.left(idx), l, mid, a, b) q2 = self.query_recursive(self.right(idx), mid + 1, r, a, b) return max(q1, q2) def show_data(self): show_list = [] for i in range(1, N + 1): show_list += [self.query(i, i)] print(show_list) if __name__ == "__main__": A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] N = 15 segt = SegmentTree(A) print(segt.query(4, 6)) print(segt.query(7, 11)) print(segt.query(7, 12)) segt.update(1, 3, 111) print(segt.query(1, 15)) segt.update(7, 8, 235) segt.show_data()
segmenttree creates a segment tree with a given array and function allowing queries to be done later in logn time function takes 2 values and returns a same type value import operator numarr segmenttree2 1 5 3 4 operator add tuplenumarr traverse doctest normalizewhitespace segmenttreenodestart0 end4 val15 segmenttreenodestart0 end2 val8 segmenttreenodestart3 end4 val7 segmenttreenodestart0 end1 val3 segmenttreenodestart2 end2 val5 segmenttreenodestart3 end3 val3 segmenttreenodestart4 end4 val4 segmenttreenodestart0 end0 val2 segmenttreenodestart1 end1 val1 numarr update1 5 tuplenumarr traverse doctest normalizewhitespace segmenttreenodestart0 end4 val19 segmenttreenodestart0 end2 val12 segmenttreenodestart3 end4 val7 segmenttreenodestart0 end1 val7 segmenttreenodestart2 end2 val5 segmenttreenodestart3 end3 val3 segmenttreenodestart4 end4 val4 segmenttreenodestart0 end0 val2 segmenttreenodestart1 end1 val5 numarr queryrange3 4 7 numarr queryrange2 2 5 numarr queryrange1 3 13 maxarr segmenttree2 1 5 3 4 max for node in maxarr traverse printnode segmenttreenodestart0 end4 val5 segmenttreenodestart0 end2 val5 segmenttreenodestart3 end4 val4 segmenttreenodestart0 end1 val2 segmenttreenodestart2 end2 val5 segmenttreenodestart3 end3 val3 segmenttreenodestart4 end4 val4 segmenttreenodestart0 end0 val2 segmenttreenodestart1 end1 val1 maxarr update1 5 for node in maxarr traverse printnode segmenttreenodestart0 end4 val5 segmenttreenodestart0 end2 val5 segmenttreenodestart3 end4 val4 segmenttreenodestart0 end1 val5 segmenttreenodestart2 end2 val5 segmenttreenodestart3 end3 val3 segmenttreenodestart4 end4 val4 segmenttreenodestart0 end0 val2 segmenttreenodestart1 end1 val5 maxarr queryrange3 4 4 maxarr queryrange2 2 5 maxarr queryrange1 3 5 minarr segmenttree2 1 5 3 4 min for node in minarr traverse printnode segmenttreenodestart0 end4 val1 segmenttreenodestart0 end2 val1 segmenttreenodestart3 end4 val3 segmenttreenodestart0 end1 val1 segmenttreenodestart2 end2 val5 segmenttreenodestart3 end3 val3 segmenttreenodestart4 end4 val4 segmenttreenodestart0 end0 val2 segmenttreenodestart1 end1 val1 minarr update1 5 for node in minarr traverse printnode segmenttreenodestart0 end4 val2 segmenttreenodestart0 end2 val2 segmenttreenodestart3 end4 val3 segmenttreenodestart0 end1 val2 segmenttreenodestart2 end2 val5 segmenttreenodestart3 end3 val3 segmenttreenodestart4 end4 val4 segmenttreenodestart0 end0 val2 segmenttreenodestart1 end1 val5 minarr queryrange3 4 3 minarr queryrange2 2 5 minarr queryrange1 3 3 update an element in logn time param i position to be update param val new value import operator numarr segmenttree2 1 5 3 4 operator add numarr update1 5 numarr queryrange1 3 13 get range query value in logn time param i left element index param j right element index return element combined in the range i j import operator numarr segmenttree2 1 5 3 4 operator add numarr update1 5 numarr queryrange3 4 7 numarr queryrange2 2 5 numarr queryrange1 3 13 range in left child tree range in left child tree and right child tree range in right child tree import operator num_arr segmenttree 2 1 5 3 4 operator add tuple num_arr traverse doctest normalize_whitespace segmenttreenode start 0 end 4 val 15 segmenttreenode start 0 end 2 val 8 segmenttreenode start 3 end 4 val 7 segmenttreenode start 0 end 1 val 3 segmenttreenode start 2 end 2 val 5 segmenttreenode start 3 end 3 val 3 segmenttreenode start 4 end 4 val 4 segmenttreenode start 0 end 0 val 2 segmenttreenode start 1 end 1 val 1 num_arr update 1 5 tuple num_arr traverse doctest normalize_whitespace segmenttreenode start 0 end 4 val 19 segmenttreenode start 0 end 2 val 12 segmenttreenode start 3 end 4 val 7 segmenttreenode start 0 end 1 val 7 segmenttreenode start 2 end 2 val 5 segmenttreenode start 3 end 3 val 3 segmenttreenode start 4 end 4 val 4 segmenttreenode start 0 end 0 val 2 segmenttreenode start 1 end 1 val 5 num_arr query_range 3 4 7 num_arr query_range 2 2 5 num_arr query_range 1 3 13 max_arr segmenttree 2 1 5 3 4 max for node in max_arr traverse print node segmenttreenode start 0 end 4 val 5 segmenttreenode start 0 end 2 val 5 segmenttreenode start 3 end 4 val 4 segmenttreenode start 0 end 1 val 2 segmenttreenode start 2 end 2 val 5 segmenttreenode start 3 end 3 val 3 segmenttreenode start 4 end 4 val 4 segmenttreenode start 0 end 0 val 2 segmenttreenode start 1 end 1 val 1 max_arr update 1 5 for node in max_arr traverse print node segmenttreenode start 0 end 4 val 5 segmenttreenode start 0 end 2 val 5 segmenttreenode start 3 end 4 val 4 segmenttreenode start 0 end 1 val 5 segmenttreenode start 2 end 2 val 5 segmenttreenode start 3 end 3 val 3 segmenttreenode start 4 end 4 val 4 segmenttreenode start 0 end 0 val 2 segmenttreenode start 1 end 1 val 5 max_arr query_range 3 4 4 max_arr query_range 2 2 5 max_arr query_range 1 3 5 min_arr segmenttree 2 1 5 3 4 min for node in min_arr traverse print node segmenttreenode start 0 end 4 val 1 segmenttreenode start 0 end 2 val 1 segmenttreenode start 3 end 4 val 3 segmenttreenode start 0 end 1 val 1 segmenttreenode start 2 end 2 val 5 segmenttreenode start 3 end 3 val 3 segmenttreenode start 4 end 4 val 4 segmenttreenode start 0 end 0 val 2 segmenttreenode start 1 end 1 val 1 min_arr update 1 5 for node in min_arr traverse print node segmenttreenode start 0 end 4 val 2 segmenttreenode start 0 end 2 val 2 segmenttreenode start 3 end 4 val 3 segmenttreenode start 0 end 1 val 2 segmenttreenode start 2 end 2 val 5 segmenttreenode start 3 end 3 val 3 segmenttreenode start 4 end 4 val 4 segmenttreenode start 0 end 0 val 2 segmenttreenode start 1 end 1 val 5 min_arr query_range 3 4 3 min_arr query_range 2 2 5 min_arr query_range 1 3 3 update an element in log n time param i position to be update param val new value import operator num_arr segmenttree 2 1 5 3 4 operator add num_arr update 1 5 num_arr query_range 1 3 13 get range query value in log n time param i left element index param j right element index return element combined in the range i j import operator num_arr segmenttree 2 1 5 3 4 operator add num_arr update 1 5 num_arr query_range 3 4 7 num_arr query_range 2 2 5 num_arr query_range 1 3 13 range in left child tree range in left child tree and right child tree range in right child tree 7 5 13
from collections.abc import Sequence from queue import Queue class SegmentTreeNode: def __init__(self, start, end, val, left=None, right=None): self.start = start self.end = end self.val = val self.mid = (start + end) // 2 self.left = left self.right = right def __repr__(self): return f"SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})" class SegmentTree: def __init__(self, collection: Sequence, function): self.collection = collection self.fn = function if self.collection: self.root = self._build_tree(0, len(collection) - 1) def update(self, i, val): self._update_tree(self.root, i, val) def query_range(self, i, j): return self._query_range(self.root, i, j) def _build_tree(self, start, end): if start == end: return SegmentTreeNode(start, end, self.collection[start]) mid = (start + end) // 2 left = self._build_tree(start, mid) right = self._build_tree(mid + 1, end) return SegmentTreeNode(start, end, self.fn(left.val, right.val), left, right) def _update_tree(self, node, i, val): if node.start == i and node.end == i: node.val = val return if i <= node.mid: self._update_tree(node.left, i, val) else: self._update_tree(node.right, i, val) node.val = self.fn(node.left.val, node.right.val) def _query_range(self, node, i, j): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: return self._query_range(node.left, i, j) else: return self.fn( self._query_range(node.left, i, node.mid), self._query_range(node.right, node.mid + 1, j), ) else: return self._query_range(node.right, i, j) def traverse(self): if self.root is not None: queue = Queue() queue.put(self.root) while not queue.empty(): node = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 50) arr = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) print(arr.query_range(2, 2)) print(arr.query_range(1, 3)) print()
a binary tree node has a value left child and right child props value the value of the node left the left child of the node right the right child of the node iterate through the tree in preorder returns an iterator of the tree nodes listtreenode1 1 null null tupletreenode1 treenode2 treenode3 1 2 null null 3 null null 2 null null 3 null null count the number of nodes in the tree returns the number of nodes in the tree lentreenode1 1 lentreenode1 treenode2 treenode3 3 represent the tree as a string returns a string representation of the tree reprtreenode1 1 null null reprtreenode1 treenode2 treenode3 1 2 null null 3 null null reprtreenode1 treenode2 treenode3 treenode4 treenode5 1 2 null null 3 4 null null 5 null null reprtreenode fivetree 1 2 null null 3 4 null null 5 null null deserialize a string to a binary tree args datastr the serialized string returns the root of the binary tree root treenode fivetree serialzeddata reprroot deserialized deserializeserialzeddata root deserialized true root is deserialized two separate trees false root right right value 6 root deserialized false serialzeddata reprroot deserialized deserializeserialzeddata root deserialized true deserialize traceback most recent call last valueerror data cannot be empty split the serialized string by a comma to get node values get the next value from the list a binary tree node has a value left child and right child props value the value of the node left the left child of the node right the right child of the node iterate through the tree in preorder returns an iterator of the tree nodes list treenode 1 1 null null tuple treenode 1 treenode 2 treenode 3 1 2 null null 3 null null 2 null null 3 null null count the number of nodes in the tree returns the number of nodes in the tree len treenode 1 1 len treenode 1 treenode 2 treenode 3 3 represent the tree as a string returns a string representation of the tree repr treenode 1 1 null null repr treenode 1 treenode 2 treenode 3 1 2 null null 3 null null repr treenode 1 treenode 2 treenode 3 treenode 4 treenode 5 1 2 null null 3 4 null null 5 null null repr treenode five_tree 1 2 null null 3 4 null null 5 null null deserialize a string to a binary tree args data str the serialized string returns the root of the binary tree root treenode five_tree serialzed_data repr root deserialized deserialize serialzed_data root deserialized true root is deserialized two separate trees false root right right value 6 root deserialized false serialzed_data repr root deserialized deserialize serialzed_data root deserialized true deserialize traceback most recent call last valueerror data cannot be empty split the serialized string by a comma to get node values get the next value from the list recursively build left subtree recursively build right subtree
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass @dataclass class TreeNode: value: int = 0 left: TreeNode | None = None right: TreeNode | None = None def __post_init__(self): if not isinstance(self.value, int): raise TypeError("Value must be an integer.") def __iter__(self) -> Iterator[TreeNode]: yield self yield from self.left or () yield from self.right or () def __len__(self) -> int: return sum(1 for _ in self) def __repr__(self) -> str: return f"{self.value},{self.left!r},{self.right!r}".replace("None", "null") @classmethod def five_tree(cls) -> TreeNode: root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.right.left = TreeNode(4) root.right.right = TreeNode(5) return root def deserialize(data: str) -> TreeNode | None: if not data: raise ValueError("Data cannot be empty.") nodes = data.split(",") def build_tree() -> TreeNode | None: value = nodes.pop(0) if value == "null": return None node = TreeNode(int(value)) node.left = build_tree() node.right = build_tree() return node return build_tree() if __name__ == "__main__": import doctest doctest.testmod()
given the root of a binary tree check whether it is a mirror of itself i e symmetric around its center leetcode reference https leetcode comproblemssymmetrictree a node has data variable and pointers to nodes to its left and right root node1 root left node2 root right node2 root left left node3 root left right node4 root right left node4 root right right node3 return root def makeasymmetrictree node r create a asymmetric tree for testing the tree looks like this 1 2 2 3 4 3 4 test cases for issymmetrictree function issymmetrictreemakesymmetrictree true issymmetrictreemakeasymmetrictree false tree1 makesymmetrictree tree1 right right node3 ismirrortree1 left tree1 right true tree2 makeasymmetrictree ismirrortree2 left tree2 right false both sides are empty which is symmetric one side is empty while the other is not which is not symmetric the values match so check the subtree a node has data variable and pointers to nodes to its left and right create a symmetric tree for testing the tree looks like this 1 2 2 3 4 4 3 create a asymmetric tree for testing the tree looks like this 1 2 2 3 4 3 4 test cases for is_symmetric_tree function is_symmetric_tree make_symmetric_tree true is_symmetric_tree make_asymmetric_tree false an empty tree is considered symmetric tree1 make_symmetric_tree tree1 right right node 3 is_mirror tree1 left tree1 right true tree2 make_asymmetric_tree is_mirror tree2 left tree2 right false both sides are empty which is symmetric one side is empty while the other is not which is not symmetric the values match so check the subtree
from __future__ import annotations from dataclasses import dataclass @dataclass class Node: data: int left: Node | None = None right: Node | None = None def make_symmetric_tree() -> Node: r root = Node(1) root.left = Node(2) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right.left = Node(4) root.right.right = Node(3) return root def make_asymmetric_tree() -> Node: r root = Node(1) root.left = Node(2) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right.left = Node(3) root.right.right = Node(4) return root def is_symmetric_tree(tree: Node) -> bool: if tree: return is_mirror(tree.left, tree.right) return True def is_mirror(left: Node | None, right: Node | None) -> bool: if left is None and right is None: return True if left is None or right is None: return False if left.data == right.data: return is_mirror(left.left, right.right) and is_mirror(left.right, right.left) return False if __name__ == "__main__": from doctest import testmod testmod()
treap s node treap is a binary tree by value and heap by priority we split current tree into 2 trees with value left tree contains all values less than split value right tree contains all values greater or equal than split value right tree s root will be current node now we splitwith the same value current node s left son left tree left part of that split right tree s left son right part of that split just symmetric to previous case we merge 2 trees into one note all left tree s values must be less than all right tree s left will be root because it has more priority now we need to merge left s right son and right tree symmetric as well insert element split current tree with a value into left right insert new node into the middle merge left node right into root erase element split all nodes with values less into left split all nodes with values greater into right merge left right just recursive print of a tree commands value to add value into treap value to erase all nodes with value root interacttreapnone 1 inorderroot 1 root interacttreaproot 3 5 17 19 2 16 4 0 inorderroot 0 1 2 3 4 5 16 17 19 root interacttreaproot 4 4 4 inorderroot 0 1 2 3 4 4 4 4 5 16 17 19 root interacttreaproot 0 inorderroot 1 2 3 4 4 4 4 5 16 17 19 root interacttreaproot 4 inorderroot 1 2 3 5 16 17 19 root interacttreaproot 0 unknown command after each command program prints treap root none print enter numbers to create a tree value to add value into treap value to erase all nodes with value q to quit args input while args q root interacttreaproot args printroot args input printgood by if name main import doctest doctest testmod main treap s node treap is a binary tree by value and heap by priority we split current tree into 2 trees with value left tree contains all values less than split value right tree contains all values greater or equal than split value none tree is split into 2 nones right tree s root will be current node now we split with the same value current node s left son left tree left part of that split right tree s left son right part of that split just symmetric to previous case we merge 2 trees into one note all left tree s values must be less than all right tree s if one node is none return the other left will be root because it has more priority now we need to merge left s right son and right tree symmetric as well insert element split current tree with a value into left right insert new node into the middle merge left node right into root erase element split all nodes with values less into left split all nodes with values greater into right merge left right just recursive print of a tree none commands value to add value into treap value to erase all nodes with value root interact_treap none 1 inorder root 1 root interact_treap root 3 5 17 19 2 16 4 0 inorder root 0 1 2 3 4 5 16 17 19 root interact_treap root 4 4 4 inorder root 0 1 2 3 4 4 4 4 5 16 17 19 root interact_treap root 0 inorder root 1 2 3 4 4 4 4 5 16 17 19 root interact_treap root 4 inorder root 1 2 3 5 16 17 19 root interact_treap root 0 unknown command after each command program prints treap
from __future__ import annotations from random import random class Node: def __init__(self, value: int | None = None): self.value = value self.prior = random() self.left: Node | None = None self.right: Node | None = None def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.value}: {self.prior:.5}'" else: return pformat( {f"{self.value}: {self.prior:.5}": (self.left, self.right)}, indent=1 ) def __str__(self) -> str: value = str(self.value) + " " left = str(self.left or "") right = str(self.right or "") return value + left + right def split(root: Node | None, value: int) -> tuple[Node | None, Node | None]: if root is None: return None, None elif root.value is None: return None, None else: if value < root.value: left, root.left = split(root.left, value) return left, root else: root.right, right = split(root.right, value) return root, right def merge(left: Node | None, right: Node | None) -> Node | None: if (not left) or (not right): return left or right elif left.prior < right.prior: left.right = merge(left.right, right) return left else: right.left = merge(left, right.left) return right def insert(root: Node | None, value: int) -> Node | None: node = Node(value) left, right = split(root, value) return merge(merge(left, node), right) def erase(root: Node | None, value: int) -> Node | None: left, right = split(root, value - 1) _, right = split(right, value) return merge(left, right) def inorder(root: Node | None) -> None: if not root: return else: inorder(root.left) print(root.value, end=",") inorder(root.right) def interact_treap(root: Node | None, args: str) -> Node | None: for arg in args.split(): if arg[0] == "+": root = insert(root, int(arg[1:])) elif arg[0] == "-": root = erase(root, int(arg[1:])) else: print("Unknown command") return root def main() -> None: root = None print( "enter numbers to create a tree, + value to add value into treap, " "- value to erase all nodes with value. 'q' to quit. " ) args = input() while args != "q": root = interact_treap(root, args) print(root) args = input() print("good by!") if __name__ == "__main__": import doctest doctest.testmod() main()
wavelet tree is a datastructure designed to efficiently answer various range queries for arrays wavelets trees are different from other binary trees in the sense that the nodes are split based on the actual values of the elements and not on indices such as the with segment trees or fenwick trees you can read more about them here 1 https users dcc uchile cljperezpapersioiconf16 pdf 2 https www youtube comwatch v4asv9pcecdwt811s 3 https www youtube comwatch vcybagvfmmct1178s node nodelength27 reprnode nodeminvalue1 maxvalue1 reprnode strnode true builds the tree for arr and returns the root of the constructed tree buildtreetestarray nodeminvalue0 maxvalue9 leaf node case where the node contains only one unique value take the mean of min and max element of arr as the pivot and partition arr into leftarr and rightarr with all elements pivot in the leftarr and the rest in rightarr maintaining the order of the elements then recursively build trees for leftarr and rightarr returns the number of occurrences of num in interval 0 index in the list root buildtreetestarray ranktillindexroot 6 6 1 ranktillindexroot 2 0 1 ranktillindexroot 1 10 2 ranktillindexroot 17 7 0 ranktillindexroot 0 9 1 leaf node cases go the left subtree and map index to the left subtree go to the right subtree and map index to the right subtree returns the number of occurrences of num in interval start end in the list root buildtreetestarray rankroot 6 3 13 2 rankroot 2 0 19 4 rankroot 9 2 2 0 rankroot 0 5 10 2 returns the index th smallest element in interval start end in the list index is 0indexed root buildtreetestarray quantileroot 2 2 5 5 quantileroot 5 2 13 4 quantileroot 0 6 6 8 quantileroot 4 2 5 1 leaf node case number of elements in the left subtree in interval start end returns the number of elements in range startnum endnum in interval start end in the list root buildtreetestarray rangecountingroot 1 10 3 7 3 rangecountingroot 2 2 1 4 1 rangecountingroot 0 19 0 100 20 rangecountingroot 1 0 1 100 0 rangecountingroot 0 17 100 1 0 node node length 27 repr node node min_value 1 max_value 1 repr node str node true builds the tree for arr and returns the root of the constructed tree build_tree test_array node min_value 0 max_value 9 leaf node case where the node contains only one unique value take the mean of min and max element of arr as the pivot and partition arr into left_arr and right_arr with all elements pivot in the left_arr and the rest in right_arr maintaining the order of the elements then recursively build trees for left_arr and right_arr returns the number of occurrences of num in interval 0 index in the list root build_tree test_array rank_till_index root 6 6 1 rank_till_index root 2 0 1 rank_till_index root 1 10 2 rank_till_index root 17 7 0 rank_till_index root 0 9 1 leaf node cases go the left subtree and map index to the left subtree go to the right subtree and map index to the right subtree returns the number of occurrences of num in interval start end in the list root build_tree test_array rank root 6 3 13 2 rank root 2 0 19 4 rank root 9 2 2 0 rank root 0 5 10 2 returns the index th smallest element in interval start end in the list index is 0 indexed root build_tree test_array quantile root 2 2 5 5 quantile root 5 2 13 4 quantile root 0 6 6 8 quantile root 4 2 5 1 leaf node case number of elements in the left subtree in interval start end returns the number of elements in range start_num end_num in interval start end in the list root build_tree test_array range_counting root 1 10 3 7 3 range_counting root 2 2 1 4 1 range_counting root 0 19 0 100 20 range_counting root 1 0 1 100 0 range_counting root 0 17 100 1 0
from __future__ import annotations test_array = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7] class Node: def __init__(self, length: int) -> None: self.minn: int = -1 self.maxx: int = -1 self.map_left: list[int] = [-1] * length self.left: Node | None = None self.right: Node | None = None def __repr__(self) -> str: return f"Node(min_value={self.minn} max_value={self.maxx})" def build_tree(arr: list[int]) -> Node | None: root = Node(len(arr)) root.minn, root.maxx = min(arr), max(arr) if root.minn == root.maxx: return root pivot = (root.minn + root.maxx) // 2 left_arr: list[int] = [] right_arr: list[int] = [] for index, num in enumerate(arr): if num <= pivot: left_arr.append(num) else: right_arr.append(num) root.map_left[index] = len(left_arr) root.left = build_tree(left_arr) root.right = build_tree(right_arr) return root def rank_till_index(node: Node | None, num: int, index: int) -> int: if index < 0 or node is None: return 0 if node.minn == node.maxx: return index + 1 if node.minn == num else 0 pivot = (node.minn + node.maxx) // 2 if num <= pivot: return rank_till_index(node.left, num, node.map_left[index] - 1) else: return rank_till_index(node.right, num, index - node.map_left[index]) def rank(node: Node | None, num: int, start: int, end: int) -> int: if start > end: return 0 rank_till_end = rank_till_index(node, num, end) rank_before_start = rank_till_index(node, num, start - 1) return rank_till_end - rank_before_start def quantile(node: Node | None, index: int, start: int, end: int) -> int: if index > (end - start) or start > end or node is None: return -1 if node.minn == node.maxx: return node.minn num_elements_in_left_tree = node.map_left[end] - ( node.map_left[start - 1] if start else 0 ) if num_elements_in_left_tree > index: return quantile( node.left, index, (node.map_left[start - 1] if start else 0), node.map_left[end] - 1, ) else: return quantile( node.right, index - num_elements_in_left_tree, start - (node.map_left[start - 1] if start else 0), end - node.map_left[end], ) def range_counting( node: Node | None, start: int, end: int, start_num: int, end_num: int ) -> int: if ( start > end or node is None or start_num > end_num or node.minn > end_num or node.maxx < start_num ): return 0 if start_num <= node.minn and node.maxx <= end_num: return end - start + 1 left = range_counting( node.left, (node.map_left[start - 1] if start else 0), node.map_left[end] - 1, start_num, end_num, ) right = range_counting( node.right, start - (node.map_left[start - 1] if start else 0), end - node.map_left[end], start_num, end_num, ) return left + right if __name__ == "__main__": import doctest doctest.testmod()
implements a disjoint set using lists and some added heuristics for efficiency union by rank heuristic and path compression initialize with a list of the number of items in each set and with rank 1 for each set merge two sets together using union by rank heuristic return true if successful merge two disjoint sets a disjointset1 1 1 a merge1 2 true a merge0 2 true a merge0 1 false find the parent of a given set a disjointset1 1 1 a merge1 2 true a getparent0 0 a getparent1 2 initialize with a list of the number of items in each set and with rank 1 for each set merge two sets together using union by rank heuristic return true if successful merge two disjoint sets a disjointset 1 1 1 a merge 1 2 true a merge 0 2 true a merge 0 1 false find the parent of a given set a disjointset 1 1 1 a merge 1 2 true a get_parent 0 0 a get_parent 1 2
class DisjointSet: def __init__(self, set_counts: list) -> None: self.set_counts = set_counts self.max_set = max(set_counts) num_sets = len(set_counts) self.ranks = [1] * num_sets self.parents = list(range(num_sets)) def merge(self, src: int, dst: int) -> bool: src_parent = self.get_parent(src) dst_parent = self.get_parent(dst) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] self.set_counts[src_parent] = 0 self.parents[src_parent] = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 joined_set_size = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] self.set_counts[dst_parent] = 0 self.parents[dst_parent] = src_parent joined_set_size = self.set_counts[src_parent] self.max_set = max(self.max_set, joined_set_size) return True def get_parent(self, disj_set: int) -> int: if self.parents[disj_set] == disj_set: return disj_set self.parents[disj_set] = self.get_parent(self.parents[disj_set]) return self.parents[disj_set]
disjoint set reference https en wikipedia orgwikidisjointsetdatastructure make x as a set rank is the distance from x to its parent root s rank is 0 union of two sets set with bigger rank should be parent so that the disjoint set tree will be more flat return the parent of x return a python standard library set that contains i testdisjointset make x as a set rank is the distance from x to its parent root s rank is 0 union of two sets set with bigger rank should be parent so that the disjoint set tree will be more flat return the parent of x return a python standard library set that contains i test_disjoint_set
class Node: def __init__(self, data: int) -> None: self.data = data self.rank: int self.parent: Node def make_set(x: Node) -> None: x.rank = 0 x.parent = x def union_set(x: Node, y: Node) -> None: x, y = find_set(x), find_set(y) if x == y: return elif x.rank > y.rank: y.parent = x else: x.parent = y if x.rank == y.rank: y.rank += 1 def find_set(x: Node) -> Node: if x != x.parent: x.parent = find_set(x.parent) return x.parent def find_python_set(node: Node) -> set: sets = ({0, 1, 2}, {3, 4, 5}) for s in sets: if node.data in s: return s msg = f"{node.data} is not in {sets}" raise ValueError(msg) def test_disjoint_set() -> None: vertex = [Node(i) for i in range(6)] for v in vertex: make_set(v) union_set(vertex[0], vertex[1]) union_set(vertex[1], vertex[2]) union_set(vertex[3], vertex[4]) union_set(vertex[3], vertex[5]) for node0 in vertex: for node1 in vertex: if find_python_set(node0).isdisjoint(find_python_set(node1)): assert find_set(node0) != find_set(node1) else: assert find_set(node0) == find_set(node1) if __name__ == "__main__": test_disjoint_set()
see https en wikipedia orgwikibloomfilter the use of this data structure is to test membership in a set compared to python s builtin set it is more spaceefficient in the following example only 8 bits of memory will be used bloom bloomsize8 initially the filter contains all zeros bloom bitstring 00000000 when an element is added two bits are set to 1 since there are 2 hash functions in this implementation titanic in bloom false bloom addtitanic bloom bitstring 01100000 titanic in bloom true however sometimes only one bit is added because both hash functions return the same value bloom addavatar avatar in bloom true bloom formathashavatar 00000100 bloom bitstring 01100100 not added elements should return false notpresentfilms the godfather interstellar parasite pulp fiction film bloom formathashfilm for film in notpresentfilms doctest normalizewhitespace the godfather 00000101 interstellar 00000011 parasite 00010010 pulp fiction 10000100 anyfilm in bloom for film in notpresentfilms false but sometimes there are false positives ratatouille in bloom true bloom formathashratatouille 01100000 the probability increases with the number of elements added the probability decreases with the number of bits in the bitarray bloom estimatederrorrate 0 140625 bloom addthe godfather bloom estimatederrorrate 0 25 bloom bitstring 01100101
from hashlib import md5, sha256 HASH_FUNCTIONS = (sha256, md5) class Bloom: def __init__(self, size: int = 8) -> None: self.bitarray = 0b0 self.size = size def add(self, value: str) -> None: h = self.hash_(value) self.bitarray |= h def exists(self, value: str) -> bool: h = self.hash_(value) return (h & self.bitarray) == h def __contains__(self, other: str) -> bool: return self.exists(other) def format_bin(self, bitarray: int) -> str: res = bin(bitarray)[2:] return res.zfill(self.size) @property def bitstring(self) -> str: return self.format_bin(self.bitarray) def hash_(self, value: str) -> int: res = 0b0 for func in HASH_FUNCTIONS: position = ( int.from_bytes(func(value.encode()).digest(), "little") % self.size ) res |= 2**position return res def format_hash(self, value: str) -> str: return self.format_bin(self.hash_(value)) @property def estimated_error_rate(self) -> float: n_ones = bin(self.bitarray).count("1") return (n_ones / self.size) ** len(HASH_FUNCTIONS)
usrbinenv python3 double hashing is a collision resolving technique in open addressed hash tables double hashing uses the idea of applying a second hash function to key when a collision occurs the advantage of double hashing is that it is one of the best form of probing producing a uniform distribution of records throughout a hash table this technique does not yield any clusters it is one of effective method for resolving collisions double hashing can be done using hash1key i hash2key tablesize where hash1 and hash2 are hash functions and tablesize is size of hash table reference https en wikipedia orgwikidoublehashing hash table example with open addressing and double hash examples 1 try to add three data elements when the size is three dh doublehash3 dh insertdata10 dh insertdata20 dh insertdata30 dh keys 1 10 2 20 0 30 2 try to add three data elements when the size is two dh doublehash2 dh insertdata10 dh insertdata20 dh insertdata30 dh keys 10 10 9 20 8 30 3 try to add three data elements when the size is four dh doublehash4 dh insertdata10 dh insertdata20 dh insertdata30 dh keys 9 20 10 10 8 30 usr bin env python3 double hashing is a collision resolving technique in open addressed hash tables double hashing uses the idea of applying a second hash function to key when a collision occurs the advantage of double hashing is that it is one of the best form of probing producing a uniform distribution of records throughout a hash table this technique does not yield any clusters it is one of effective method for resolving collisions double hashing can be done using hash1 key i hash2 key table_size where hash1 and hash2 are hash functions and table_size is size of hash table reference https en wikipedia org wiki double_hashing hash table example with open addressing and double hash gt bigger than examples 1 try to add three data elements when the size is three dh doublehash 3 dh insert_data 10 dh insert_data 20 dh insert_data 30 dh keys 1 10 2 20 0 30 2 try to add three data elements when the size is two dh doublehash 2 dh insert_data 10 dh insert_data 20 dh insert_data 30 dh keys 10 10 9 20 8 30 3 try to add three data elements when the size is four dh doublehash 4 dh insert_data 10 dh insert_data 20 dh insert_data 30 dh keys 9 20 10 10 8 30
from .hash_table import HashTable from .number_theory.prime_numbers import is_prime, next_prime class DoubleHash(HashTable): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __hash_function_2(self, value, data): next_prime_gt = ( next_prime(value % self.size_table) if not is_prime(value % self.size_table) else value % self.size_table ) return next_prime_gt - (data % next_prime_gt) def __hash_double_function(self, key, data, increment): return (increment * self.__hash_function_2(key, data)) % self.size_table def _collision_resolution(self, key, data=None): i = 1 new_key = self.hash_function(data) while self.values[new_key] is not None and self.values[new_key] != key: new_key = ( self.__hash_double_function(key, data, i) if self.balanced_factor() >= self.lim_charge else None ) if new_key is None: break else: i += 1 return new_key if __name__ == "__main__": import doctest doctest.testmod()
hash map with open addressing https en wikipedia orgwikihashtable another hash map implementation with a good explanation modern dictionaries by raymond hettinger https www youtube comwatch vp33cvv29og8 hash map with open addressing get next index implements linear open addressing hashmap5 getnextind3 4 hashmap5 getnextind5 1 hashmap5 getnextind6 2 hashmap5 getnextind9 0 try to add value to the bucket if bucket is empty or key is the same does insert and return true if bucket has another key or deleted placeholder that means that we need to check next bucket return true if we have reached safe capacity so we need to increase the number of buckets to avoid collisions hm hashmap2 hm additem1 10 hm additem2 20 hm isfull true hashmap2 isfull false return true if we need twice fewer buckets when we have now if lenself buckets self initialblocksize return false limit lenself buckets self capacityfactor 2 return lenself limit def resizeself newsize int none oldbuckets self buckets self buckets none newsize self len 0 for item in oldbuckets if item self additemitem key item val def sizeupself none self resizelenself buckets 2 def sizedownself none self resizelenself buckets 2 def iteratebucketsself key key iteratorint ind self getbucketindexkey for in rangelenself buckets yield ind ind self getnextindind def additemself key key val val none for ind in self iteratebucketskey if self trysetind key val break def setitemself key key val val none if self isfull self sizeup self additemkey val def delitemself key key none trying to remove a nonexisting item for ind in self iteratebucketskey item self bucketsind if item is none raise keyerrorkey if item is deleted continue if item key key self bucketsind deleted self len 1 break if self issparse self sizedown def getitemself key key val for ind in self iteratebucketskey item self bucketsind if item is none break if item is deleted continue if item key key return item val raise keyerrorkey def lenself int return self len def iterself iteratorkey yield from item key for item in self buckets if item def reprself str valstring join fitem key item val for item in self buckets if item return fhashmapvalstring if name main import doctest doctest testmod hash map with open addressing get next index implements linear open addressing hashmap 5 _get_next_ind 3 4 hashmap 5 _get_next_ind 5 1 hashmap 5 _get_next_ind 6 2 hashmap 5 _get_next_ind 9 0 try to add value to the bucket if bucket is empty or key is the same does insert and return true if bucket has another key or deleted placeholder that means that we need to check next bucket return true if we have reached safe capacity so we need to increase the number of buckets to avoid collisions hm hashmap 2 hm _add_item 1 10 hm _add_item 2 20 hm _is_full true hashmap 2 _is_full false return true if we need twice fewer buckets when we have now try to add 3 elements when the size is 5 hm hashmap 5 hm _add_item 1 10 hm _add_item 2 20 hm _add_item 3 30 hm hashmap 1 10 2 20 3 30 try to add 3 elements when the size is 5 hm hashmap 5 hm _add_item 5 10 hm _add_item 6 30 hm _add_item 7 20 hm hashmap 5 10 6 30 7 20 try to add 3 elements when size is 1 hm hashmap 1 hm _add_item 10 13 2 hm _add_item 6 5 26 hm _add_item 7 5 155 hm hashmap 10 13 2 trying to add an element with a key that is a floating point value hm hashmap 5 hm _add_item 1 5 10 hm hashmap 1 5 10 5 trying to add an item with the same key hm hashmap 5 hm _add_item 1 10 hm _add_item 1 20 hm hashmap 1 20 1 changing value of item whose key is present hm hashmap 5 hm _add_item 1 10 hm __setitem__ 1 20 hm hashmap 1 20 2 changing value of item whose key is not present hm hashmap 5 hm _add_item 1 10 hm __setitem__ 0 20 hm hashmap 0 20 1 10 3 changing the value of the same item multiple times hm hashmap 5 hm _add_item 1 10 hm __setitem__ 1 20 hm __setitem__ 1 30 hm hashmap 1 30 hm hashmap 5 hm _add_item 1 10 hm _add_item 2 20 hm _add_item 3 30 hm __delitem__ 3 hm hashmap 1 10 2 20 hm hashmap 5 hm _add_item 5 10 hm _add_item 6 30 hm _add_item 7 20 hm __delitem__ 5 hm hashmap 6 30 7 20 trying to remove a non existing item hm hashmap 5 hm _add_item 1 10 hm _add_item 2 20 hm _add_item 3 30 hm __delitem__ 4 traceback most recent call last keyerror 4 returns the item at the given key hm hashmap 5 hm _add_item 1 10 hm __getitem__ 1 10 hm hashmap 5 hm _add_item 10 10 hm _add_item 20 20 hm __getitem__ 20 20 hm hashmap 5 hm _add_item 1 10 hm __getitem__ 1 10 returns the number of items present in hashmap hm hashmap 5 hm _add_item 1 10 hm _add_item 2 20 hm _add_item 3 30 hm __len__ 3 hm hashmap 5 hm __len__ 0
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar KEY = TypeVar("KEY") VAL = TypeVar("VAL") @dataclass(frozen=True, slots=True) class _Item(Generic[KEY, VAL]): key: KEY val: VAL class _DeletedItem(_Item): def __init__(self) -> None: super().__init__(None, None) def __bool__(self) -> bool: return False _deleted = _DeletedItem() class HashMap(MutableMapping[KEY, VAL]): def __init__( self, initial_block_size: int = 8, capacity_factor: float = 0.75 ) -> None: self._initial_block_size = initial_block_size self._buckets: list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 self._capacity_factor = capacity_factor self._len = 0 def _get_bucket_index(self, key: KEY) -> int: return hash(key) % len(self._buckets) def _get_next_ind(self, ind: int) -> int: return (ind + 1) % len(self._buckets) def _try_set(self, ind: int, key: KEY, val: VAL) -> bool: stored = self._buckets[ind] if not stored: self._buckets[ind] = _Item(key, val) self._len += 1 return True elif stored.key == key: self._buckets[ind] = _Item(key, val) return True else: return False def _is_full(self) -> bool: limit = len(self._buckets) * self._capacity_factor return len(self) >= int(limit) def _is_sparse(self) -> bool: if len(self._buckets) <= self._initial_block_size: return False limit = len(self._buckets) * self._capacity_factor / 2 return len(self) < limit def _resize(self, new_size: int) -> None: old_buckets = self._buckets self._buckets = [None] * new_size self._len = 0 for item in old_buckets: if item: self._add_item(item.key, item.val) def _size_up(self) -> None: self._resize(len(self._buckets) * 2) def _size_down(self) -> None: self._resize(len(self._buckets) // 2) def _iterate_buckets(self, key: KEY) -> Iterator[int]: ind = self._get_bucket_index(key) for _ in range(len(self._buckets)): yield ind ind = self._get_next_ind(ind) def _add_item(self, key: KEY, val: VAL) -> None: for ind in self._iterate_buckets(key): if self._try_set(ind, key, val): break def __setitem__(self, key: KEY, val: VAL) -> None: if self._is_full(): self._size_up() self._add_item(key, val) def __delitem__(self, key: KEY) -> None: for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: raise KeyError(key) if item is _deleted: continue if item.key == key: self._buckets[ind] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__(self, key: KEY) -> VAL: for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(key) def __len__(self) -> int: return self._len def __iter__(self) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__(self) -> str: val_string = ", ".join( f"{item.key}: {item.val}" for item in self._buckets if item ) return f"HashMap({val_string})" if __name__ == "__main__": import doctest doctest.testmod()
usrbinenv python3 basic hash table example with open addressing and linear probing the keys function returns a dictionary containing the key value pairs key being the index number in hash table and value being the data value examples 1 creating hashtable with size 10 and inserting 3 elements ht hashtable10 ht insertdata10 ht insertdata20 ht insertdata30 ht keys 0 10 1 20 2 30 2 creating hashtable with size 5 and inserting 5 elements ht hashtable5 ht insertdata5 ht insertdata4 ht insertdata3 ht insertdata2 ht insertdata1 ht keys 0 5 4 4 3 3 2 2 1 1 generates hash for the given key value examples creating hashtable with size 5 ht hashtable5 ht hashfunction10 0 ht hashfunction20 0 ht hashfunction4 4 ht hashfunction18 3 ht hashfunction18 2 ht hashfunction18 5 3 5 ht hashfunction0 0 ht hashfunction0 0 bulkinsert is used for entering more than one element at a time in the hashtable examples 1 ht hashtable5 ht bulkinsert10 20 30 step 1 0 1 2 3 4 10 none none none none step 2 0 1 2 3 4 10 20 none none none step 3 0 1 2 3 4 10 20 30 none none 2 ht hashtable5 ht bulkinsert5 4 3 2 1 step 1 0 1 2 3 4 5 none none none none step 2 0 1 2 3 4 5 none none none 4 step 3 0 1 2 3 4 5 none none 3 4 step 4 0 1 2 3 4 5 none 2 3 4 step 5 0 1 2 3 4 5 1 2 3 4 setvalue functions allows to update value at a particular hash examples 1 setvalue in hashtable of size 5 ht hashtable5 ht insertdata10 ht insertdata20 ht insertdata30 ht setvalue0 15 ht keys 0 15 1 20 2 30 2 setvalue in hashtable of size 2 ht hashtable2 ht insertdata17 ht insertdata18 ht insertdata99 ht setvalue3 15 ht keys 3 15 2 17 4 99 3 setvalue in hashtable when hash is not present ht hashtable2 ht insertdata17 ht insertdata18 ht insertdata99 ht setvalue0 15 ht keys 3 18 2 17 4 99 0 15 4 setvalue in hashtable when multiple hash are not present ht hashtable2 ht insertdata17 ht insertdata18 ht insertdata99 ht setvalue0 15 ht setvalue1 20 ht keys 3 18 2 17 4 99 0 15 1 20 this method is a type of open addressing which is used for handling collision in this implementation the concept of linear probing has been used the hash table is searched sequentially from the original location of the hash if the new hashlocation we get is already occupied we check for the next hashlocation references https en wikipedia orgwikilinearprobing examples 1 the collision will be with keys 18 99 so new hash will be created for 99 ht hashtable3 ht insertdata17 ht insertdata18 ht insertdata99 ht keys 2 17 0 18 1 99 2 the collision will be with keys 17 101 so new hash will be created for 101 ht hashtable4 ht insertdata17 ht insertdata18 ht insertdata99 ht insertdata101 ht keys 1 17 2 18 3 99 0 101 2 the collision will be with all keys so new hash will be created for all ht hashtable1 ht insertdata17 ht insertdata18 ht insertdata99 ht keys 2 17 3 18 4 99 3 trying to insert float key in hash ht hashtable1 ht insertdata17 ht insertdata18 ht insertdata99 99 traceback most recent call last typeerror list indices must be integers or slices not float insertdata is used for inserting a single element at a time in the hashtable examples ht hashtable3 ht insertdata5 ht keys 2 5 ht hashtable5 ht insertdata30 ht insertdata50 ht keys 0 30 1 50 usr bin env python3 basic hash table example with open addressing and linear probing the keys function returns a dictionary containing the key value pairs key being the index number in hash table and value being the data value examples 1 creating hashtable with size 10 and inserting 3 elements ht hashtable 10 ht insert_data 10 ht insert_data 20 ht insert_data 30 ht keys 0 10 1 20 2 30 2 creating hashtable with size 5 and inserting 5 elements ht hashtable 5 ht insert_data 5 ht insert_data 4 ht insert_data 3 ht insert_data 2 ht insert_data 1 ht keys 0 5 4 4 3 3 2 2 1 1 generates hash for the given key value examples creating hashtable with size 5 ht hashtable 5 ht hash_function 10 0 ht hash_function 20 0 ht hash_function 4 4 ht hash_function 18 3 ht hash_function 18 2 ht hash_function 18 5 3 5 ht hash_function 0 0 ht hash_function 0 0 bulk_insert is used for entering more than one element at a time in the hashtable examples 1 ht hashtable 5 ht bulk_insert 10 20 30 step 1 0 1 2 3 4 10 none none none none step 2 0 1 2 3 4 10 20 none none none step 3 0 1 2 3 4 10 20 30 none none 2 ht hashtable 5 ht bulk_insert 5 4 3 2 1 step 1 0 1 2 3 4 5 none none none none step 2 0 1 2 3 4 5 none none none 4 step 3 0 1 2 3 4 5 none none 3 4 step 4 0 1 2 3 4 5 none 2 3 4 step 5 0 1 2 3 4 5 1 2 3 4 _set_value functions allows to update value at a particular hash examples 1 _set_value in hashtable of size 5 ht hashtable 5 ht insert_data 10 ht insert_data 20 ht insert_data 30 ht _set_value 0 15 ht keys 0 15 1 20 2 30 2 _set_value in hashtable of size 2 ht hashtable 2 ht insert_data 17 ht insert_data 18 ht insert_data 99 ht _set_value 3 15 ht keys 3 15 2 17 4 99 3 _set_value in hashtable when hash is not present ht hashtable 2 ht insert_data 17 ht insert_data 18 ht insert_data 99 ht _set_value 0 15 ht keys 3 18 2 17 4 99 0 15 4 _set_value in hashtable when multiple hash are not present ht hashtable 2 ht insert_data 17 ht insert_data 18 ht insert_data 99 ht _set_value 0 15 ht _set_value 1 20 ht keys 3 18 2 17 4 99 0 15 1 20 this method is a type of open addressing which is used for handling collision in this implementation the concept of linear probing has been used the hash table is searched sequentially from the original location of the hash if the new hash location we get is already occupied we check for the next hash location references https en wikipedia org wiki linear_probing examples 1 the collision will be with keys 18 99 so new hash will be created for 99 ht hashtable 3 ht insert_data 17 ht insert_data 18 ht insert_data 99 ht keys 2 17 0 18 1 99 2 the collision will be with keys 17 101 so new hash will be created for 101 ht hashtable 4 ht insert_data 17 ht insert_data 18 ht insert_data 99 ht insert_data 101 ht keys 1 17 2 18 3 99 0 101 2 the collision will be with all keys so new hash will be created for all ht hashtable 1 ht insert_data 17 ht insert_data 18 ht insert_data 99 ht keys 2 17 3 18 4 99 3 trying to insert float key in hash ht hashtable 1 ht insert_data 17 ht insert_data 18 ht insert_data 99 99 traceback most recent call last typeerror list indices must be integers or slices not float hell s pointers d don t dry insert_data is used for inserting a single element at a time in the hashtable examples ht hashtable 3 ht insert_data 5 ht keys 2 5 ht hashtable 5 ht insert_data 30 ht insert_data 50 ht keys 0 30 1 50
from .number_theory.prime_numbers import next_prime class HashTable: def __init__( self, size_table: int, charge_factor: int | None = None, lim_charge: float | None = None, ) -> None: self.size_table = size_table self.values = [None] * self.size_table self.lim_charge = 0.75 if lim_charge is None else lim_charge self.charge_factor = 1 if charge_factor is None else charge_factor self.__aux_list: list = [] self._keys: dict = {} def keys(self): return self._keys def balanced_factor(self): return sum(1 for slot in self.values if slot is not None) / ( self.size_table * self.charge_factor ) def hash_function(self, key): return key % self.size_table def _step_by_step(self, step_ord): print(f"step {step_ord}") print(list(range(len(self.values)))) print(self.values) def bulk_insert(self, values): i = 1 self.__aux_list = values for value in values: self.insert_data(value) self._step_by_step(i) i += 1 def _set_value(self, key, data): self.values[key] = data self._keys[key] = data def _collision_resolution(self, key, data=None): new_key = self.hash_function(key + 1) while self.values[new_key] is not None and self.values[new_key] != key: if self.values.count(None) > 0: new_key = self.hash_function(new_key + 1) else: new_key = None break return new_key def rehashing(self): survivor_values = [value for value in self.values if value is not None] self.size_table = next_prime(self.size_table, factor=2) self._keys.clear() self.values = [None] * self.size_table for value in survivor_values: self.insert_data(value) def insert_data(self, data): key = self.hash_function(data) if self.values[key] is None: self._set_value(key, data) elif self.values[key] == data: pass else: collision_resolution = self._collision_resolution(key, data) if collision_resolution is not None: self._set_value(collision_resolution, data) else: self.rehashing() self.insert_data(data) if __name__ == "__main__": import doctest doctest.testmod()
usrbinenv python3 module to operations with prime numbers checks to see if a number is a prime in osqrtn a number is prime if it has exactly two factors 1 and itself isprime0 false isprime1 false isprime2 true isprime3 true isprime27 false isprime87 false isprime563 true isprime2999 true isprime67483 false precondition 2 and 3 are primes negatives 0 1 and all even numbers are not primes usr bin env python3 module to operations with prime numbers checks to see if a number is a prime in o sqrt n a number is prime if it has exactly two factors 1 and itself is_prime 0 false is_prime 1 false is_prime 2 true is_prime 3 true is_prime 27 false is_prime 87 false is_prime 563 true is_prime 2999 true is_prime 67483 false precondition 2 and 3 are primes negatives 0 1 and all even numbers are not primes
import math def is_prime(number: int) -> bool: assert isinstance(number, int) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: return True elif number < 2 or not number % 2: return False odd_numbers = range(3, int(math.sqrt(number) + 1), 2) return not any(not number % i for i in odd_numbers) def next_prime(value, factor=1, **kwargs): value = factor * value first_value_val = value while not is_prime(value): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1, **kwargs) return value
usrbinenv python3 basic hash table example with open addressing using quadratic probing quadratic probing is an open addressing scheme used for resolving collisions in hash table it works by taking the original hash index and adding successive values of an arbitrary quadratic polynomial until open slot is found hash 1 hash 2 hash 3 hash n reference https en wikipedia orgwikiquadraticprobing e g 1 create hash table with size 7 qp quadraticprobing7 qp insertdata90 qp insertdata340 qp insertdata24 qp insertdata45 qp insertdata99 qp insertdata73 qp insertdata7 qp keys 11 45 14 99 7 24 0 340 5 73 6 90 8 7 2 create hash table with size 8 qp quadraticprobing8 qp insertdata0 qp insertdata999 qp insertdata111 qp keys 0 0 7 999 3 111 3 try to add three data elements when the size is two qp quadraticprobing2 qp insertdata0 qp insertdata999 qp insertdata111 qp keys 0 0 4 999 1 111 4 try to add three data elements when the size is one qp quadraticprobing1 qp insertdata0 qp insertdata999 qp insertdata111 qp keys 4 999 1 111 usr bin env python3 basic hash table example with open addressing using quadratic probing quadratic probing is an open addressing scheme used for resolving collisions in hash table it works by taking the original hash index and adding successive values of an arbitrary quadratic polynomial until open slot is found hash 1² hash 2² hash 3² hash n² reference https en wikipedia org wiki quadratic_probing e g 1 create hash table with size 7 qp quadraticprobing 7 qp insert_data 90 qp insert_data 340 qp insert_data 24 qp insert_data 45 qp insert_data 99 qp insert_data 73 qp insert_data 7 qp keys 11 45 14 99 7 24 0 340 5 73 6 90 8 7 2 create hash table with size 8 qp quadraticprobing 8 qp insert_data 0 qp insert_data 999 qp insert_data 111 qp keys 0 0 7 999 3 111 3 try to add three data elements when the size is two qp quadraticprobing 2 qp insert_data 0 qp insert_data 999 qp insert_data 111 qp keys 0 0 4 999 1 111 4 try to add three data elements when the size is one qp quadraticprobing 1 qp insert_data 0 qp insert_data 999 qp insert_data 111 qp keys 4 999 1 111
from .hash_table import HashTable class QuadraticProbing(HashTable): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _collision_resolution(self, key, data=None): i = 1 new_key = self.hash_function(key + i * i) while self.values[new_key] is not None and self.values[new_key] != key: i += 1 new_key = ( self.hash_function(key + i * i) if not self.balanced_factor() >= self.lim_charge else None ) if new_key is None: break return new_key if __name__ == "__main__": import doctest doctest.testmod()
a max heap implementation unsorted 103 9 1 7 11 15 25 201 209 107 5 h heap h buildmaxheapunsorted h 209 201 25 103 107 15 1 9 7 11 5 h extractmax 209 h 201 107 25 103 11 15 1 9 7 5 h insert100 h 201 107 25 103 100 15 1 9 7 5 11 h heapsort h 1 5 7 9 11 15 25 100 103 107 201 returns the parent index based on the given child index h heap h buildmaxheap103 9 1 7 11 15 25 201 209 107 5 h 209 201 25 103 107 15 1 9 7 11 5 h parentindex1 returns none if index is 0 h parentindex0 returns none if index is 0 h parentindex1 0 h parentindex2 0 h parentindex3 1 h parentindex4 1 h parentindex5 2 h parentindex10 5 4 0 h parentindex209 0 104 0 h parentindextest traceback most recent call last typeerror not supported between instances of str and int return the left child index if the left child exists if not return none return the right child index if the right child exists if not return none correct a single violation of the heap property in a subtree s root it is the function that is responsible for restoring the property of max heap i e the maximum element is always at top check which child is larger than its parent if violation indeed exists swap to fix the violation fix the subsequent violation recursively if any build max heap from an unsorted array h heap h buildmaxheap20 40 50 20 10 h 50 40 20 20 10 h heap h buildmaxheap1 2 3 4 5 6 7 8 9 0 h 9 8 7 4 5 6 3 2 1 0 h heap h buildmaxheap514 5 61 57 8 99 105 h 514 57 105 5 8 99 61 h heap h buildmaxheap514 5 61 6 57 8 9 9 105 h 514 57 105 5 8 9 9 61 6 maxheapify from right to left but exclude leaves last level get and remove max from heap h heap h buildmaxheap20 40 50 20 10 h extractmax 50 h heap h buildmaxheap514 5 61 57 8 99 105 h extractmax 514 h heap h buildmaxheap1 2 3 4 5 6 7 8 9 0 h extractmax 9 insert a new value into the max heap h heap h insert10 h 10 h heap h insert10 h insert10 h 10 10 h heap h insert10 h insert10 1 h 10 1 10 h heap h insert0 1 h insert0 h insert9 h insert5 h 9 5 0 1 0 run doc test demo a max heap implementation unsorted 103 9 1 7 11 15 25 201 209 107 5 h heap h build_max_heap unsorted h 209 201 25 103 107 15 1 9 7 11 5 h extract_max 209 h 201 107 25 103 11 15 1 9 7 5 h insert 100 h 201 107 25 103 100 15 1 9 7 5 11 h heap_sort h 1 5 7 9 11 15 25 100 103 107 201 returns the parent index based on the given child index h heap h build_max_heap 103 9 1 7 11 15 25 201 209 107 5 h 209 201 25 103 107 15 1 9 7 11 5 h parent_index 1 returns none if index is 0 h parent_index 0 returns none if index is 0 h parent_index 1 0 h parent_index 2 0 h parent_index 3 1 h parent_index 4 1 h parent_index 5 2 h parent_index 10 5 4 0 h parent_index 209 0 104 0 h parent_index test traceback most recent call last typeerror not supported between instances of str and int return the left child index if the left child exists if not return none return the right child index if the right child exists if not return none correct a single violation of the heap property in a subtree s root it is the function that is responsible for restoring the property of max heap i e the maximum element is always at top check which child is larger than its parent if violation indeed exists swap to fix the violation fix the subsequent violation recursively if any build max heap from an unsorted array h heap h build_max_heap 20 40 50 20 10 h 50 40 20 20 10 h heap h build_max_heap 1 2 3 4 5 6 7 8 9 0 h 9 8 7 4 5 6 3 2 1 0 h heap h build_max_heap 514 5 61 57 8 99 105 h 514 57 105 5 8 99 61 h heap h build_max_heap 514 5 61 6 57 8 9 9 105 h 514 57 105 5 8 9 9 61 6 max_heapify from right to left but exclude leaves last level get and remove max from heap h heap h build_max_heap 20 40 50 20 10 h extract_max 50 h heap h build_max_heap 514 5 61 57 8 99 105 h extract_max 514 h heap h build_max_heap 1 2 3 4 5 6 7 8 9 0 h extract_max 9 insert a new value into the max heap h heap h insert 10 h 10 h heap h insert 10 h insert 10 h 10 10 h heap h insert 10 h insert 10 1 h 10 1 10 h heap h insert 0 1 h insert 0 h insert 9 h insert 5 h 9 5 0 1 0 run doc test demo
from __future__ import annotations from abc import abstractmethod from collections.abc import Iterable from typing import Generic, Protocol, TypeVar class Comparable(Protocol): @abstractmethod def __lt__(self: T, other: T) -> bool: pass @abstractmethod def __gt__(self: T, other: T) -> bool: pass @abstractmethod def __eq__(self: T, other: object) -> bool: pass T = TypeVar("T", bound=Comparable) class Heap(Generic[T]): def __init__(self) -> None: self.h: list[T] = [] self.heap_size: int = 0 def __repr__(self) -> str: return str(self.h) def parent_index(self, child_idx: int) -> int | None: if child_idx > 0: return (child_idx - 1) // 2 return None def left_child_idx(self, parent_idx: int) -> int | None: left_child_index = 2 * parent_idx + 1 if left_child_index < self.heap_size: return left_child_index return None def right_child_idx(self, parent_idx: int) -> int | None: right_child_index = 2 * parent_idx + 2 if right_child_index < self.heap_size: return right_child_index return None def max_heapify(self, index: int) -> None: if index < self.heap_size: violation: int = index left_child = self.left_child_idx(index) right_child = self.right_child_idx(index) if left_child is not None and self.h[left_child] > self.h[violation]: violation = left_child if right_child is not None and self.h[right_child] > self.h[violation]: violation = right_child if violation != index: self.h[violation], self.h[index] = self.h[index], self.h[violation] self.max_heapify(violation) def build_max_heap(self, collection: Iterable[T]) -> None: self.h = list(collection) self.heap_size = len(self.h) if self.heap_size > 1: for i in range(self.heap_size // 2 - 1, -1, -1): self.max_heapify(i) def extract_max(self) -> T: if self.heap_size >= 2: me = self.h[0] self.h[0] = self.h.pop(-1) self.heap_size -= 1 self.max_heapify(0) return me elif self.heap_size == 1: self.heap_size -= 1 return self.h.pop(-1) else: raise Exception("Empty heap") def insert(self, value: T) -> None: self.h.append(value) idx = (self.heap_size - 1) // 2 self.heap_size += 1 while idx >= 0: self.max_heapify(idx) idx = (idx - 1) // 2 def heap_sort(self) -> None: size = self.heap_size for j in range(size - 1, 0, -1): self.h[0], self.h[j] = self.h[j], self.h[0] self.heap_size -= 1 self.max_heapify(0) self.heap_size = size if __name__ == "__main__": import doctest doctest.testmod() for unsorted in [ [0], [2], [3, 5], [5, 3], [5, 5], [0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 3, 5], [0, 2, 2, 3, 5], [2, 5, 3, 0, 2, 3, 0, 3], [6, 1, 2, 7, 9, 3, 4, 5, 10, 8], [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5], [-45, -2, -5], ]: print(f"unsorted array: {unsorted}") heap: Heap[int] = Heap() heap.build_max_heap(unsorted) print(f"after build heap: {heap}") print(f"max value: {heap.extract_max()}") print(f"after max value removed: {heap}") heap.insert(100) print(f"after new value 100 inserted: {heap}") heap.heap_sort() print(f"heap-sorted array: {heap}\n")
a maxheap implementation in python binaryheap binaryheap binaryheap insert6 binaryheap insert10 binaryheap insert15 binaryheap insert12 binaryheap pop 15 binaryheap pop 12 binaryheap getlist 10 6 lenbinaryheap 2 swap the element up temporary self heapi while i 2 0 if self heapi self heapi 2 self heapi self heapi 2 self heapi 2 temporary i 2 def insertself value int none swap the element down while self size 2 i if 2 i 1 self size biggerchild 2 i else if self heap2 i self heap2 i 1 biggerchild 2 i else biggerchild 2 i 1 temporary self heapi if self heapi self heapbiggerchild self heapi self heapbiggerchild self heapbiggerchild temporary i biggerchild def popself int length of the array return self size if name main import doctest doctest testmod create an instance of binaryheap binaryheap binaryheap binaryheap insert6 binaryheap insert10 binaryheap insert15 binaryheap insert12 pop rootmaxvalues because it is max heap printbinaryheap pop 15 printbinaryheap pop 12 get the list and size after operations printbinaryheap getlist printlenbinaryheap a max heap implementation in python binary_heap binaryheap binary_heap insert 6 binary_heap insert 10 binary_heap insert 15 binary_heap insert 12 binary_heap pop 15 binary_heap pop 12 binary_heap get_list 10 6 len binary_heap 2 swap the element up insert new element swap the element down pop the root element length of the array create an instance of binaryheap pop root max values because it is max heap 15 12 get the list and size after operations
class BinaryHeap: def __init__(self): self.__heap = [0] self.__size = 0 def __swap_up(self, i: int) -> None: temporary = self.__heap[i] while i // 2 > 0: if self.__heap[i] > self.__heap[i // 2]: self.__heap[i] = self.__heap[i // 2] self.__heap[i // 2] = temporary i //= 2 def insert(self, value: int) -> None: self.__heap.append(value) self.__size += 1 self.__swap_up(self.__size) def __swap_down(self, i: int) -> None: while self.__size >= 2 * i: if 2 * i + 1 > self.__size: bigger_child = 2 * i else: if self.__heap[2 * i] > self.__heap[2 * i + 1]: bigger_child = 2 * i else: bigger_child = 2 * i + 1 temporary = self.__heap[i] if self.__heap[i] < self.__heap[bigger_child]: self.__heap[i] = self.__heap[bigger_child] self.__heap[bigger_child] = temporary i = bigger_child def pop(self) -> int: max_value = self.__heap[1] self.__heap[1] = self.__heap[self.__size] self.__size -= 1 self.__heap.pop() self.__swap_down(1) return max_value @property def get_list(self): return self.__heap[1:] def __len__(self): return self.__size if __name__ == "__main__": import doctest doctest.testmod() binary_heap = BinaryHeap() binary_heap.insert(6) binary_heap.insert(10) binary_heap.insert(15) binary_heap.insert(12) print(binary_heap.pop()) print(binary_heap.pop()) print(binary_heap.get_list) print(len(binary_heap))
min heap data structure with decrease key functionality in ologn time r noder 1 b nodeb 6 a nodea 3 x nodex 1 e nodee 4 printb nodeb 6 myminheap minheapr b a x e myminheap decreasekeyb 17 printb nodeb 17 myminheapb 17 this is minheapify method usage use one of these two ways to generate minheap generating minheap from array generating minheap by insert method myminheap inserta myminheap insertb myminheap insertx myminheap insertr myminheap inserte before after min heap data structure with decrease key functionality in o log n time r node r 1 b node b 6 a node a 3 x node x 1 e node e 4 print b node b 6 myminheap minheap r b a x e myminheap decrease_key b 17 print b node b 17 myminheap b 17 this is min heapify method noqa e741 usage use one of these two ways to generate min heap generating min heap from array generating min heap by insert method myminheap insert a myminheap insert b myminheap insert x myminheap insert r myminheap insert e before after
class Node: def __init__(self, name, val): self.name = name self.val = val def __str__(self): return f"{self.__class__.__name__}({self.name}, {self.val})" def __lt__(self, other): return self.val < other.val class MinHeap: def __init__(self, array): self.idx_of_element = {} self.heap_dict = {} self.heap = self.build_heap(array) def __getitem__(self, key): return self.get_value(key) def get_parent_idx(self, idx): return (idx - 1) // 2 def get_left_child_idx(self, idx): return idx * 2 + 1 def get_right_child_idx(self, idx): return idx * 2 + 2 def get_value(self, key): return self.heap_dict[key] def build_heap(self, array): last_idx = len(array) - 1 start_from = self.get_parent_idx(last_idx) for idx, i in enumerate(array): self.idx_of_element[i] = idx self.heap_dict[i.name] = i.val for i in range(start_from, -1, -1): self.sift_down(i, array) return array def sift_down(self, idx, array): while True: l = self.get_left_child_idx(idx) r = self.get_right_child_idx(idx) smallest = idx if l < len(array) and array[l] < array[idx]: smallest = l if r < len(array) and array[r] < array[smallest]: smallest = r if smallest != idx: array[idx], array[smallest] = array[smallest], array[idx] ( self.idx_of_element[array[idx]], self.idx_of_element[array[smallest]], ) = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) idx = smallest else: break def sift_up(self, idx): p = self.get_parent_idx(idx) while p >= 0 and self.heap[p] > self.heap[idx]: self.heap[p], self.heap[idx] = self.heap[idx], self.heap[p] self.idx_of_element[self.heap[p]], self.idx_of_element[self.heap[idx]] = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) idx = p p = self.get_parent_idx(idx) def peek(self): return self.heap[0] def remove(self): self.heap[0], self.heap[-1] = self.heap[-1], self.heap[0] self.idx_of_element[self.heap[0]], self.idx_of_element[self.heap[-1]] = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) x = self.heap.pop() del self.idx_of_element[x] self.sift_down(0, self.heap) return x def insert(self, node): self.heap.append(node) self.idx_of_element[node] = len(self.heap) - 1 self.heap_dict[node.name] = node.val self.sift_up(len(self.heap) - 1) def is_empty(self): return len(self.heap) == 0 def decrease_key(self, node, new_value): assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" node.val = new_value self.heap_dict[node.name] = new_value self.sift_up(self.idx_of_element[node]) r = Node("R", -1) b = Node("B", 6) a = Node("A", 3) x = Node("X", 1) e = Node("E", 4) my_min_heap = MinHeap([r, b, a, x, e]) print("Min Heap - before decrease key") for i in my_min_heap.heap: print(i) print("Min Heap - After decrease key of node [B -> -17]") my_min_heap.decrease_key(b, -17) for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
usrbinenv python3 one node of the randomized heap contains the value and references to two children return the value of the node rhn randomizedheapnode10 rhn value 10 rhn randomizedheapnode10 rhn value 10 merge 2 nodes together rhn1 randomizedheapnode10 rhn2 randomizedheapnode20 randomizedheapnode mergerhn1 rhn2 value 10 rhn1 randomizedheapnode20 rhn2 randomizedheapnode10 randomizedheapnode mergerhn1 rhn2 value 10 rhn1 randomizedheapnode5 rhn2 randomizedheapnode0 randomizedheapnode mergerhn1 rhn2 value 0 a data structure that allows inserting a new value and to pop the smallest values both operations take ologn time where n is the size of the structure wiki https en wikipedia orgwikirandomizedmeldableheap randomizedheap2 3 1 5 1 7 tosortedlist 1 1 2 3 5 7 rh randomizedheap rh pop traceback most recent call last indexerror can t get top element for the empty heap rh insert1 rh insert1 rh insert0 rh tosortedlist 1 0 1 rh randomizedheap3 1 3 7 rh tosortedlist 1 3 3 7 insert the value into the heap rh randomizedheap rh insert3 rh insert1 rh insert3 rh insert7 rh tosortedlist 1 3 3 7 pop the smallest value from the heap and return it rh randomizedheap3 1 3 7 rh pop 1 rh pop 3 rh pop 3 rh pop 7 rh pop traceback most recent call last indexerror can t get top element for the empty heap return the smallest value from the heap rh randomizedheap rh insert3 rh top 3 rh insert1 rh top 1 rh insert3 rh top 1 rh insert7 rh top 1 clear the heap rh randomizedheap3 1 3 7 rh clear rh pop traceback most recent call last indexerror can t get top element for the empty heap returns sorted list containing all the values in the heap rh randomizedheap3 1 3 7 rh tosortedlist 1 3 3 7 check if the heap is not empty rh randomizedheap boolrh false rh insert1 boolrh true rh clear boolrh false usr bin env python3 one node of the randomized heap contains the value and references to two children return the value of the node rhn randomizedheapnode 10 rhn value 10 rhn randomizedheapnode 10 rhn value 10 merge 2 nodes together rhn1 randomizedheapnode 10 rhn2 randomizedheapnode 20 randomizedheapnode merge rhn1 rhn2 value 10 rhn1 randomizedheapnode 20 rhn2 randomizedheapnode 10 randomizedheapnode merge rhn1 rhn2 value 10 rhn1 randomizedheapnode 5 rhn2 randomizedheapnode 0 randomizedheapnode merge rhn1 rhn2 value 0 a data structure that allows inserting a new value and to pop the smallest values both operations take o logn time where n is the size of the structure wiki https en wikipedia org wiki randomized_meldable_heap randomizedheap 2 3 1 5 1 7 to_sorted_list 1 1 2 3 5 7 rh randomizedheap rh pop traceback most recent call last indexerror can t get top element for the empty heap rh insert 1 rh insert 1 rh insert 0 rh to_sorted_list 1 0 1 rh randomizedheap 3 1 3 7 rh to_sorted_list 1 3 3 7 insert the value into the heap rh randomizedheap rh insert 3 rh insert 1 rh insert 3 rh insert 7 rh to_sorted_list 1 3 3 7 pop the smallest value from the heap and return it rh randomizedheap 3 1 3 7 rh pop 1 rh pop 3 rh pop 3 rh pop 7 rh pop traceback most recent call last indexerror can t get top element for the empty heap return the smallest value from the heap rh randomizedheap rh insert 3 rh top 3 rh insert 1 rh top 1 rh insert 3 rh top 1 rh insert 7 rh top 1 clear the heap rh randomizedheap 3 1 3 7 rh clear rh pop traceback most recent call last indexerror can t get top element for the empty heap returns sorted list containing all the values in the heap rh randomizedheap 3 1 3 7 rh to_sorted_list 1 3 3 7 check if the heap is not empty rh randomizedheap bool rh false rh insert 1 bool rh true rh clear bool rh false
from __future__ import annotations import random from collections.abc import Iterable from typing import Any, Generic, TypeVar T = TypeVar("T", bound=bool) class RandomizedHeapNode(Generic[T]): def __init__(self, value: T) -> None: self._value: T = value self.left: RandomizedHeapNode[T] | None = None self.right: RandomizedHeapNode[T] | None = None @property def value(self) -> T: return self._value @staticmethod def merge( root1: RandomizedHeapNode[T] | None, root2: RandomizedHeapNode[T] | None ) -> RandomizedHeapNode[T] | None: if not root1: return root2 if not root2: return root1 if root1.value > root2.value: root1, root2 = root2, root1 if random.choice([True, False]): root1.left, root1.right = root1.right, root1.left root1.left = RandomizedHeapNode.merge(root1.left, root2) return root1 class RandomizedHeap(Generic[T]): def __init__(self, data: Iterable[T] | None = ()) -> None: self._root: RandomizedHeapNode[T] | None = None if data: for item in data: self.insert(item) def insert(self, value: T) -> None: self._root = RandomizedHeapNode.merge(self._root, RandomizedHeapNode(value)) def pop(self) -> T | None: result = self.top() if self._root is None: return None self._root = RandomizedHeapNode.merge(self._root.left, self._root.right) return result def top(self) -> T: if not self._root: raise IndexError("Can't get top element for the empty heap.") return self._root.value def clear(self) -> None: self._root = None def to_sorted_list(self) -> list[Any]: result = [] while self: result.append(self.pop()) return result def __bool__(self) -> bool: return self._root is not None if __name__ == "__main__": import doctest doctest.testmod()
usrbinenv python3 one node of the skew heap contains the value and references to two children return the value of the node return self value staticmethod def merge root1 skewnodet none root2 skewnodet none skewnodet none a data structure that allows inserting a new value and to pop the smallest values both operations take ologn time where n is the size of the structure wiki https en wikipedia orgwikiskewheap visualization https www cs usfca edugallesvisualizationskewheap html listskewheap2 3 1 5 1 7 1 1 2 3 5 7 sh skewheap sh pop traceback most recent call last indexerror can t get top element for the empty heap sh insert1 sh insert1 sh insert0 listsh 1 0 1 sh skewheap3 1 3 7 listsh 1 3 3 7 check if the heap is not empty sh skewheap boolsh false sh insert1 boolsh true sh clear boolsh false returns sorted list containing all the values in the heap sh skewheap3 1 3 7 listsh 1 3 3 7 pushing items back to the heap not to clear it insert the value into the heap sh skewheap sh insert3 sh insert1 sh insert3 sh insert7 listsh 1 3 3 7 pop the smallest value from the heap and return it sh skewheap3 1 3 7 sh pop 1 sh pop 3 sh pop 3 sh pop 7 sh pop traceback most recent call last indexerror can t get top element for the empty heap return the smallest value from the heap sh skewheap sh insert3 sh top 3 sh insert1 sh top 1 sh insert3 sh top 1 sh insert7 sh top 1 clear the heap sh skewheap3 1 3 7 sh clear sh pop traceback most recent call last indexerror can t get top element for the empty heap usr bin env python3 one node of the skew heap contains the value and references to two children return the value of the node merge 2 nodes together a data structure that allows inserting a new value and to pop the smallest values both operations take o logn time where n is the size of the structure wiki https en wikipedia org wiki skew_heap visualization https www cs usfca edu galles visualization skewheap html list skewheap 2 3 1 5 1 7 1 1 2 3 5 7 sh skewheap sh pop traceback most recent call last indexerror can t get top element for the empty heap sh insert 1 sh insert 1 sh insert 0 list sh 1 0 1 sh skewheap 3 1 3 7 list sh 1 3 3 7 check if the heap is not empty sh skewheap bool sh false sh insert 1 bool sh true sh clear bool sh false returns sorted list containing all the values in the heap sh skewheap 3 1 3 7 list sh 1 3 3 7 pushing items back to the heap not to clear it insert the value into the heap sh skewheap sh insert 3 sh insert 1 sh insert 3 sh insert 7 list sh 1 3 3 7 pop the smallest value from the heap and return it sh skewheap 3 1 3 7 sh pop 1 sh pop 3 sh pop 3 sh pop 7 sh pop traceback most recent call last indexerror can t get top element for the empty heap return the smallest value from the heap sh skewheap sh insert 3 sh top 3 sh insert 1 sh top 1 sh insert 3 sh top 1 sh insert 7 sh top 1 clear the heap sh skewheap 3 1 3 7 sh clear sh pop traceback most recent call last indexerror can t get top element for the empty heap
from __future__ import annotations from collections.abc import Iterable, Iterator from typing import Any, Generic, TypeVar T = TypeVar("T", bound=bool) class SkewNode(Generic[T]): def __init__(self, value: T) -> None: self._value: T = value self.left: SkewNode[T] | None = None self.right: SkewNode[T] | None = None @property def value(self) -> T: return self._value @staticmethod def merge( root1: SkewNode[T] | None, root2: SkewNode[T] | None ) -> SkewNode[T] | None: if not root1: return root2 if not root2: return root1 if root1.value > root2.value: root1, root2 = root2, root1 result = root1 temp = root1.right result.right = root1.left result.left = SkewNode.merge(temp, root2) return result class SkewHeap(Generic[T]): def __init__(self, data: Iterable[T] | None = ()) -> None: self._root: SkewNode[T] | None = None if data: for item in data: self.insert(item) def __bool__(self) -> bool: return self._root is not None def __iter__(self) -> Iterator[T]: result: list[Any] = [] while self: result.append(self.pop()) for item in result: self.insert(item) return iter(result) def insert(self, value: T) -> None: self._root = SkewNode.merge(self._root, SkewNode(value)) def pop(self) -> T | None: result = self.top() self._root = ( SkewNode.merge(self._root.left, self._root.right) if self._root else None ) return result def top(self) -> T: if not self._root: raise IndexError("Can't get top element for the empty heap.") return self._root.value def clear(self) -> None: self._root = None if __name__ == "__main__": import doctest doctest.testmod()
linked lists consists of nodes nodes contain data and also may link to other nodes head node first node the address of the head node gives us access of the complete list last node points to null add an item to the linkedlist at the specified position default position is 0 the head args item any the item to add to the linkedlist position int optional the position at which to add the item defaults to 0 raises valueerror if the position is negative or out of bounds linkedlist linkedlist linkedlist add1 linkedlist add2 linkedlist add3 linkedlist add4 2 printlinkedlist 3 2 4 1 test adding to a negative position linkedlist add5 3 traceback most recent call last valueerror position must be nonnegative test adding to an outofbounds position linkedlist add5 7 traceback most recent call last valueerror out of bounds linkedlist add5 4 printlinkedlist 3 2 4 1 5 switched self isempty to self head is none because mypy was considering the possibility that self head can be none in below else part and giving error linkedlist linkedlist linkedlist add23 linkedlist add14 linkedlist add9 printlinkedlist 9 14 23 linkedlist linkedlist lenlinkedlist 0 linkedlist adda lenlinkedlist 1 linkedlist addb lenlinkedlist 2 linkedlist remove lenlinkedlist 1 linkedlist remove lenlinkedlist 0 noqa a002 add an item to the linkedlist at the specified position default position is 0 the head args item any the item to add to the linkedlist position int optional the position at which to add the item defaults to 0 raises valueerror if the position is negative or out of bounds linked_list linkedlist linked_list add 1 linked_list add 2 linked_list add 3 linked_list add 4 2 print linked_list 3 2 4 1 test adding to a negative position linked_list add 5 3 traceback most recent call last valueerror position must be non negative test adding to an out of bounds position linked_list add 5 7 traceback most recent call last valueerror out of bounds linked_list add 5 4 print linked_list 3 2 4 1 5 switched self is_empty to self head is none because mypy was considering the possibility that self head can be none in below else part and giving error linked_list linkedlist linked_list add 23 linked_list add 14 linked_list add 9 print linked_list 9 14 23 linked_list linkedlist len linked_list 0 linked_list add a len linked_list 1 linked_list add b len linked_list 2 _ linked_list remove len linked_list 1 _ linked_list remove len linked_list 0
from __future__ import annotations from typing import Any class Node: def __init__(self, item: Any, next: Any) -> None: self.item = item self.next = next class LinkedList: def __init__(self) -> None: self.head: Node | None = None self.size = 0 def add(self, item: Any, position: int = 0) -> None: if position < 0: raise ValueError("Position must be non-negative") if position == 0 or self.head is None: new_node = Node(item, self.head) self.head = new_node else: current = self.head for _ in range(position - 1): current = current.next if current is None: raise ValueError("Out of bounds") new_node = Node(item, current.next) current.next = new_node self.size += 1 def remove(self) -> Any: if self.head is None: return None else: item = self.head.item self.head = self.head.next self.size -= 1 return item def is_empty(self) -> bool: return self.head is None def __str__(self) -> str: if self.is_empty(): return "" else: iterate = self.head item_str = "" item_list: list[str] = [] while iterate: item_list.append(str(iterate.item)) iterate = iterate.next item_str = " --> ".join(item_list) return item_str def __len__(self) -> int: return self.size
iterate through all nodes in the circular linked list yielding their data yields the data of each node in the linked list get the length number of nodes in the circular linked list generate a string representation of the circular linked list returns a string of the format 12 n insert a node with the given data at the end of the circular linked list insert a node with the given data at the beginning of the circular linked list insert the data of the node at the nth pos in the circular linked list args index the index at which the data should be inserted data the data to be inserted raises indexerror if the index is out of range delete and return the data of the node at the front of the circular linked list raises indexerror if the list is empty delete and return the data of the node at the end of the circular linked list returns any the data of the deleted node raises indexerror if the index is out of range delete and return the data of the node at the nth pos in circular linked list args index int the index of the node to be deleted defaults to 0 returns any the data of the deleted node raises indexerror if the index is out of range check if the circular linked list is empty returns bool true if the list is empty false otherwise test cases for the circularlinkedlist class testcircularlinkedlist reference to the head first node reference to the tail last node iterate through all nodes in the circular linked list yielding their data yields the data of each node in the linked list get the length number of nodes in the circular linked list generate a string representation of the circular linked list returns a string of the format 1 2 n insert a node with the given data at the end of the circular linked list insert a node with the given data at the beginning of the circular linked list insert the data of the node at the nth pos in the circular linked list args index the index at which the data should be inserted data the data to be inserted raises indexerror if the index is out of range first node points to itself insert at the head list is not empty tail exists insert at the tail delete and return the data of the node at the front of the circular linked list raises indexerror if the list is empty delete and return the data of the node at the end of the circular linked list returns any the data of the deleted node raises indexerror if the index is out of range delete and return the data of the node at the nth pos in circular linked list args index int the index of the node to be deleted defaults to 0 returns any the data of the deleted node raises indexerror if the index is out of range just one node delete head node delete at tail check if the circular linked list is empty returns bool true if the list is empty false otherwise test cases for the circularlinkedlist class test_circular_linked_list this should not happen this should happen this should not happen this should happen
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass from typing import Any @dataclass class Node: data: Any next_node: Node | None = None @dataclass class CircularLinkedList: head: Node | None = None tail: Node | None = None def __iter__(self) -> Iterator[Any]: node = self.head while node: yield node.data node = node.next_node if node == self.head: break def __len__(self) -> int: return sum(1 for _ in self) def __repr__(self) -> str: return "->".join(str(item) for item in iter(self)) def insert_tail(self, data: Any) -> None: self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: if index < 0 or index > len(self): raise IndexError("list index out of range.") new_node: Node = Node(data) if self.head is None: new_node.next_node = new_node self.tail = self.head = new_node elif index == 0: new_node.next_node = self.head assert self.tail is not None self.head = self.tail.next_node = new_node else: temp: Node | None = self.head for _ in range(index - 1): assert temp is not None temp = temp.next_node assert temp is not None new_node.next_node = temp.next_node temp.next_node = new_node if index == len(self) - 1: self.tail = new_node def delete_front(self) -> Any: return self.delete_nth(0) def delete_tail(self) -> Any: return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: if not 0 <= index < len(self): raise IndexError("list index out of range.") assert self.head is not None assert self.tail is not None delete_node: Node = self.head if self.head == self.tail: self.head = self.tail = None elif index == 0: assert self.tail.next_node is not None self.tail.next_node = self.tail.next_node.next_node self.head = self.head.next_node else: temp: Node | None = self.head for _ in range(index - 1): assert temp is not None temp = temp.next_node assert temp is not None assert temp.next_node is not None delete_node = temp.next_node temp.next_node = temp.next_node.next_node if index == len(self) - 1: self.tail = temp return delete_node.data def is_empty(self) -> bool: return len(self) == 0 def test_circular_linked_list() -> None: circular_linked_list = CircularLinkedList() assert len(circular_linked_list) == 0 assert circular_linked_list.is_empty() is True assert str(circular_linked_list) == "" try: circular_linked_list.delete_front() raise AssertionError except IndexError: assert True try: circular_linked_list.delete_tail() raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(-1) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5): assert len(circular_linked_list) == i circular_linked_list.insert_nth(i, i + 1) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) circular_linked_list.insert_tail(6) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7)) circular_linked_list.insert_head(0) assert str(circular_linked_list) == "->".join(str(i) for i in range(7)) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) assert circular_linked_list.delete_nth(2) == 3 circular_linked_list.insert_nth(2, 3) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
implementing deque using doublylinkedlist operations 1 insertion in the front o1 2 insertion in the end o1 3 remove from the front o1 4 remove from the end o1 a private class to be inherited class node slots prev data next def initself linkp element linkn self prev linkp self data element self next linkn def hasnextandprevself return f prev self prev is not none next self next is not none def initself self header self nodenone none none self trailer self nodenone none none self header next self trailer self trailer prev self header self size 0 def lenself return self size def isemptyself return self len 0 def insertself predecessor e successor create newnode by setting it s prev link header setting it s next link trailer newnode self nodepredecessor e successor predecessor next newnode successor prev newnode self size 1 return self def deleteself node predecessor node prev successor node next predecessor next successor successor prev predecessor self size 1 temp node data node prev node next node data none del node return temp class linkeddequedoublylinkedbase def firstself if self isempty raise exceptionlist is empty return self header next data def lastself if self isempty raise exceptionlist is empty return self trailer prev data deque insert operations at the front at the end def addfirstself element return self insertself header element self header next def addlastself element return self insertself trailer prev element self trailer dequeu remove operations at the front at the end def removefirstself if self isempty raise indexerrorremovefirst from empty list return self deleteself header next def removelastself if self isempty raise indexerrorremovefirst from empty list return self deleteself trailer prev a private class to be inherited create new_node by setting it s prev link header setting it s next link trailer return first element d linkeddeque d add_first a first a d add_first b first b return last element d linkeddeque d add_last a last a d add_last b last b deque insert operations at the front at the end insertion in the front linkeddeque add_first av first av insertion in the end linkeddeque add_last b last b dequeu remove operations at the front at the end removal from the front d linkeddeque d is_empty true d remove_first traceback most recent call last indexerror remove_first from empty list d add_first a doctest ellipsis data_structures linked_list deque_doubly linkeddeque object at d remove_first a d is_empty true removal in the end d linkeddeque d is_empty true d remove_last traceback most recent call last indexerror remove_first from empty list d add_first a doctest ellipsis data_structures linked_list deque_doubly linkeddeque object at d remove_last a d is_empty true
class _DoublyLinkedBase: class _Node: __slots__ = "_prev", "_data", "_next" def __init__(self, link_p, element, link_n): self._prev = link_p self._data = element self._next = link_n def has_next_and_prev(self): return ( f" Prev -> {self._prev is not None}, Next -> {self._next is not None}" ) def __init__(self): self._header = self._Node(None, None, None) self._trailer = self._Node(None, None, None) self._header._next = self._trailer self._trailer._prev = self._header self._size = 0 def __len__(self): return self._size def is_empty(self): return self.__len__() == 0 def _insert(self, predecessor, e, successor): new_node = self._Node(predecessor, e, successor) predecessor._next = new_node successor._prev = new_node self._size += 1 return self def _delete(self, node): predecessor = node._prev successor = node._next predecessor._next = successor successor._prev = predecessor self._size -= 1 temp = node._data node._prev = node._next = node._data = None del node return temp class LinkedDeque(_DoublyLinkedBase): def first(self): if self.is_empty(): raise Exception("List is empty") return self._header._next._data def last(self): if self.is_empty(): raise Exception("List is empty") return self._trailer._prev._data def add_first(self, element): return self._insert(self._header, element, self._header._next) def add_last(self, element): return self._insert(self._trailer._prev, element, self._trailer) def remove_first(self): if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._header._next) def remove_last(self): if self.is_empty(): raise IndexError("remove_first from empty list") return self._delete(self._trailer._prev)
https en wikipedia orgwikidoublylinkedlist linkedlist doublylinkedlist linkedlist insertathead b linkedlist insertathead a linkedlist insertattail c tuplelinkedlist a b c linkedlist doublylinkedlist linkedlist insertattail a linkedlist insertattail b linkedlist insertattail c strlinkedlist abc linkedlist doublylinkedlist for i in range0 5 linkedlist insertatnthi i 1 lenlinkedlist 5 true linkedlist doublylinkedlist linkedlist insertatnth1 666 traceback most recent call last indexerror list index out of range linkedlist insertatnth1 666 traceback most recent call last indexerror list index out of range linkedlist insertatnth0 2 linkedlist insertatnth0 1 linkedlist insertatnth2 4 linkedlist insertatnth2 3 strlinkedlist 1234 linkedlist insertatnth5 5 traceback most recent call last indexerror list index out of range linkedlist doublylinkedlist linkedlist deleteatnth0 traceback most recent call last indexerror list index out of range for i in range0 5 linkedlist insertatnthi i 1 linkedlist deleteatnth0 1 true linkedlist deleteatnth3 5 true linkedlist deleteatnth1 3 true strlinkedlist 24 linkedlist deleteatnth2 traceback most recent call last indexerror list index out of range linkedlist doublylinkedlist linkedlist isempty true linkedlist insertattail1 linkedlist isempty false testdoublylinkedlist linked_list doublylinkedlist linked_list insert_at_head b linked_list insert_at_head a linked_list insert_at_tail c tuple linked_list a b c linked_list doublylinkedlist linked_list insert_at_tail a linked_list insert_at_tail b linked_list insert_at_tail c str linked_list a b c linked_list doublylinkedlist for i in range 0 5 linked_list insert_at_nth i i 1 len linked_list 5 true linked_list doublylinkedlist linked_list insert_at_nth 1 666 traceback most recent call last indexerror list index out of range linked_list insert_at_nth 1 666 traceback most recent call last indexerror list index out of range linked_list insert_at_nth 0 2 linked_list insert_at_nth 0 1 linked_list insert_at_nth 2 4 linked_list insert_at_nth 2 3 str linked_list 1 2 3 4 linked_list insert_at_nth 5 5 traceback most recent call last indexerror list index out of range linked_list doublylinkedlist linked_list delete_at_nth 0 traceback most recent call last indexerror list index out of range for i in range 0 5 linked_list insert_at_nth i i 1 linked_list delete_at_nth 0 1 true linked_list delete_at_nth 3 5 true linked_list delete_at_nth 1 3 true str linked_list 2 4 linked_list delete_at_nth 2 traceback most recent call last indexerror list index out of range default first node find the position to delete we have reached the end an no value matches before 1 2 current 3 1 3 1 3 linked_list doublylinkedlist linked_list is_empty true linked_list insert_at_tail 1 linked_list is_empty false test_doubly_linked_list this should not happen this should happen this should not happen this should happen
class Node: def __init__(self, data): self.data = data self.previous = None self.next = None def __str__(self): return f"{self.data}" class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def __iter__(self): node = self.head while node: yield node.data node = node.next def __str__(self): return "->".join([str(item) for item in self]) def __len__(self): return sum(1 for _ in self) def insert_at_head(self, data): self.insert_at_nth(0, data) def insert_at_tail(self, data): self.insert_at_nth(len(self), data) def insert_at_nth(self, index: int, data): length = len(self) if not 0 <= index <= length: raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = self.tail = new_node elif index == 0: self.head.previous = new_node new_node.next = self.head self.head = new_node elif index == length: self.tail.next = new_node new_node.previous = self.tail self.tail = new_node else: temp = self.head for _ in range(index): temp = temp.next temp.previous.next = new_node new_node.previous = temp.previous new_node.next = temp temp.previous = new_node def delete_head(self): return self.delete_at_nth(0) def delete_tail(self): return self.delete_at_nth(len(self) - 1) def delete_at_nth(self, index: int): length = len(self) if not 0 <= index <= length - 1: raise IndexError("list index out of range") delete_node = self.head if length == 1: self.head = self.tail = None elif index == 0: self.head = self.head.next self.head.previous = None elif index == length - 1: delete_node = self.tail self.tail = self.tail.previous self.tail.next = None else: temp = self.head for _ in range(index): temp = temp.next delete_node = temp temp.next.previous = temp.previous temp.previous.next = temp.next return delete_node.data def delete(self, data) -> str: current = self.head while current.data != data: if current.next: current = current.next else: raise ValueError("No data matching given value") if current == self.head: self.delete_head() elif current == self.tail: self.delete_tail() else: current.previous.next = current.next current.next.previous = current.previous return data def is_empty(self): return len(self) == 0 def test_doubly_linked_list() -> None: linked_list = DoublyLinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() raise AssertionError except IndexError: assert True try: linked_list.delete_tail() raise AssertionError except IndexError: assert True for i in range(10): assert len(linked_list) == i linked_list.insert_at_nth(i, i + 1) assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) linked_list.insert_at_head(0) linked_list.insert_at_tail(11) assert str(linked_list) == "->".join(str(i) for i in range(12)) assert linked_list.delete_head() == 0 assert linked_list.delete_at_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) if __name__ == "__main__": from doctest import testmod testmod()
floyd s cycle detection algorithm is a popular algorithm used to detect cycles in a linked list it uses two pointers a slow pointer and a fast pointer to traverse the linked list the slow pointer moves one node at a time while the fast pointer moves two nodes at a time if there is a cycle in the linked list the fast pointer will eventually catch up to the slow pointer and they will meet at the same node if there is no cycle the fast pointer will reach the end of the linked list and the algorithm will terminate for more information https en wikipedia orgwikicycledetectionfloyd stortoiseandhare a class representing a node in a singly linked list a class representing a singly linked list iterates through the linked list returns iterator an iterator over the linked list examples linkedlist linkedlist listlinkedlist linkedlist addnode1 tuplelinkedlist 1 avoid infinite loop in there s a cycle adds a new node to the end of the linked list args data any the data to be stored in the new node examples linkedlist linkedlist linkedlist addnode1 linkedlist addnode2 linkedlist addnode3 linkedlist addnode4 tuplelinkedlist 1 2 3 4 detects if there is a cycle in the linked list using floyd s cycle detection algorithm returns bool true if there is a cycle false otherwise examples linkedlist linkedlist linkedlist addnode1 linkedlist addnode2 linkedlist addnode3 linkedlist addnode4 linkedlist detectcycle false create a cycle in the linked list linkedlist head nextnode nextnode nextnode linkedlist head nextnode linkedlist detectcycle true create a cycle in the linked list it first checks if the head nextnode and nextnode nextnode attributes of the linked list are not none to avoid any potential type errors a class representing a node in a singly linked list a class representing a singly linked list iterates through the linked list returns iterator an iterator over the linked list examples linked_list linkedlist list linked_list linked_list add_node 1 tuple linked_list 1 avoid infinite loop in there s a cycle adds a new node to the end of the linked list args data any the data to be stored in the new node examples linked_list linkedlist linked_list add_node 1 linked_list add_node 2 linked_list add_node 3 linked_list add_node 4 tuple linked_list 1 2 3 4 detects if there is a cycle in the linked list using floyd s cycle detection algorithm returns bool true if there is a cycle false otherwise examples linked_list linkedlist linked_list add_node 1 linked_list add_node 2 linked_list add_node 3 linked_list add_node 4 linked_list detect_cycle false create a cycle in the linked list linked_list head next_node next_node next_node linked_list head next_node linked_list detect_cycle true create a cycle in the linked list it first checks if the head next_node and next_node next_node attributes of the linked list are not none to avoid any potential type errors output true
from collections.abc import Iterator from dataclasses import dataclass from typing import Any, Self @dataclass class Node: data: Any next_node: Self | None = None @dataclass class LinkedList: head: Node | None = None def __iter__(self) -> Iterator: visited = [] node = self.head while node: if node in visited: return visited.append(node) yield node.data node = node.next_node def add_node(self, data: Any) -> None: new_node = Node(data) if self.head is None: self.head = new_node return current_node = self.head while current_node.next_node is not None: current_node = current_node.next_node current_node.next_node = new_node def detect_cycle(self) -> bool: if self.head is None: return False slow_pointer: Node | None = self.head fast_pointer: Node | None = self.head while fast_pointer is not None and fast_pointer.next_node is not None: slow_pointer = slow_pointer.next_node if slow_pointer else None fast_pointer = fast_pointer.next_node.next_node if slow_pointer == fast_pointer: return True return False if __name__ == "__main__": import doctest doctest.testmod() linked_list = LinkedList() linked_list.add_node(1) linked_list.add_node(2) linked_list.add_node(3) linked_list.add_node(4) if ( linked_list.head and linked_list.head.next_node and linked_list.head.next_node.next_node ): linked_list.head.next_node.next_node.next_node = linked_list.head.next_node has_cycle = linked_list.detect_cycle() print(has_cycle)
recursive prorgam to create a linked list from a sequence and print a string representation of it returns a visual representation of the node and all its following nodes stringrep temp self while temp stringrep ftemp data temp temp next stringrep end return stringrep def makelinkedlistelementslist if elementslist is empty set first element as head loop through elements from position 1 recursive prorgam to create a linked list from a sequence and print a string representation of it returns a visual representation of the node and all its following nodes creates a linked list from the elements of the given sequence list tuple and returns the head of the linked list if elements_list is empty set first element as head loop through elements from position 1
class Node: def __init__(self, data=None): self.data = data self.next = None def __repr__(self): string_rep = "" temp = self while temp: string_rep += f"<{temp.data}> ---> " temp = temp.next string_rep += "<END>" return string_rep def make_linked_list(elements_list): if not elements_list: raise Exception("The Elements List is empty") head = Node(elements_list[0]) current = head for data in elements_list[1:]: current.next = Node(data) current = current.next return head list_data = [1, 3, 5, 32, 44, 12, 43] print(f"List: {list_data}") print("Creating Linked List from List.") linked_list = make_linked_list(list_data) print("Linked List:") print(linked_list)
a loop is when the exact same node appears more than once in a linked list rootnode node1 rootnode nextnode node2 rootnode nextnode nextnode node3 rootnode nextnode nextnode nextnode node4 rootnode hasloop false rootnode nextnode nextnode nextnode rootnode nextnode rootnode hasloop true a loop is when the exact same node appears more than once in a linked list root_node node 1 root_node next_node node 2 root_node next_node next_node node 3 root_node next_node next_node next_node node 4 root_node has_loop false root_node next_node next_node next_node root_node next_node root_node has_loop true false true false false
from __future__ import annotations from typing import Any class ContainsLoopError(Exception): pass class Node: def __init__(self, data: Any) -> None: self.data: Any = data self.next_node: Node | None = None def __iter__(self): node = self visited = [] while node: if node in visited: raise ContainsLoopError visited.append(node) yield node.data node = node.next_node @property def has_loop(self) -> bool: try: list(self) return False except ContainsLoopError: return True if __name__ == "__main__": root_node = Node(1) root_node.next_node = Node(2) root_node.next_node.next_node = Node(3) root_node.next_node.next_node.next_node = Node(4) print(root_node.has_loop) root_node.next_node.next_node.next_node = root_node.next_node print(root_node.has_loop) root_node = Node(5) root_node.next_node = Node(6) root_node.next_node.next_node = Node(5) root_node.next_node.next_node.next_node = Node(6) print(root_node.has_loop) root_node = Node(1) print(root_node.has_loop)
check if a linked list is a palindrome args head the head of the linked list returns bool true if the linked list is a palindrome false otherwise examples ispalindromenone true ispalindromelistnode1 true ispalindromelistnode1 listnode2 false ispalindromelistnode1 listnode2 listnode1 true ispalindromelistnode1 listnode2 listnode2 listnode1 true split the list to two parts slow will always be defined adding this check to resolve mypy static check reverse the second part compare two parts second part has the same or one less node check if a linked list is a palindrome using a stack args head listnode the head of the linked list returns bool true if the linked list is a palindrome false otherwise examples ispalindromestacknone true ispalindromestacklistnode1 true ispalindromestacklistnode1 listnode2 false ispalindromestacklistnode1 listnode2 listnode1 true ispalindromestacklistnode1 listnode2 listnode2 listnode1 true 1 get the midpoint slow slow will always be defined adding this check to resolve mypy static check 2 push the second half into the stack 3 comparison check if a linked list is a palindrome using a dictionary args head listnode the head of the linked list returns bool true if the linked list is a palindrome false otherwise examples ispalindromedictnone true ispalindromedictlistnode1 true ispalindromedictlistnode1 listnode2 false ispalindromedictlistnode1 listnode2 listnode1 true ispalindromedictlistnode1 listnode2 listnode2 listnode1 true ispalindromedict listnode 1 listnode2 listnode1 listnode3 listnode2 listnode1 false check if a linked list is a palindrome args head the head of the linked list returns bool true if the linked list is a palindrome false otherwise examples is_palindrome none true is_palindrome listnode 1 true is_palindrome listnode 1 listnode 2 false is_palindrome listnode 1 listnode 2 listnode 1 true is_palindrome listnode 1 listnode 2 listnode 2 listnode 1 true split the list to two parts slow will always be defined adding this check to resolve mypy static check don t forget here but forget still works reverse the second part compare two parts second part has the same or one less node check if a linked list is a palindrome using a stack args head listnode the head of the linked list returns bool true if the linked list is a palindrome false otherwise examples is_palindrome_stack none true is_palindrome_stack listnode 1 true is_palindrome_stack listnode 1 listnode 2 false is_palindrome_stack listnode 1 listnode 2 listnode 1 true is_palindrome_stack listnode 1 listnode 2 listnode 2 listnode 1 true 1 get the midpoint slow slow will always be defined adding this check to resolve mypy static check 2 push the second half into the stack 3 comparison check if a linked list is a palindrome using a dictionary args head listnode the head of the linked list returns bool true if the linked list is a palindrome false otherwise examples is_palindrome_dict none true is_palindrome_dict listnode 1 true is_palindrome_dict listnode 1 listnode 2 false is_palindrome_dict listnode 1 listnode 2 listnode 1 true is_palindrome_dict listnode 1 listnode 2 listnode 2 listnode 1 true is_palindrome_dict listnode 1 listnode 2 listnode 1 listnode 3 listnode 2 listnode 1 false
from __future__ import annotations from dataclasses import dataclass @dataclass class ListNode: val: int = 0 next_node: ListNode | None = None def is_palindrome(head: ListNode | None) -> bool: if not head: return True fast: ListNode | None = head.next_node slow: ListNode | None = head while fast and fast.next_node: fast = fast.next_node.next_node slow = slow.next_node if slow else None if slow: second = slow.next_node slow.next_node = None node: ListNode | None = None while second: nxt = second.next_node second.next_node = node node = second second = nxt while node and head: if node.val != head.val: return False node = node.next_node head = head.next_node return True def is_palindrome_stack(head: ListNode | None) -> bool: if not head or not head.next_node: return True slow: ListNode | None = head fast: ListNode | None = head while fast and fast.next_node: fast = fast.next_node.next_node slow = slow.next_node if slow else None if slow: stack = [slow.val] while slow.next_node: slow = slow.next_node stack.append(slow.val) cur: ListNode | None = head while stack and cur: if stack.pop() != cur.val: return False cur = cur.next_node return True def is_palindrome_dict(head: ListNode | None) -> bool: if not head or not head.next_node: return True d: dict[int, list[int]] = {} pos = 0 while head: if head.val in d: d[head.val].append(pos) else: d[head.val] = [pos] head = head.next_node pos += 1 checksum = pos - 1 middle = 0 for v in d.values(): if len(v) % 2 != 0: middle += 1 else: step = 0 for i in range(len(v)): if v[i] + v[len(v) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True if __name__ == "__main__": import doctest doctest.testmod()
algorithm that merges two sorted linked lists into one sorted linked list tuplesortedlinkedlisttestdataodd tuplesortedtestdataodd true tuplesortedlinkedlisttestdataeven tuplesortedtestdataeven true for i in range3 lensortedlinkedlistrangei i true true true lensortedlinkedlisttestdataodd 8 strsortedlinkedlist strsortedlinkedlisttestdataodd 11 1 0 1 3 5 7 9 strsortedlinkedlisttestdataeven 2 0 2 3 4 6 8 10 ssl sortedlinkedlist merged mergelistsssltestdataodd ssltestdataeven lenmerged 16 strmerged 11 2 1 0 0 1 2 3 3 4 5 6 7 8 9 10 listmerged listsortedtestdataodd testdataeven true tuple sortedlinkedlist test_data_odd tuple sorted test_data_odd true tuple sortedlinkedlist test_data_even tuple sorted test_data_even true for i in range 3 len sortedlinkedlist range i i true true true len sortedlinkedlist test_data_odd 8 str sortedlinkedlist str sortedlinkedlist test_data_odd 11 1 0 1 3 5 7 9 str sortedlinkedlist test_data_even 2 0 2 3 4 6 8 10 ssl sortedlinkedlist merged merge_lists ssl test_data_odd ssl test_data_even len merged 16 str merged 11 2 1 0 0 1 2 3 3 4 5 6 7 8 9 10 list merged list sorted test_data_odd test_data_even true
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1) test_data_even = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class Node: data: int next_node: Node | None class SortedLinkedList: def __init__(self, ints: Iterable[int]) -> None: self.head: Node | None = None for i in sorted(ints, reverse=True): self.head = Node(i, self.head) def __iter__(self) -> Iterator[int]: node = self.head while node: yield node.data node = node.next_node def __len__(self) -> int: return sum(1 for _ in self) def __str__(self) -> str: return " -> ".join([str(node) for node in self]) def merge_lists( sll_one: SortedLinkedList, sll_two: SortedLinkedList ) -> SortedLinkedList: return SortedLinkedList(list(sll_one) + list(sll_two)) if __name__ == "__main__": import doctest doctest.testmod() SSL = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
link linkedlist link middleelement no element found link push5 5 link push6 6 link push8 8 link push8 8 link push10 10 link push12 12 link push17 17 link push7 7 link push3 3 link push20 20 link push20 20 link middleelement 12 link linkedlist link middle_element no element found link push 5 5 link push 6 6 link push 8 8 link push 8 8 link push 10 10 link push 12 12 link push 17 17 link push 7 7 link push 3 3 link push 20 20 link push 20 20 link middle_element 12
from __future__ import annotations class Node: def __init__(self, data: int) -> None: self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data: int) -> int: new_node = Node(new_data) new_node.next = self.head self.head = new_node return self.head.data def middle_element(self) -> int | None: slow_pointer = self.head fast_pointer = self.head if self.head: while fast_pointer and fast_pointer.next: fast_pointer = fast_pointer.next.next slow_pointer = slow_pointer.next return slow_pointer.data else: print("No element found.") return None if __name__ == "__main__": link = LinkedList() for _ in range(int(input().strip())): data = int(input().strip()) link.push(data) print(link.middle_element())
a class to represent a linked list use a tail pointer to speed up the append operation initialize a linkedlist with the head node set to none linkedlist linkedlist linkedlist head linkedlist tail none none iterate the linkedlist yielding each node s data linkedlist linkedlist items 1 2 3 4 5 linkedlist extenditems tuplelinkedlist items true returns a string representation of the linkedlist linkedlist linkedlist strlinkedlist linkedlist append1 strlinkedlist 1 linkedlist extend2 3 4 5 strlinkedlist 1 2 3 4 5 appends a new node with the given data to the end of the linkedlist linkedlist linkedlist strlinkedlist linkedlist append1 strlinkedlist 1 linkedlist append2 strlinkedlist 1 2 appends each item to the end of the linkedlist linkedlist linkedlist linkedlist extend strlinkedlist linkedlist extend1 2 strlinkedlist 1 2 linkedlist extend3 4 strlinkedlist 1 2 3 4 creates a linked list from the elements of the given sequence listtuple and returns the head of the linked list makelinkedlist traceback most recent call last exception the elements list is empty makelinkedlist7 7 makelinkedlist abc abc makelinkedlist7 25 7 25 prints the elements of the given linked list in reverse order inreverselinkedlist inreversemakelinkedlist69 88 73 73 88 69 a class to represent a linked list use a tail pointer to speed up the append operation initialize a linkedlist with the head node set to none linked_list linkedlist linked_list head linked_list tail none none speeds up the append operation iterate the linkedlist yielding each node s data linked_list linkedlist items 1 2 3 4 5 linked_list extend items tuple linked_list items true returns a string representation of the linkedlist linked_list linkedlist str linked_list linked_list append 1 str linked_list 1 linked_list extend 2 3 4 5 str linked_list 1 2 3 4 5 appends a new node with the given data to the end of the linkedlist linked_list linkedlist str linked_list linked_list append 1 str linked_list 1 linked_list append 2 str linked_list 1 2 appends each item to the end of the linkedlist linked_list linkedlist linked_list extend str linked_list linked_list extend 1 2 str linked_list 1 2 linked_list extend 3 4 str linked_list 1 2 3 4 creates a linked list from the elements of the given sequence list tuple and returns the head of the linked list make_linked_list traceback most recent call last exception the elements list is empty make_linked_list 7 7 make_linked_list abc abc make_linked_list 7 25 7 25 prints the elements of the given linked list in reverse order in_reverse linkedlist in_reverse make_linked_list 69 88 73 73 88 69
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass @dataclass class Node: data: int next_node: Node | None = None class LinkedList: def __init__(self) -> None: self.head: Node | None = None self.tail: Node | None = None def __iter__(self) -> Iterator[int]: node = self.head while node: yield node.data node = node.next_node def __repr__(self) -> str: return " -> ".join([str(data) for data in self]) def append(self, data: int) -> None: if self.tail: self.tail.next_node = self.tail = Node(data) else: self.head = self.tail = Node(data) def extend(self, items: Iterable[int]) -> None: for item in items: self.append(item) def make_linked_list(elements_list: Iterable[int]) -> LinkedList: if not elements_list: raise Exception("The Elements List is empty") linked_list = LinkedList() linked_list.extend(elements_list) return linked_list def in_reverse(linked_list: LinkedList) -> str: return " <- ".join(str(line) for line in reversed(tuple(linked_list))) if __name__ == "__main__": from doctest import testmod testmod() linked_list = make_linked_list((14, 52, 14, 12, 43)) print(f"Linked List: {linked_list}") print(f"Reverse List: {in_reverse(linked_list)}")
ints listlinkedlistints ints true ints tuplerange5 tuplelinkedlistints ints true for i in range3 lenlinkedlistrangei i true true true lenlinkedlistabcdefgh 8 strlinkedlist strlinkedlistrange5 0 1 2 3 4 ll linkedlist1 2 tuplell 1 2 ll append3 tuplell 1 2 3 ll append4 tuplell 1 2 3 4 lenll 4 reverse nodes within groups of size k ll linkedlist1 2 3 4 5 ll reverseknodes2 tuplell 2 1 4 3 5 strll 2 1 4 3 5 ints list linkedlist ints ints true ints tuple range 5 tuple linkedlist ints ints true for i in range 3 len linkedlist range i i true true true len linkedlist abcdefgh 8 str linkedlist str linkedlist range 5 0 1 2 3 4 ll linkedlist 1 2 tuple ll 1 2 ll append 3 tuple ll 1 2 3 ll append 4 tuple ll 1 2 3 4 len ll 4 reverse nodes within groups of size k ll linkedlist 1 2 3 4 5 ll reverse_k_nodes 2 tuple ll 2 1 4 3 5 str ll 2 1 4 3 5
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass @dataclass class Node: data: int next_node: Node | None = None class LinkedList: def __init__(self, ints: Iterable[int]) -> None: self.head: Node | None = None for i in ints: self.append(i) def __iter__(self) -> Iterator[int]: node = self.head while node: yield node.data node = node.next_node def __len__(self) -> int: return sum(1 for _ in self) def __str__(self) -> str: return " -> ".join([str(node) for node in self]) def append(self, data: int) -> None: if not self.head: self.head = Node(data) return node = self.head while node.next_node: node = node.next_node node.next_node = Node(data) def reverse_k_nodes(self, group_size: int) -> None: if self.head is None or self.head.next_node is None: return length = len(self) dummy_head = Node(0) dummy_head.next_node = self.head previous_node = dummy_head while length >= group_size: current_node = previous_node.next_node assert current_node next_node = current_node.next_node for _ in range(1, group_size): assert next_node, current_node current_node.next_node = next_node.next_node assert previous_node next_node.next_node = previous_node.next_node previous_node.next_node = next_node next_node = current_node.next_node previous_node = current_node length -= group_size self.head = dummy_head.next_node if __name__ == "__main__": import doctest doctest.testmod() ll = LinkedList([1, 2, 3, 4, 5]) print(f"Original Linked List: {ll}") k = 2 ll.reverse_k_nodes(k) print(f"After reversing groups of size {k}: {ll}")
print the entire linked list iteratively this function prints the elements of a linked list separated by parameters head node none the head of the linked list to be printed or none if the linked list is empty head insertnodenone 0 head insertnodehead 2 head insertnodehead 1 printlinkedlisthead 021 head insertnodehead 4 head insertnodehead 5 printlinkedlisthead 02145 insert a new node at the end of a linked list and return the new head parameters head node none the head of the linked list data int the data to be inserted into the new node returns node the new head of the linked list head insertnodenone 10 head insertnodehead 9 head insertnodehead 8 printlinkedlisthead 1098 if the linked list is empty the newnode becomes the head rotate a linked list to the right by places times parameters head the head of the linked list places the number of places to rotate returns node the head of the rotated linked list rotatetotherightnone places1 traceback most recent call last valueerror the linked list is empty head insertnodenone 1 rotatetotherighthead places1 head true head insertnodenone 1 head insertnodehead 2 head insertnodehead 3 head insertnodehead 4 head insertnodehead 5 newhead rotatetotherighthead places2 printlinkedlistnewhead 45123 check if the list is empty or has only one element calculate the length of the linked list adjust the value of places to avoid places longer than the list find the new head position after rotation traverse to the new head position update pointers to perform rotation print the entire linked list iteratively this function prints the elements of a linked list separated by parameters head node none the head of the linked list to be printed or none if the linked list is empty head insert_node none 0 head insert_node head 2 head insert_node head 1 print_linked_list head 0 2 1 head insert_node head 4 head insert_node head 5 print_linked_list head 0 2 1 4 5 insert a new node at the end of a linked list and return the new head parameters head node none the head of the linked list data int the data to be inserted into the new node returns node the new head of the linked list head insert_node none 10 head insert_node head 9 head insert_node head 8 print_linked_list head 10 9 8 if the linked list is empty the new_node becomes the head type ignore rotate a linked list to the right by places times parameters head the head of the linked list places the number of places to rotate returns node the head of the rotated linked list rotate_to_the_right none places 1 traceback most recent call last valueerror the linked list is empty head insert_node none 1 rotate_to_the_right head places 1 head true head insert_node none 1 head insert_node head 2 head insert_node head 3 head insert_node head 4 head insert_node head 5 new_head rotate_to_the_right head places 2 print_linked_list new_head 4 5 1 2 3 check if the list is empty or has only one element calculate the length of the linked list adjust the value of places to avoid places longer than the list as no rotation is needed find the new head position after rotation traverse to the new head position update pointers to perform rotation
from __future__ import annotations from dataclasses import dataclass @dataclass class Node: data: int next_node: Node | None = None def print_linked_list(head: Node | None) -> None: if head is None: return while head.next_node is not None: print(head.data, end="->") head = head.next_node print(head.data) def insert_node(head: Node | None, data: int) -> Node: new_node = Node(data) if head is None: return new_node temp_node = head while temp_node.next_node: temp_node = temp_node.next_node temp_node.next_node = new_node return head def rotate_to_the_right(head: Node, places: int) -> Node: if not head: raise ValueError("The linked list is empty.") if head.next_node is None: return head length = 1 temp_node = head while temp_node.next_node is not None: length += 1 temp_node = temp_node.next_node places %= length if places == 0: return head new_head_index = length - places temp_node = head for _ in range(new_head_index - 1): assert temp_node.next_node temp_node = temp_node.next_node assert temp_node.next_node new_head = temp_node.next_node temp_node.next_node = None temp_node = new_head while temp_node.next_node: temp_node = temp_node.next_node temp_node.next_node = head assert new_head return new_head if __name__ == "__main__": import doctest doctest.testmod() head = insert_node(None, 5) head = insert_node(head, 1) head = insert_node(head, 2) head = insert_node(head, 4) head = insert_node(head, 3) print("Original list: ", end="") print_linked_list(head) places = 3 new_head = rotate_to_the_right(head, places) print(f"After {places} iterations: ", end="") print_linked_list(new_head)
create and initialize node class instance node20 node20 nodehello world nodehello world nodenone nodenone nodetrue nodetrue get the string representation of this node node10 repr node10 reprnode10 node10 strnode10 node10 node10 node10 create and initialize linkedlist class instance linkedlist linkedlist linkedlist head is none true this function is intended for iterators to access and iterate through data inside linked list linkedlist linkedlist linkedlist inserttailtail linkedlist inserttailtail1 linkedlist inserttailtail2 for node in linkedlist iter used here node tail tail1 tail2 return length of linked list i e number of nodes linkedlist linkedlist lenlinkedlist 0 linkedlist inserttailtail lenlinkedlist 1 linkedlist insertheadhead lenlinkedlist 2 linkedlist deletetail lenlinkedlist 1 linkedlist deletehead lenlinkedlist 0 string representationvisualization of a linked lists linkedlist linkedlist linkedlist inserttail1 linkedlist inserttail3 linkedlist repr 1 3 reprlinkedlist 1 3 strlinkedlist 1 3 linkedlist inserttail5 flinkedlist 1 3 5 indexing support used to get a node at particular position linkedlist linkedlist for i in range0 10 linkedlist insertnthi i allstrlinkedlisti stri for i in range0 10 true linkedlist10 traceback most recent call last valueerror list index out of range linkedlistlenlinkedlist traceback most recent call last valueerror list index out of range used to change the data of a particular node linkedlist linkedlist for i in range0 10 linkedlist insertnthi i linkedlist0 666 linkedlist0 666 linkedlist5 666 linkedlist5 666 linkedlist10 666 traceback most recent call last valueerror list index out of range linkedlistlenlinkedlist 666 traceback most recent call last valueerror list index out of range insert data to the end of linked list linkedlist linkedlist linkedlist inserttailtail linkedlist tail linkedlist inserttailtail2 linkedlist tail tail2 linkedlist inserttailtail3 linkedlist tail tail2 tail3 insert data to the beginning of linked list linkedlist linkedlist linkedlist insertheadhead linkedlist head linkedlist insertheadhead2 linkedlist head2 head linkedlist insertheadhead3 linkedlist head3 head2 head insert data at given index linkedlist linkedlist linkedlist inserttailfirst linkedlist inserttailsecond linkedlist inserttailthird linkedlist first second third linkedlist insertnth1 fourth linkedlist first fourth second third linkedlist insertnth3 fifth linkedlist first fourth second fifth third this method prints every node data linkedlist linkedlist linkedlist inserttailfirst linkedlist inserttailsecond linkedlist inserttailthird linkedlist first second third delete the first node and return the node s data linkedlist linkedlist linkedlist inserttailfirst linkedlist inserttailsecond linkedlist inserttailthird linkedlist first second third linkedlist deletehead first linkedlist second third linkedlist deletehead second linkedlist third linkedlist deletehead third linkedlist deletehead traceback most recent call last indexerror list index out of range delete the tail end node and return the node s data linkedlist linkedlist linkedlist inserttailfirst linkedlist inserttailsecond linkedlist inserttailthird linkedlist first second third linkedlist deletetail third linkedlist first second linkedlist deletetail second linkedlist first linkedlist deletetail first linkedlist deletetail traceback most recent call last indexerror list index out of range delete node at given index and return the node s data linkedlist linkedlist linkedlist inserttailfirst linkedlist inserttailsecond linkedlist inserttailthird linkedlist first second third linkedlist deletenth1 delete middle second linkedlist first third linkedlist deletenth5 this raises error traceback most recent call last indexerror list index out of range linkedlist deletenth1 this also raises error traceback most recent call last indexerror list index out of range check if linked list is empty linkedlist linkedlist linkedlist isempty true linkedlist insertheadfirst linkedlist isempty false this reverses the linked list order linkedlist linkedlist linkedlist inserttailfirst linkedlist inserttailsecond linkedlist inserttailthird linkedlist first second third linkedlist reverse linkedlist third second first store the current node s next node make the current node s nextnode point backwards make the previous node be the current node make the current node the nextnode node to progress iteration return prev in order to put the head at the end testsinglylinkedlist this section of the test used varying data types for input testsinglylinkedlist2 check if it s empty or not delete the head delete the tail delete a node in specific location in linked list add a node instance to its head add none to its tail reverse the linked list create and initialize node class instance node 20 node 20 node hello world node hello world node none node none node true node true get the string representation of this node node 10 __repr__ node 10 repr node 10 node 10 str node 10 node 10 node 10 node 10 create and initialize linkedlist class instance linked_list linkedlist linked_list head is none true this function is intended for iterators to access and iterate through data inside linked list linked_list linkedlist linked_list insert_tail tail linked_list insert_tail tail_1 linked_list insert_tail tail_2 for node in linked_list __iter__ used here node tail tail_1 tail_2 return length of linked list i e number of nodes linked_list linkedlist len linked_list 0 linked_list insert_tail tail len linked_list 1 linked_list insert_head head len linked_list 2 _ linked_list delete_tail len linked_list 1 _ linked_list delete_head len linked_list 0 string representation visualization of a linked lists linked_list linkedlist linked_list insert_tail 1 linked_list insert_tail 3 linked_list __repr__ 1 3 repr linked_list 1 3 str linked_list 1 3 linked_list insert_tail 5 f linked_list 1 3 5 indexing support used to get a node at particular position linked_list linkedlist for i in range 0 10 linked_list insert_nth i i all str linked_list i str i for i in range 0 10 true linked_list 10 traceback most recent call last valueerror list index out of range linked_list len linked_list traceback most recent call last valueerror list index out of range used to change the data of a particular node linked_list linkedlist for i in range 0 10 linked_list insert_nth i i linked_list 0 666 linked_list 0 666 linked_list 5 666 linked_list 5 666 linked_list 10 666 traceback most recent call last valueerror list index out of range linked_list len linked_list 666 traceback most recent call last valueerror list index out of range insert data to the end of linked list linked_list linkedlist linked_list insert_tail tail linked_list tail linked_list insert_tail tail_2 linked_list tail tail_2 linked_list insert_tail tail_3 linked_list tail tail_2 tail_3 insert data to the beginning of linked list linked_list linkedlist linked_list insert_head head linked_list head linked_list insert_head head_2 linked_list head_2 head linked_list insert_head head_3 linked_list head_3 head_2 head insert data at given index linked_list linkedlist linked_list insert_tail first linked_list insert_tail second linked_list insert_tail third linked_list first second third linked_list insert_nth 1 fourth linked_list first fourth second third linked_list insert_nth 3 fifth linked_list first fourth second fifth third link new_node to head print every node data this method prints every node data linked_list linkedlist linked_list insert_tail first linked_list insert_tail second linked_list insert_tail third linked_list first second third delete the first node and return the node s data linked_list linkedlist linked_list insert_tail first linked_list insert_tail second linked_list insert_tail third linked_list first second third linked_list delete_head first linked_list second third linked_list delete_head second linked_list third linked_list delete_head third linked_list delete_head traceback most recent call last indexerror list index out of range delete from tail delete the tail end node and return the node s data linked_list linkedlist linked_list insert_tail first linked_list insert_tail second linked_list insert_tail third linked_list first second third linked_list delete_tail third linked_list first second linked_list delete_tail second linked_list first linked_list delete_tail first linked_list delete_tail traceback most recent call last indexerror list index out of range delete node at given index and return the node s data linked_list linkedlist linked_list insert_tail first linked_list insert_tail second linked_list insert_tail third linked_list first second third linked_list delete_nth 1 delete middle second linked_list first third linked_list delete_nth 5 this raises error traceback most recent call last indexerror list index out of range linked_list delete_nth 1 this also raises error traceback most recent call last indexerror list index out of range test if index is valid default first node check if linked list is empty linked_list linkedlist linked_list is_empty true linked_list insert_head first linked_list is_empty false this reverses the linked list order linked_list linkedlist linked_list insert_tail first linked_list insert_tail second linked_list insert_tail third linked_list first second third linked_list reverse linked_list third second first store the current node s next node make the current node s next_node point backwards make the previous node be the current node make the current node the next_node node to progress iteration return prev in order to put the head at the end test_singly_linked_list this should not happen this should happen this should not happen this should happen this section of the test used varying data types for input test_singly_linked_list_2 check if it s empty or not delete the head delete the tail delete a node in specific location in linked list add a node instance to its head add none to its tail reverse the linked list
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass from typing import Any @dataclass class Node: data: Any next_node: Node | None = None def __repr__(self) -> str: return f"Node({self.data})" class LinkedList: def __init__(self): self.head = None def __iter__(self) -> Iterator[Any]: node = self.head while node: yield node.data node = node.next_node def __len__(self) -> int: return sum(1 for _ in self) def __repr__(self) -> str: return " -> ".join([str(item) for item in self]) def __getitem__(self, index: int) -> Any: if not 0 <= index < len(self): raise ValueError("list index out of range.") for i, node in enumerate(self): if i == index: return node return None def __setitem__(self, index: int, data: Any) -> None: if not 0 <= index < len(self): raise ValueError("list index out of range.") current = self.head for _ in range(index): current = current.next_node current.data = data def insert_tail(self, data: Any) -> None: self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: if not 0 <= index <= len(self): raise IndexError("list index out of range") new_node = Node(data) if self.head is None: self.head = new_node elif index == 0: new_node.next_node = self.head self.head = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next_node new_node.next_node = temp.next_node temp.next_node = new_node def print_list(self) -> None: print(self) def delete_head(self) -> Any: return self.delete_nth(0) def delete_tail(self) -> Any: return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: if not 0 <= index <= len(self) - 1: raise IndexError("List index out of range.") delete_node = self.head if index == 0: self.head = self.head.next_node else: temp = self.head for _ in range(index - 1): temp = temp.next_node delete_node = temp.next_node temp.next_node = temp.next_node.next_node return delete_node.data def is_empty(self) -> bool: return self.head is None def reverse(self) -> None: prev = None current = self.head while current: next_node = current.next_node current.next_node = prev prev = current current = next_node self.head = prev def test_singly_linked_list() -> None: linked_list = LinkedList() assert linked_list.is_empty() is True assert str(linked_list) == "" try: linked_list.delete_head() raise AssertionError except IndexError: assert True try: linked_list.delete_tail() raise AssertionError except IndexError: assert True for i in range(10): assert len(linked_list) == i linked_list.insert_nth(i, i + 1) assert str(linked_list) == " -> ".join(str(i) for i in range(1, 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(linked_list) == " -> ".join(str(i) for i in range(12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(linked_list) == 9 assert str(linked_list) == " -> ".join(str(i) for i in range(1, 10)) assert all(linked_list[i] == i + 1 for i in range(9)) is True for i in range(9): linked_list[i] = -i assert all(linked_list[i] == -i for i in range(9)) is True linked_list.reverse() assert str(linked_list) == " -> ".join(str(i) for i in range(-8, 1)) def test_singly_linked_list_2() -> None: test_input = [ -9, 100, Node(77345112), "dlrow olleH", 7, 5555, 0, -192.55555, "Hello, world!", 77.9, Node(10), None, None, 12.20, ] linked_list = LinkedList() for i in test_input: linked_list.insert_tail(i) assert linked_list.is_empty() is False assert ( str(linked_list) == "-9 -> 100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> " "0 -> -192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None -> 12.2" ) result = linked_list.delete_head() assert result == -9 assert ( str(linked_list) == "100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> 0 -> " "-192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None -> 12.2" ) result = linked_list.delete_tail() assert result == 12.2 assert ( str(linked_list) == "100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> 0 -> " "-192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None" ) result = linked_list.delete_nth(10) assert result is None assert ( str(linked_list) == "100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> 0 -> " "-192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None" ) linked_list.insert_head(Node("Hello again, world!")) assert ( str(linked_list) == "Node(Hello again, world!) -> 100 -> Node(77345112) -> dlrow olleH -> " "7 -> 5555 -> 0 -> -192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None" ) linked_list.insert_tail(None) assert ( str(linked_list) == "Node(Hello again, world!) -> 100 -> Node(77345112) -> dlrow olleH -> 7 -> " "5555 -> 0 -> -192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None" ) linked_list.reverse() assert ( str(linked_list) == "None -> None -> Node(10) -> 77.9 -> Hello, world! -> -192.55555 -> 0 -> " "5555 -> 7 -> dlrow olleH -> Node(77345112) -> 100 -> Node(Hello again, world!)" ) def main(): from doctest import testmod testmod() linked_list = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(linked_list) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") linked_list[1] = input("Enter New Value: ").strip() print("New list:") print(linked_list) print(f"length of linked_list is : {len(linked_list)}") if __name__ == "__main__": main()
based on skip lists a probabilistic alternative to balanced trees by william pugh https epaperpress comsortsearchdownloadskiplist pdf return visual representation of node node nodekey 2 reprnode nodekey 2 return number of forward references node nodekey 2 node level 0 node forward appendnodekey2 4 node level 1 node forward appendnodekey3 6 node level 2 return visual representation of skiplist skiplist skiplist printskiplist skiplistlevel0 skiplist insertkey1 value printskiplist doctest ellipsis skiplistlevel root key1key1 none skiplist insertkey2 othervalue printskiplist doctest ellipsis skiplistlevel root key1key1 key2key2 none return random level from 1 self maxlevel interval higher values are less likely param key searched key return tuple with searched node or none if given key is not present and list of nodes that refer if key is present of should refer to given node nodes with refer or should refer to output node i node level when node level is lesser than i decrement i node forwardi key key jumping to node with key value higher or equal to searched key would result in skipping searched key each leftmost node relative to searched node will potentially have to be updated lennode forward 0 if current node doesn t contain any further references then searched key is not present node forward0 key key next node key should be equal to search key if key is present param key key to remove from list skiplist skiplist skiplist insert2 two skiplist insert1 one skiplist insert3 three listskiplist 1 2 3 skiplist delete2 listskiplist 1 3 remove or replace all references to removed node param key key to insert param value value associated with given key skiplist skiplist skiplist insert2 two skiplist find2 two listskiplist 2 after level increase we have to add additional nodes to head change references to pass through new node param key search key return value associated with given key or none if given key is not present skiplist skiplist skiplist find2 skiplist insert2 two skiplist find2 two skiplist insert2 three skiplist find2 three repeat test 100 times due to the probabilistic nature of skip list random values random bugs pytests return visual representation of node node node key 2 repr node node key 2 return number of forward references node node key 2 node level 0 node forward append node key2 4 node level 1 node forward append node key3 6 node level 2 return visual representation of skiplist skip_list skiplist print skip_list skiplist level 0 skip_list insert key1 value print skip_list doctest ellipsis skiplist level root key1 key1 none skip_list insert key2 othervalue print skip_list doctest ellipsis skiplist level root key1 key1 key2 key2 none return random level from 1 self max_level interval higher values are less likely param key searched key return tuple with searched node or none if given key is not present and list of nodes that refer if key is present of should refer to given node nodes with refer or should refer to output node i node level when node level is lesser than i decrement i node forward i key key jumping to node with key value higher or equal to searched key would result in skipping searched key each leftmost node relative to searched node will potentially have to be updated note that we were inserting values in reverse order len node forward 0 if current node doesn t contain any further references then searched key is not present node forward 0 key key next node key should be equal to search key if key is present param key key to remove from list skip_list skiplist skip_list insert 2 two skip_list insert 1 one skip_list insert 3 three list skip_list 1 2 3 skip_list delete 2 list skip_list 1 3 remove or replace all references to removed node param key key to insert param value value associated with given key skip_list skiplist skip_list insert 2 two skip_list find 2 two list skip_list 2 after level increase we have to add additional nodes to head change references to pass through new node param key search key return value associated with given key or none if given key is not present skip_list skiplist skip_list find 2 skip_list insert 2 two skip_list find 2 two skip_list insert 2 three skip_list find 2 three repeat test 100 times due to the probabilistic nature of skip list random values random bugs pytests
from __future__ import annotations from random import random from typing import Generic, TypeVar KT = TypeVar("KT") VT = TypeVar("VT") class Node(Generic[KT, VT]): def __init__(self, key: KT | str = "root", value: VT | None = None): self.key = key self.value = value self.forward: list[Node[KT, VT]] = [] def __repr__(self) -> str: return f"Node({self.key}: {self.value})" @property def level(self) -> int: return len(self.forward) class SkipList(Generic[KT, VT]): def __init__(self, p: float = 0.5, max_level: int = 16): self.head: Node[KT, VT] = Node[KT, VT]() self.level = 0 self.p = p self.max_level = max_level def __str__(self) -> str: items = list(self) if len(items) == 0: return f"SkipList(level={self.level})" label_size = max((len(str(item)) for item in items), default=4) label_size = max(label_size, 4) + 4 node = self.head lines = [] forwards = node.forward.copy() lines.append(f"[{node.key}]".ljust(label_size, "-") + "* " * len(forwards)) lines.append(" " * label_size + "| " * len(forwards)) while len(node.forward) != 0: node = node.forward[0] lines.append( f"[{node.key}]".ljust(label_size, "-") + " ".join(str(n.key) if n.key == node.key else "|" for n in forwards) ) lines.append(" " * label_size + "| " * len(forwards)) forwards[: node.level] = node.forward lines.append("None".ljust(label_size) + "* " * len(forwards)) return f"SkipList(level={self.level})\n" + "\n".join(lines) def __iter__(self): node = self.head while len(node.forward) != 0: yield node.forward[0].key node = node.forward[0] def random_level(self) -> int: level = 1 while random() < self.p and level < self.max_level: level += 1 return level def _locate_node(self, key) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: update_vector = [] node = self.head for i in reversed(range(self.level)): while i < node.level and node.forward[i].key < key: node = node.forward[i] update_vector.append(node) update_vector.reverse() if len(node.forward) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def delete(self, key: KT): node, update_vector = self._locate_node(key) if node is not None: for i, update_node in enumerate(update_vector): if update_node.level > i and update_node.forward[i].key == key: if node.level > i: update_node.forward[i] = node.forward[i] else: update_node.forward = update_node.forward[:i] def insert(self, key: KT, value: VT): node, update_vector = self._locate_node(key) if node is not None: node.value = value else: level = self.random_level() if level > self.level: for _ in range(self.level - 1, level): update_vector.append(self.head) self.level = level new_node = Node(key, value) for i, update_node in enumerate(update_vector[:level]): if update_node.level > i: new_node.forward.append(update_node.forward[i]) if update_node.level < i + 1: update_node.forward.append(new_node) else: update_node.forward[i] = new_node def find(self, key: VT) -> VT | None: node, _ = self._locate_node(key) if node is not None: return node.value return None def test_insert(): skip_list = SkipList() skip_list.insert("Key1", 3) skip_list.insert("Key2", 12) skip_list.insert("Key3", 41) skip_list.insert("Key4", -19) node = skip_list.head all_values = {} while node.level != 0: node = node.forward[0] all_values[node.key] = node.value assert len(all_values) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def test_insert_overrides_existing_value(): skip_list = SkipList() skip_list.insert("Key1", 10) skip_list.insert("Key1", 12) skip_list.insert("Key5", 7) skip_list.insert("Key7", 10) skip_list.insert("Key10", 5) skip_list.insert("Key7", 7) skip_list.insert("Key5", 5) skip_list.insert("Key10", 10) node = skip_list.head all_values = {} while node.level != 0: node = node.forward[0] all_values[node.key] = node.value if len(all_values) != 4: print() assert len(all_values) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def test_searching_empty_list_returns_none(): skip_list = SkipList() assert skip_list.find("Some key") is None def test_search(): skip_list = SkipList() skip_list.insert("Key2", 20) assert skip_list.find("Key2") == 20 skip_list.insert("Some Key", 10) skip_list.insert("Key2", 8) skip_list.insert("V", 13) assert skip_list.find("Y") is None assert skip_list.find("Key2") == 8 assert skip_list.find("Some Key") == 10 assert skip_list.find("V") == 13 def test_deleting_item_from_empty_list_do_nothing(): skip_list = SkipList() skip_list.delete("Some key") assert len(skip_list.head.forward) == 0 def test_deleted_items_are_not_founded_by_find_method(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 14) skip_list.insert("Key2", 15) skip_list.delete("V") skip_list.delete("Key2") assert skip_list.find("V") is None assert skip_list.find("Key2") is None def test_delete_removes_only_given_key(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 14) skip_list.insert("Key2", 15) skip_list.delete("V") assert skip_list.find("V") is None assert skip_list.find("X") == 14 assert skip_list.find("Key1") == 12 assert skip_list.find("Key2") == 15 skip_list.delete("X") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") == 12 assert skip_list.find("Key2") == 15 skip_list.delete("Key1") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") is None assert skip_list.find("Key2") == 15 skip_list.delete("Key2") assert skip_list.find("V") is None assert skip_list.find("X") is None assert skip_list.find("Key1") is None assert skip_list.find("Key2") is None def test_delete_doesnt_leave_dead_nodes(): skip_list = SkipList() skip_list.insert("Key1", 12) skip_list.insert("V", 13) skip_list.insert("X", 142) skip_list.insert("Key2", 15) skip_list.delete("X") def traverse_keys(node): yield node.key for forward_node in node.forward: yield from traverse_keys(forward_node) assert len(set(traverse_keys(skip_list.head))) == 4 def test_iter_always_yields_sorted_values(): def is_sorted(lst): return all(next_item >= item for item, next_item in zip(lst, lst[1:])) skip_list = SkipList() for i in range(10): skip_list.insert(i, i) assert is_sorted(list(skip_list)) skip_list.delete(5) skip_list.delete(8) skip_list.delete(2) assert is_sorted(list(skip_list)) skip_list.insert(-12, -12) skip_list.insert(77, 77) assert is_sorted(list(skip_list)) def pytests(): for _ in range(100): test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def main(): skip_list = SkipList() skip_list.insert(2, "2") skip_list.insert(4, "4") skip_list.insert(6, "4") skip_list.insert(4, "5") skip_list.insert(8, "4") skip_list.insert(9, "4") skip_list.delete(4) print(skip_list) if __name__ == "__main__": import doctest doctest.testmod() main()
linkedlist linkedlist listlinkedlist linkedlist push0 tuplelinkedlist 0 linkedlist linkedlist lenlinkedlist 0 linkedlist push0 lenlinkedlist 1 add a new node with the given data to the beginning of the linked list args newdata any the data to be added to the new node returns none examples linkedlist linkedlist linkedlist push5 linkedlist push4 linkedlist push3 linkedlist push2 linkedlist push1 listlinkedlist 1 2 3 4 5 swap the positions of two nodes in the linked list based on their data values args nodedata1 data value of the first node to be swapped nodedata2 data value of the second node to be swapped note if either of the specified data values isn t found then no swapping occurs examples when both values are present in a linked list linkedlist linkedlist linkedlist push5 linkedlist push4 linkedlist push3 linkedlist push2 linkedlist push1 listlinkedlist 1 2 3 4 5 linkedlist swapnodes1 5 tuplelinkedlist 5 2 3 4 1 when one value is present and the other isn t in the linked list secondlist linkedlist secondlist push6 secondlist push7 secondlist push8 secondlist push9 secondlist swapnodes1 6 is none true when both values are absent in the linked list secondlist linkedlist secondlist push10 secondlist push9 secondlist push8 secondlist push7 secondlist swapnodes1 3 is none true when linkedlist is empty secondlist linkedlist secondlist swapnodes1 3 is none true returns none swap the data values of the two nodes python script that outputs the swap of nodes in a linked list linked_list linkedlist list linked_list linked_list push 0 tuple linked_list 0 linked_list linkedlist len linked_list 0 linked_list push 0 len linked_list 1 add a new node with the given data to the beginning of the linked list args new_data any the data to be added to the new node returns none examples linked_list linkedlist linked_list push 5 linked_list push 4 linked_list push 3 linked_list push 2 linked_list push 1 list linked_list 1 2 3 4 5 swap the positions of two nodes in the linked list based on their data values args node_data_1 data value of the first node to be swapped node_data_2 data value of the second node to be swapped note if either of the specified data values isn t found then no swapping occurs examples when both values are present in a linked list linked_list linkedlist linked_list push 5 linked_list push 4 linked_list push 3 linked_list push 2 linked_list push 1 list linked_list 1 2 3 4 5 linked_list swap_nodes 1 5 tuple linked_list 5 2 3 4 1 when one value is present and the other isn t in the linked list second_list linkedlist second_list push 6 second_list push 7 second_list push 8 second_list push 9 second_list swap_nodes 1 6 is none true when both values are absent in the linked list second_list linkedlist second_list push 10 second_list push 9 second_list push 8 second_list push 7 second_list swap_nodes 1 3 is none true when linkedlist is empty second_list linkedlist second_list swap_nodes 1 3 is none true returns none swap the data values of the two nodes python script that outputs the swap of nodes in a linked list
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass from typing import Any @dataclass class Node: data: Any next_node: Node | None = None @dataclass class LinkedList: head: Node | None = None def __iter__(self) -> Iterator: node = self.head while node: yield node.data node = node.next_node def __len__(self) -> int: return sum(1 for _ in self) def push(self, new_data: Any) -> None: new_node = Node(new_data) new_node.next_node = self.head self.head = new_node def swap_nodes(self, node_data_1: Any, node_data_2: Any) -> None: if node_data_1 == node_data_2: return node_1 = self.head while node_1 and node_1.data != node_data_1: node_1 = node_1.next_node node_2 = self.head while node_2 and node_2.data != node_data_2: node_2 = node_2.next_node if node_1 is None or node_2 is None: return node_1.data, node_2.data = node_2.data, node_1.data if __name__ == "__main__": from doctest import testmod testmod() linked_list = LinkedList() for i in range(5, 0, -1): linked_list.push(i) print(f"Original Linked List: {list(linked_list)}") linked_list.swap_nodes(1, 4) print(f"Modified Linked List: {list(linked_list)}") print("After swapping the nodes whose data is 1 and 4.")
implementation of circular queue using python lists circular fifo queue with a fixed capacity def initself n int self n n self array none self n self front 0 index of the first element self rear 0 self size 0 def lenself int return self size def isemptyself bool return self size 0 def firstself return false if self isempty else self arrayself front def enqueueself data if self size self n raise exceptionqueue is full self arrayself rear data self rear self rear 1 self n self size 1 return self def dequeueself if self size 0 raise exceptionunderflow temp self arrayself front self arrayself front none self front self front 1 self n self size 1 return temp implementation of circular queue using python lists circular fifo queue with a fixed capacity index of the first element cq circularqueue 5 len cq 0 cq enqueue a doctest ellipsis data_structures queue circular_queue circularqueue object at len cq 1 cq circularqueue 5 cq is_empty true cq enqueue a is_empty false cq circularqueue 5 cq first false cq enqueue a first a this function insert an element in the queue using self rear value as an index cq circularqueue 5 cq enqueue a doctest ellipsis data_structures queue circular_queue circularqueue object at cq size cq first 1 a cq enqueue b doctest ellipsis data_structures queue circular_queue circularqueue object at cq size cq first 2 a this function removes an element from the queue using on self front value as an index cq circularqueue 5 cq dequeue traceback most recent call last exception underflow cq enqueue a enqueue b dequeue a cq size cq first 1 b cq dequeue b cq dequeue traceback most recent call last exception underflow
class CircularQueue: def __init__(self, n: int): self.n = n self.array = [None] * self.n self.front = 0 self.rear = 0 self.size = 0 def __len__(self) -> int: return self.size def is_empty(self) -> bool: return self.size == 0 def first(self): return False if self.is_empty() else self.array[self.front] def enqueue(self, data): if self.size >= self.n: raise Exception("QUEUE IS FULL") self.array[self.rear] = data self.rear = (self.rear + 1) % self.n self.size += 1 return self def dequeue(self): if self.size == 0: raise Exception("UNDERFLOW") temp = self.array[self.front] self.array[self.front] = None self.front = (self.front + 1) % self.n self.size -= 1 return temp
implementation of circular queue using linked lists https en wikipedia orgwikicircularbuffer circular fifo list with the given capacity default queue length 6 cq circularqueuelinkedlist2 cq enqueue a cq enqueue b cq enqueue c traceback most recent call last exception full queue checks where the queue is empty or not cq circularqueuelinkedlist cq isempty true cq enqueue a cq isempty false cq dequeue a cq isempty true returns the first element of the queue cq circularqueuelinkedlist cq first traceback most recent call last exception empty queue cq enqueue a cq first a cq dequeue a cq first traceback most recent call last exception empty queue cq enqueue b cq enqueue c cq first b saves data at the end of the queue cq circularqueuelinkedlist cq enqueue a cq enqueue b cq dequeue a cq dequeue b cq dequeue traceback most recent call last exception empty queue removes and retrieves the first element of the queue cq circularqueuelinkedlist cq dequeue traceback most recent call last exception empty queue cq enqueue a cq dequeue a cq dequeue traceback most recent call last exception empty queue implementation of circular queue using linked lists https en wikipedia org wiki circular_buffer circular fifo list with the given capacity default queue length 6 cq circularqueuelinkedlist 2 cq enqueue a cq enqueue b cq enqueue c traceback most recent call last exception full queue checks where the queue is empty or not cq circularqueuelinkedlist cq is_empty true cq enqueue a cq is_empty false cq dequeue a cq is_empty true returns the first element of the queue cq circularqueuelinkedlist cq first traceback most recent call last exception empty queue cq enqueue a cq first a cq dequeue a cq first traceback most recent call last exception empty queue cq enqueue b cq enqueue c cq first b saves data at the end of the queue cq circularqueuelinkedlist cq enqueue a cq enqueue b cq dequeue a cq dequeue b cq dequeue traceback most recent call last exception empty queue removes and retrieves the first element of the queue cq circularqueuelinkedlist cq dequeue traceback most recent call last exception empty queue cq enqueue a cq dequeue a cq dequeue traceback most recent call last exception empty queue
from __future__ import annotations from typing import Any class CircularQueueLinkedList: def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None self.rear: Node | None = None self.create_linked_list(initial_capacity) def create_linked_list(self, initial_capacity: int) -> None: current_node = Node() self.front = current_node self.rear = current_node previous_node = current_node for _ in range(1, initial_capacity): current_node = Node() previous_node.next = current_node current_node.prev = previous_node previous_node = current_node previous_node.next = self.front self.front.prev = previous_node def is_empty(self) -> bool: return ( self.front == self.rear and self.front is not None and self.front.data is None ) def first(self) -> Any | None: self.check_can_perform_operation() return self.front.data if self.front else None def enqueue(self, data: Any) -> None: if self.rear is None: return self.check_is_full() if not self.is_empty(): self.rear = self.rear.next if self.rear: self.rear.data = data def dequeue(self) -> Any: self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: data = self.front.data self.front.data = None return data old_front = self.front self.front = old_front.next data = old_front.data old_front.data = None return data def check_can_perform_operation(self) -> None: if self.is_empty(): raise Exception("Empty Queue") def check_is_full(self) -> None: if self.rear and self.rear.next == self.front: raise Exception("Full Queue") class Node: def __init__(self) -> None: self.data: Any | None = None self.next: Node | None = None self.prev: Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
implementation of double ended queue deque data structure operations appendval any none appendleftval any none extenditerable iterable none extendleftiterable iterable none pop any popleft any observers isempty bool attributes front node front of the deque a k a the first element back node back of the element a k a the last element len int the number of nodes representation of a node contains a value and a pointer to the next node as well as to the previous one helper class for iteration will be used to implement iteration attributes cur node the current node of the iteration ourdeque deque1 2 3 iterator iterourdeque ourdeque deque1 2 3 iterator iterourdeque nextiterator 1 nextiterator 2 nextiterator 3 finished iterating append every value to the deque adds val to the end of the deque time complexity o1 ourdeque1 deque1 2 3 ourdeque1 append4 ourdeque1 1 2 3 4 ourdeque2 deque ab ourdeque2 append c ourdeque2 a b c from collections import deque dequecollections1 deque1 2 3 dequecollections1 append4 dequecollections1 deque1 2 3 4 dequecollections2 deque ab dequecollections2 append c dequecollections2 deque a b c listourdeque1 listdequecollections1 true listourdeque2 listdequecollections2 true front back connect nodes make sure there were no errors adds val to the beginning of the deque time complexity o1 ourdeque1 deque2 3 ourdeque1 appendleft1 ourdeque1 1 2 3 ourdeque2 deque bc ourdeque2 appendleft a ourdeque2 a b c from collections import deque dequecollections1 deque2 3 dequecollections1 appendleft1 dequecollections1 deque1 2 3 dequecollections2 deque bc dequecollections2 appendleft a dequecollections2 deque a b c listourdeque1 listdequecollections1 true listourdeque2 listdequecollections2 true front back connect nodes make sure there were no errors appends every value of iterable to the end of the deque time complexity on ourdeque1 deque1 2 3 ourdeque1 extend4 5 ourdeque1 1 2 3 4 5 ourdeque2 deque ab ourdeque2 extend cd ourdeque2 a b c d from collections import deque dequecollections1 deque1 2 3 dequecollections1 extend4 5 dequecollections1 deque1 2 3 4 5 dequecollections2 deque ab dequecollections2 extend cd dequecollections2 deque a b c d listourdeque1 listdequecollections1 true listourdeque2 listdequecollections2 true appends every value of iterable to the beginning of the deque time complexity on ourdeque1 deque1 2 3 ourdeque1 extendleft0 1 ourdeque1 1 0 1 2 3 ourdeque2 deque cd ourdeque2 extendleft ba ourdeque2 a b c d from collections import deque dequecollections1 deque1 2 3 dequecollections1 extendleft0 1 dequecollections1 deque1 0 1 2 3 dequecollections2 deque cd dequecollections2 extendleft ba dequecollections2 deque a b c d listourdeque1 listdequecollections1 true listourdeque2 listdequecollections2 true removes the last element of the deque and returns it time complexity o1 returns topop val the value of the node to pop ourdeque1 deque1 ourpopped1 ourdeque1 pop ourpopped1 1 ourdeque1 ourdeque2 deque1 2 3 15182 ourpopped2 ourdeque2 pop ourpopped2 15182 ourdeque2 1 2 3 from collections import deque dequecollections deque1 2 3 15182 collectionspopped dequecollections pop collectionspopped 15182 dequecollections deque1 2 3 listourdeque2 listdequecollections true ourpopped2 collectionspopped true make sure the deque has elements to pop if only one element in the queue point the front and back to none else remove one element from back drop the last node python will deallocate memory automatically removes the first element of the deque and returns it time complexity o1 returns topop val the value of the node to pop ourdeque1 deque1 ourpopped1 ourdeque1 pop ourpopped1 1 ourdeque1 ourdeque2 deque15182 1 2 3 ourpopped2 ourdeque2 popleft ourpopped2 15182 ourdeque2 1 2 3 from collections import deque dequecollections deque15182 1 2 3 collectionspopped dequecollections popleft collectionspopped 15182 dequecollections deque1 2 3 listourdeque2 listdequecollections true ourpopped2 collectionspopped true make sure the deque has elements to pop if only one element in the queue point the front and back to none else remove one element from front checks if the deque is empty time complexity o1 ourdeque deque1 2 3 ourdeque isempty false ouremptydeque deque ouremptydeque isempty true from collections import deque emptydequecollections deque listouremptydeque listemptydequecollections true implements len function returns the length of the deque time complexity o1 ourdeque deque1 2 3 lenourdeque 3 ouremptydeque deque lenouremptydeque 0 from collections import deque dequecollections deque1 2 3 lendequecollections 3 emptydequecollections deque lenemptydequecollections 0 lenouremptydeque lenemptydequecollections true implements operator returns if self is equal to other time complexity on ourdeque1 deque1 2 3 ourdeque2 deque1 2 3 ourdeque1 ourdeque2 true ourdeque3 deque1 2 ourdeque1 ourdeque3 false from collections import deque dequecollections1 deque1 2 3 dequecollections2 deque1 2 3 dequecollections1 dequecollections2 true dequecollections3 deque1 2 dequecollections1 dequecollections3 false ourdeque1 ourdeque2 dequecollections1 dequecollections2 true ourdeque1 ourdeque3 dequecollections1 dequecollections3 true if the length of the dequeues are not the same they are not equal compare every value implements iteration time complexity o1 ourdeque deque1 2 3 for v in ourdeque printv 1 2 3 from collections import deque dequecollections deque1 2 3 for v in dequecollections printv 1 2 3 implements representation of the deque represents it as a list with its values between and time complexity on ourdeque deque1 2 3 ourdeque 1 2 3 append the values in a list to display deque data structure operations append val any none appendleft val any none extend iterable iterable none extendleft iterable iterable none pop any popleft any observers is_empty bool attributes _front _node front of the deque a k a the first element _back _node back of the element a k a the last element _len int the number of nodes representation of a node contains a value and a pointer to the next node as well as to the previous one helper class for iteration will be used to implement iteration attributes _cur _node the current node of the iteration our_deque deque 1 2 3 iterator iter our_deque our_deque deque 1 2 3 iterator iter our_deque next iterator 1 next iterator 2 next iterator 3 finished iterating append every value to the deque adds val to the end of the deque time complexity o 1 our_deque_1 deque 1 2 3 our_deque_1 append 4 our_deque_1 1 2 3 4 our_deque_2 deque ab our_deque_2 append c our_deque_2 a b c from collections import deque deque_collections_1 deque 1 2 3 deque_collections_1 append 4 deque_collections_1 deque 1 2 3 4 deque_collections_2 deque ab deque_collections_2 append c deque_collections_2 deque a b c list our_deque_1 list deque_collections_1 true list our_deque_2 list deque_collections_2 true front back connect nodes assign new back to the new node make sure there were no errors adds val to the beginning of the deque time complexity o 1 our_deque_1 deque 2 3 our_deque_1 appendleft 1 our_deque_1 1 2 3 our_deque_2 deque bc our_deque_2 appendleft a our_deque_2 a b c from collections import deque deque_collections_1 deque 2 3 deque_collections_1 appendleft 1 deque_collections_1 deque 1 2 3 deque_collections_2 deque bc deque_collections_2 appendleft a deque_collections_2 deque a b c list our_deque_1 list deque_collections_1 true list our_deque_2 list deque_collections_2 true front back connect nodes assign new front to the new node make sure there were no errors appends every value of iterable to the end of the deque time complexity o n our_deque_1 deque 1 2 3 our_deque_1 extend 4 5 our_deque_1 1 2 3 4 5 our_deque_2 deque ab our_deque_2 extend cd our_deque_2 a b c d from collections import deque deque_collections_1 deque 1 2 3 deque_collections_1 extend 4 5 deque_collections_1 deque 1 2 3 4 5 deque_collections_2 deque ab deque_collections_2 extend cd deque_collections_2 deque a b c d list our_deque_1 list deque_collections_1 true list our_deque_2 list deque_collections_2 true appends every value of iterable to the beginning of the deque time complexity o n our_deque_1 deque 1 2 3 our_deque_1 extendleft 0 1 our_deque_1 1 0 1 2 3 our_deque_2 deque cd our_deque_2 extendleft ba our_deque_2 a b c d from collections import deque deque_collections_1 deque 1 2 3 deque_collections_1 extendleft 0 1 deque_collections_1 deque 1 0 1 2 3 deque_collections_2 deque cd deque_collections_2 extendleft ba deque_collections_2 deque a b c d list our_deque_1 list deque_collections_1 true list our_deque_2 list deque_collections_2 true removes the last element of the deque and returns it time complexity o 1 returns topop val the value of the node to pop our_deque1 deque 1 our_popped1 our_deque1 pop our_popped1 1 our_deque1 our_deque2 deque 1 2 3 15182 our_popped2 our_deque2 pop our_popped2 15182 our_deque2 1 2 3 from collections import deque deque_collections deque 1 2 3 15182 collections_popped deque_collections pop collections_popped 15182 deque_collections deque 1 2 3 list our_deque2 list deque_collections true our_popped2 collections_popped true make sure the deque has elements to pop if only one element in the queue point the front and back to none else remove one element from back set new back drop the last node python will deallocate memory automatically removes the first element of the deque and returns it time complexity o 1 returns topop val the value of the node to pop our_deque1 deque 1 our_popped1 our_deque1 pop our_popped1 1 our_deque1 our_deque2 deque 15182 1 2 3 our_popped2 our_deque2 popleft our_popped2 15182 our_deque2 1 2 3 from collections import deque deque_collections deque 15182 1 2 3 collections_popped deque_collections popleft collections_popped 15182 deque_collections deque 1 2 3 list our_deque2 list deque_collections true our_popped2 collections_popped true make sure the deque has elements to pop if only one element in the queue point the front and back to none else remove one element from front set new front and drop the first node checks if the deque is empty time complexity o 1 our_deque deque 1 2 3 our_deque is_empty false our_empty_deque deque our_empty_deque is_empty true from collections import deque empty_deque_collections deque list our_empty_deque list empty_deque_collections true implements len function returns the length of the deque time complexity o 1 our_deque deque 1 2 3 len our_deque 3 our_empty_deque deque len our_empty_deque 0 from collections import deque deque_collections deque 1 2 3 len deque_collections 3 empty_deque_collections deque len empty_deque_collections 0 len our_empty_deque len empty_deque_collections true implements operator returns if self is equal to other time complexity o n our_deque_1 deque 1 2 3 our_deque_2 deque 1 2 3 our_deque_1 our_deque_2 true our_deque_3 deque 1 2 our_deque_1 our_deque_3 false from collections import deque deque_collections_1 deque 1 2 3 deque_collections_2 deque 1 2 3 deque_collections_1 deque_collections_2 true deque_collections_3 deque 1 2 deque_collections_1 deque_collections_3 false our_deque_1 our_deque_2 deque_collections_1 deque_collections_2 true our_deque_1 our_deque_3 deque_collections_1 deque_collections_3 true if the length of the dequeues are not the same they are not equal compare every value implements iteration time complexity o 1 our_deque deque 1 2 3 for v in our_deque print v 1 2 3 from collections import deque deque_collections deque 1 2 3 for v in deque_collections print v 1 2 3 implements representation of the deque represents it as a list with its values between and time complexity o n our_deque deque 1 2 3 our_deque 1 2 3 append the values in a list to display
from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from typing import Any class Deque: __slots__ = ("_front", "_back", "_len") @dataclass class _Node: val: Any = None next_node: Deque._Node | None = None prev_node: Deque._Node | None = None class _Iterator: __slots__ = ("_cur",) def __init__(self, cur: Deque._Node | None) -> None: self._cur = cur def __iter__(self) -> Deque._Iterator: return self def __next__(self) -> Any: if self._cur is None: raise StopIteration val = self._cur.val self._cur = self._cur.next_node return val def __init__(self, iterable: Iterable[Any] | None = None) -> None: self._front: Any = None self._back: Any = None self._len: int = 0 if iterable is not None: for val in iterable: self.append(val) def append(self, val: Any) -> None: node = self._Node(val, None, None) if self.is_empty(): self._front = self._back = node self._len = 1 else: self._back.next_node = node node.prev_node = self._back self._back = node self._len += 1 assert not self.is_empty(), "Error on appending value." def appendleft(self, val: Any) -> None: node = self._Node(val, None, None) if self.is_empty(): self._front = self._back = node self._len = 1 else: node.next_node = self._front self._front.prev_node = node self._front = node self._len += 1 assert not self.is_empty(), "Error on appending value." def extend(self, iterable: Iterable[Any]) -> None: for val in iterable: self.append(val) def extendleft(self, iterable: Iterable[Any]) -> None: for val in iterable: self.appendleft(val) def pop(self) -> Any: assert not self.is_empty(), "Deque is empty." topop = self._back if self._front == self._back: self._front = None self._back = None else: self._back = self._back.prev_node self._back.next_node = None self._len -= 1 return topop.val def popleft(self) -> Any: assert not self.is_empty(), "Deque is empty." topop = self._front if self._front == self._back: self._front = None self._back = None else: self._front = self._front.next_node self._front.prev_node = None self._len -= 1 return topop.val def is_empty(self) -> bool: return self._front is None def __len__(self) -> int: return self._len def __eq__(self, other: object) -> bool: if not isinstance(other, Deque): return NotImplemented me = self._front oth = other._front if len(self) != len(other): return False while me is not None and oth is not None: if me.val != oth.val: return False me = me.next_node oth = oth.next_node return True def __iter__(self) -> Deque._Iterator: return Deque._Iterator(self._front) def __repr__(self) -> str: values_list = [] aux = self._front while aux is not None: values_list.append(aux.val) aux = aux.next_node return f"[{', '.join(repr(val) for val in values_list)}]" if __name__ == "__main__": import doctest doctest.testmod() dq = Deque([3]) dq.pop()
a queue using a linked list like structure from future import annotations from collections abc import iterator from typing import any class node def initself data any none self data any data self next node none none def strself str return fself data class linkedqueue def initself none self front node none none self rear node none none def iterself iteratorany node self front while node yield node data node node next def lenself int return lentupleiterself def strself str return joinstritem for item in self def isemptyself bool return lenself 0 def putself item any none node nodeitem if self isempty self front self rear node else assert isinstanceself rear node self rear next node self rear node def getself any if self isempty raise indexerrordequeue from empty queue assert isinstanceself front node node self front self front self front next if self front is none self rear none return node data def clearself none self front self rear none if name main from doctest import testmod testmod queue linkedqueue queue is_empty true queue put 5 queue put 9 queue put python queue is_empty false queue get 5 queue put algorithms queue get 9 queue get python queue get algorithms queue is_empty true queue get traceback most recent call last indexerror dequeue from empty queue queue linkedqueue for i in range 1 6 queue put i len queue 5 for i in range 1 6 assert len queue 6 i _ queue get len queue 0 queue linkedqueue for i in range 1 4 queue put i queue put python queue put 3 14 queue put true str queue 1 2 3 python 3 14 true queue linkedqueue queue is_empty true for i in range 1 6 queue put i queue is_empty false queue linkedqueue queue get traceback most recent call last indexerror dequeue from empty queue for i in range 1 6 queue put i str queue 1 2 3 4 5 queue linkedqueue queue get traceback most recent call last indexerror dequeue from empty queue queue linkedqueue for i in range 1 6 queue put i for i in range 1 6 assert queue get i len queue 0 queue linkedqueue for i in range 1 6 queue put i queue clear len queue 0 str queue
from __future__ import annotations from collections.abc import Iterator from typing import Any class Node: def __init__(self, data: Any) -> None: self.data: Any = data self.next: Node | None = None def __str__(self) -> str: return f"{self.data}" class LinkedQueue: def __init__(self) -> None: self.front: Node | None = None self.rear: Node | None = None def __iter__(self) -> Iterator[Any]: node = self.front while node: yield node.data node = node.next def __len__(self) -> int: return len(tuple(iter(self))) def __str__(self) -> str: return " <- ".join(str(item) for item in self) def is_empty(self) -> bool: return len(self) == 0 def put(self, item: Any) -> None: node = Node(item) if self.is_empty(): self.front = self.rear = node else: assert isinstance(self.rear, Node) self.rear.next = node self.rear = node def get(self) -> Any: if self.is_empty(): raise IndexError("dequeue from empty queue") assert isinstance(self.front, Node) node = self.front self.front = self.front.next if self.front is None: self.rear = None return node.data def clear(self) -> None: self.front = self.rear = None if __name__ == "__main__": from doctest import testmod testmod()
pure python implementations of a fixed priority queue and an element priority queue using python lists tasks can be added to a priority queue at any time and in any order but when tasks are removed then the task with the highest priority is removed in fifo order in code we will use three levels of priority with priority zero tasks being the most urgent high priority and priority 2 tasks being the least urgent examples fpq fixedpriorityqueue fpq enqueue0 10 fpq enqueue1 70 fpq enqueue0 100 fpq enqueue2 1 fpq enqueue2 5 fpq enqueue1 7 fpq enqueue2 4 fpq enqueue1 64 fpq enqueue0 128 printfpq priority 0 10 100 128 priority 1 70 7 64 priority 2 1 5 4 fpq dequeue 10 fpq dequeue 100 fpq dequeue 128 fpq dequeue 70 fpq dequeue 7 printfpq priority 0 priority 1 64 priority 2 1 5 4 fpq dequeue 64 fpq dequeue 1 fpq dequeue 5 fpq dequeue 4 fpq dequeue traceback most recent call last datastructures queue priorityqueueusinglist underflowerror all queues are empty printfpq priority 0 priority 1 priority 2 add an element to a queue based on its priority if the priority is invalid valueerror is raised if the queue is full an overflowerror is raised return the highest priority element in fifo order if the queue is empty then an under flow exception is raised element priority queue is the same as fixed priority queue except that the value of the element itself is the priority the rules for priorities are the same the as fixed priority queue epq elementpriorityqueue epq enqueue10 epq enqueue70 epq enqueue4 epq enqueue1 epq enqueue5 epq enqueue7 epq enqueue4 epq enqueue64 epq enqueue128 printepq 10 70 4 1 5 7 4 64 128 epq dequeue 1 epq dequeue 4 epq dequeue 4 epq dequeue 5 epq dequeue 7 epq dequeue 10 printepq 70 64 128 epq dequeue 64 epq dequeue 70 epq dequeue 128 epq dequeue traceback most recent call last datastructures queue priorityqueueusinglist underflowerror the queue is empty printepq this function enters the element into the queue if the queue is full an exception is raised saying over flow return the highest priority element in fifo order if the queue is empty then an under flow exception is raised prints all the elements within the element priority queue tasks can be added to a priority queue at any time and in any order but when tasks are removed then the task with the highest priority is removed in fifo order in code we will use three levels of priority with priority zero tasks being the most urgent high priority and priority 2 tasks being the least urgent examples fpq fixedpriorityqueue fpq enqueue 0 10 fpq enqueue 1 70 fpq enqueue 0 100 fpq enqueue 2 1 fpq enqueue 2 5 fpq enqueue 1 7 fpq enqueue 2 4 fpq enqueue 1 64 fpq enqueue 0 128 print fpq priority 0 10 100 128 priority 1 70 7 64 priority 2 1 5 4 fpq dequeue 10 fpq dequeue 100 fpq dequeue 128 fpq dequeue 70 fpq dequeue 7 print fpq priority 0 priority 1 64 priority 2 1 5 4 fpq dequeue 64 fpq dequeue 1 fpq dequeue 5 fpq dequeue 4 fpq dequeue traceback most recent call last data_structures queue priority_queue_using_list underflowerror all queues are empty print fpq priority 0 priority 1 priority 2 add an element to a queue based on its priority if the priority is invalid valueerror is raised if the queue is full an overflowerror is raised return the highest priority element in fifo order if the queue is empty then an under flow exception is raised element priority queue is the same as fixed priority queue except that the value of the element itself is the priority the rules for priorities are the same the as fixed priority queue epq elementpriorityqueue epq enqueue 10 epq enqueue 70 epq enqueue 4 epq enqueue 1 epq enqueue 5 epq enqueue 7 epq enqueue 4 epq enqueue 64 epq enqueue 128 print epq 10 70 4 1 5 7 4 64 128 epq dequeue 1 epq dequeue 4 epq dequeue 4 epq dequeue 5 epq dequeue 7 epq dequeue 10 print epq 70 64 128 epq dequeue 64 epq dequeue 70 epq dequeue 128 epq dequeue traceback most recent call last data_structures queue priority_queue_using_list underflowerror the queue is empty print epq this function enters the element into the queue if the queue is full an exception is raised saying over flow return the highest priority element in fifo order if the queue is empty then an under flow exception is raised prints all the elements within the element priority queue
class OverFlowError(Exception): pass class UnderFlowError(Exception): pass class FixedPriorityQueue: def __init__(self): self.queues = [ [], [], [], ] def enqueue(self, priority: int, data: int) -> None: try: if len(self.queues[priority]) >= 100: raise OverflowError("Maximum queue size is 100") self.queues[priority].append(data) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2") def dequeue(self) -> int: for queue in self.queues: if queue: return queue.pop(0) raise UnderFlowError("All queues are empty") def __str__(self) -> str: return "\n".join(f"Priority {i}: {q}" for i, q in enumerate(self.queues)) class ElementPriorityQueue: def __init__(self): self.queue = [] def enqueue(self, data: int) -> None: if len(self.queue) == 100: raise OverFlowError("Maximum queue size is 100") self.queue.append(data) def dequeue(self) -> int: if not self.queue: raise UnderFlowError("The queue is empty") else: data = min(self.queue) self.queue.remove(data) return data def __str__(self) -> str: return str(self.queue) def fixed_priority_queue(): fpq = FixedPriorityQueue() fpq.enqueue(0, 10) fpq.enqueue(1, 70) fpq.enqueue(0, 100) fpq.enqueue(2, 1) fpq.enqueue(2, 5) fpq.enqueue(1, 7) fpq.enqueue(2, 4) fpq.enqueue(1, 64) fpq.enqueue(0, 128) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) print(fpq.dequeue()) def element_priority_queue(): epq = ElementPriorityQueue() epq.enqueue(10) epq.enqueue(70) epq.enqueue(100) epq.enqueue(1) epq.enqueue(5) epq.enqueue(7) epq.enqueue(4) epq.enqueue(64) epq.enqueue(128) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) print(epq.dequeue()) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
queue represented by a python list from collections abc import iterable from typing import generic typevar t typevart class queuebylistgenerict def initself iterable iterablet none none none self entries listt listiterable or def lenself int return lenself entries def reprself str return fqueuetupleself entries def putself item t none self entries appenditem def getself t if not self entries raise indexerrorqueue is empty return self entries pop0 def rotateself rotation int none put self entries append get self entries pop for in rangerotation putget0 def getfrontself t return self entries0 if name main from doctest import testmod testmod queuebylist queue queuebylist 10 20 30 queue 10 20 30 queuebylist i 2 for i in range 1 4 queue 1 4 9 len queuebylist 0 from string import ascii_lowercase len queuebylist ascii_lowercase 26 queue queuebylist for i in range 1 11 queue put i len queue 10 for i in range 2 queue get 1 2 len queue 8 queue queuebylist queue queue str queue queue queue put 10 queue queue 10 queue put 20 queue put 30 queue queue 10 20 30 put item to the queue queue queuebylist queue put 10 queue put 20 len queue 2 queue queue 10 20 get item from the queue queue queuebylist 10 20 30 queue get 10 queue put 40 queue get 20 queue get 30 len queue 1 queue get 40 queue get traceback most recent call last indexerror queue is empty rotate the items of the queue rotation times queue queuebylist 10 20 30 40 queue queue 10 20 30 40 queue rotate 1 queue queue 20 30 40 10 queue rotate 2 queue queue 40 10 20 30 get the front item from the queue queue queuebylist 10 20 30 queue get_front 10 queue queue 10 20 30 queue get 10 queue get_front 20
from collections.abc import Iterable from typing import Generic, TypeVar _T = TypeVar("_T") class QueueByList(Generic[_T]): def __init__(self, iterable: Iterable[_T] | None = None) -> None: self.entries: list[_T] = list(iterable or []) def __len__(self) -> int: return len(self.entries) def __repr__(self) -> str: return f"Queue({tuple(self.entries)})" def put(self, item: _T) -> None: self.entries.append(item) def get(self) -> _T: if not self.entries: raise IndexError("Queue is empty") return self.entries.pop(0) def rotate(self, rotation: int) -> None: put = self.entries.append get = self.entries.pop for _ in range(rotation): put(get(0)) def get_front(self) -> _T: return self.entries[0] if __name__ == "__main__": from doctest import testmod testmod()
queue implementation using two stacks from collections abc import iterable from typing import generic typevar t typevart class queuebytwostacksgenerict def initself iterable iterablet none none none self stack1 listt listiterable or self stack2 listt def lenself int return lenself stack1 lenself stack2 def reprself str return fqueuetupleself stack2 1 self stack1 def putself item t none self stack1 appenditem def getself t to reduce number of attribute lookups in while loop stack1pop self stack1 pop stack2append self stack2 append if not self stack2 while self stack1 stack2appendstack1pop if not self stack2 raise indexerrorqueue is empty return self stack2 pop if name main from doctest import testmod testmod queuebytwostacks queue queuebytwostacks 10 20 30 queue 10 20 30 queuebytwostacks i 2 for i in range 1 4 queue 1 4 9 len queuebytwostacks 0 from string import ascii_lowercase len queuebytwostacks ascii_lowercase 26 queue queuebytwostacks for i in range 1 11 queue put i len queue 10 for i in range 2 queue get 1 2 len queue 8 queue queuebytwostacks queue queue str queue queue queue put 10 queue queue 10 queue put 20 queue put 30 queue queue 10 20 30 put item into the queue queue queuebytwostacks queue put 10 queue put 20 len queue 2 queue queue 10 20 get item from the queue queue queuebytwostacks 10 20 30 queue get 10 queue put 40 queue get 20 queue get 30 len queue 1 queue get 40 queue get traceback most recent call last indexerror queue is empty to reduce number of attribute look ups in while loop
from collections.abc import Iterable from typing import Generic, TypeVar _T = TypeVar("_T") class QueueByTwoStacks(Generic[_T]): def __init__(self, iterable: Iterable[_T] | None = None) -> None: self._stack1: list[_T] = list(iterable or []) self._stack2: list[_T] = [] def __len__(self) -> int: return len(self._stack1) + len(self._stack2) def __repr__(self) -> str: return f"Queue({tuple(self._stack2[::-1] + self._stack1)})" def put(self, item: _T) -> None: self._stack1.append(item) def get(self) -> _T: stack1_pop = self._stack1.pop stack2_append = self._stack2.append if not self._stack2: while self._stack1: stack2_append(stack1_pop()) if not self._stack2: raise IndexError("Queue is empty") return self._stack2.pop() if __name__ == "__main__": from doctest import testmod testmod()
queue represented by a pseudo stack represented by a list with pop and append from typing import any class queue def initself self stack self length 0 def strself printed strself stack1 1 return printed dequeues code item requirement self length 0 return dequeued item that was dequeued def getself any self rotate1 dequeued self stackself length 1 self stack self stack 1 self rotateself length 1 self length self length 1 return dequeued reports item at the front of self return item at front of self stack def frontself any front self get self putfront self rotateself length 1 return front enqueues code item param item item to enqueue dequeues code item requirement self length 0 return dequeued item that was dequeued rotates the queue code rotation times param rotation number of times to rotate queue reports item at the front of self return item at front of self stack returns the length of this stack
from typing import Any class Queue: def __init__(self): self.stack = [] self.length = 0 def __str__(self): printed = "<" + str(self.stack)[1:-1] + ">" return printed def put(self, item: Any) -> None: self.stack.append(item) self.length = self.length + 1 def get(self) -> Any: self.rotate(1) dequeued = self.stack[self.length - 1] self.stack = self.stack[:-1] self.rotate(self.length - 1) self.length = self.length - 1 return dequeued def rotate(self, rotation: int) -> None: for _ in range(rotation): temp = self.stack[0] self.stack = self.stack[1:] self.put(temp) self.length = self.length - 1 def front(self) -> Any: front = self.get() self.put(front) self.rotate(self.length - 1) return front def size(self) -> int: return self.length
use a stack to check if a string of parentheses is balanced balancedparentheses true balancedparentheses true balancedparentheses false balancedparentheses1234 true balancedparentheses true use a stack to check if a string of parentheses is balanced balanced_parentheses true balanced_parentheses true balanced_parentheses false balanced_parentheses 1 2 3 4 true balanced_parentheses true
from .stack import Stack def balanced_parentheses(parentheses: str) -> bool: stack: Stack[str] = Stack() bracket_pairs = {"(": ")", "[": "]", "{": "}"} for bracket in parentheses: if bracket in bracket_pairs: stack.push(bracket) elif bracket in (")", "]", "}"): if stack.is_empty() or bracket_pairs[stack.pop()] != bracket: return False return stack.is_empty() if __name__ == "__main__": from doctest import testmod testmod() examples = ["((()))", "((())", "(()))"] print("Balanced parentheses demonstration:\n") for example in examples: not_str = "" if balanced_parentheses(example) else "not " print(f"{example} is {not_str}balanced")
alexander joslin github github comechoaj explanation https medium comhaleesammarimplementedinjsdijkstras2stack algorithmforevaluatingmathematicalexpressionsfc0837dae1ea we can use dijkstra s two stack algorithm to solve an equation such as 5 4 2 2 3 these are the algorithm s rules rule 1 scan the expression from left to right when an operand is encountered push it onto the operand stack rule 2 when an operator is encountered in the expression push it onto the operator stack rule 3 when a left parenthesis is encountered in the expression ignore it rule 4 when a right parenthesis is encountered in the expression pop an operator off the operator stack the two operands it must operate on must be the last two operands pushed onto the operand stack we therefore pop the operand stack twice perform the operation and push the result back onto the operand stack so it will be available for use as an operand of the next operator popped off the operator stack rule 5 when the entire infix expression has been scanned the value left on the operand stack represents the value of the expression note it only works with whole numbers doctests dijkstrastwostackalgorithm5 3 8 dijkstrastwostackalgorithm9 2 9 8 1 5 dijkstrastwostackalgorithm3 2 2 3 2 4 3 3 param equation a string return result an integer rule 1 rule 2 rule 4 rule 5 answer 45 doctests dijkstras_two_stack_algorithm 5 3 8 dijkstras_two_stack_algorithm 9 2 9 8 1 5 dijkstras_two_stack_algorithm 3 2 2 3 2 4 3 3 param equation a string return result an integer rule 1 rule 2 rule 4 rule 5 answer 45
__author__ = "Alexander Joslin" import operator as op from .stack import Stack def dijkstras_two_stack_algorithm(equation: str) -> int: operators = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} operand_stack: Stack[int] = Stack() operator_stack: Stack[str] = Stack() for i in equation: if i.isdigit(): operand_stack.push(int(i)) elif i in operators: operator_stack.push(i) elif i == ")": opr = operator_stack.peek() operator_stack.pop() num1 = operand_stack.peek() operand_stack.pop() num2 = operand_stack.peek() operand_stack.pop() total = operators[opr](num2, num1) operand_stack.push(total) return operand_stack.peek() if __name__ == "__main__": equation = "(5 + ((4 * 2) * (2 + 3)))" print(f"{equation} = {dijkstras_two_stack_algorithm(equation)}")
https en wikipedia orgwikiinfixnotation https en wikipedia orgwikireversepolishnotation https en wikipedia orgwikishuntingyardalgorithm return integer value representing an operator s precedence or order of operation https en wikipedia orgwikiorderofoperations return the associativity of the operator char https en wikipedia orgwikioperatorassociativity infixtopostfix1234 traceback most recent call last valueerror mismatched parentheses infixtopostfix infixtopostfix32 3 2 infixtopostfix3456 3 4 5 6 infixtopostfix12345 1 2 3 4 5 infixtopostfixabcdefg a b c d e f g infixtopostfixxy5z2 x y 5 z 2 infixtopostfix232 2 3 2 precedences are equal return integer value representing an operator s precedence or order of operation https en wikipedia org wiki order_of_operations return the associativity of the operator char https en wikipedia org wiki operator_associativity infix_to_postfix 1 2 3 4 traceback most recent call last valueerror mismatched parentheses infix_to_postfix infix_to_postfix 3 2 3 2 infix_to_postfix 3 4 5 6 3 4 5 6 infix_to_postfix 1 2 3 4 5 1 2 3 4 5 infix_to_postfix a b c d e f g a b c d e f g infix_to_postfix x y 5 z 2 x y 5 z 2 infix_to_postfix 2 3 2 2 3 2 precedences are equal
from typing import Literal from .balanced_parentheses import balanced_parentheses from .stack import Stack PRECEDENCES: dict[str, int] = { "+": 1, "-": 1, "*": 2, "/": 2, "^": 3, } ASSOCIATIVITIES: dict[str, Literal["LR", "RL"]] = { "+": "LR", "-": "LR", "*": "LR", "/": "LR", "^": "RL", } def precedence(char: str) -> int: return PRECEDENCES.get(char, -1) def associativity(char: str) -> Literal["LR", "RL"]: return ASSOCIATIVITIES[char] def infix_to_postfix(expression_str: str) -> str: if not balanced_parentheses(expression_str): raise ValueError("Mismatched parentheses") stack: Stack[str] = Stack() postfix = [] for char in expression_str: if char.isalpha() or char.isdigit(): postfix.append(char) elif char == "(": stack.push(char) elif char == ")": while not stack.is_empty() and stack.peek() != "(": postfix.append(stack.pop()) stack.pop() else: while True: if stack.is_empty(): stack.push(char) break char_precedence = precedence(char) tos_precedence = precedence(stack.peek()) if char_precedence > tos_precedence: stack.push(char) break if char_precedence < tos_precedence: postfix.append(stack.pop()) continue if associativity(char) == "RL": stack.push(char) break postfix.append(stack.pop()) while not stack.is_empty(): postfix.append(stack.pop()) return " ".join(postfix) if __name__ == "__main__": from doctest import testmod testmod() expression = "a+b*(c^d-e)^(f+g*h)-i" print("Infix to Postfix Notation demonstration:\n") print("Infix notation: " + expression) print("Postfix notation: " + infix_to_postfix(expression))
output enter an infix equation a b c symbol stack postfix c c c b cb cb a cba cba abc infix abc prefix infix2postfixabc doctest normalizewhitespace symbol stack postfix a a a b ab ab c abc abc abc abc infix2postfix1a2b doctest normalizewhitespace symbol stack postfix 1 1 1 1 1 1 a 1a 1a 1a 2 1a2 1a2 b 1a2b 1a2b 1a2b 1a2b infix2postfix symbol stack postfix infix2postfix traceback most recent call last valueerror invalid expression infix2postfix traceback most recent call last indexerror list index out of range print table header for output infix2prefixabc doctest normalizewhitespace symbol stack postfix c c c b cb cb a cba cba abc infix2prefix1a2b doctest normalizewhitespace symbol stack postfix b b b 2 b2 b2 b2 a b2a b2a b2a b2a b2a 1 b2a1 b2a1 1a2b infix2prefix symbol stack postfix infix2prefix traceback most recent call last indexerror list index out of range infix2prefix traceback most recent call last valueerror invalid expression call infix2postfix on infix return reverse of postfix infix_2_postfix a b c doctest normalize_whitespace symbol stack postfix a a a b ab ab c abc abc abc abc infix_2_postfix 1 a 2 b doctest normalize_whitespace symbol stack postfix 1 1 1 1 1 1 a 1a 1a 1a 2 1a 2 1a 2 b 1a 2 b 1a 2 b 1a 2 b 1a 2 b infix_2_postfix symbol stack postfix infix_2_postfix traceback most recent call last valueerror invalid expression infix_2_postfix traceback most recent call last indexerror list index out of range priority of each operator print table header for output if x is alphabet digit add it to postfix if x is push to stack if x is pop stack until is encountered close bracket without open bracket pop stack add the content to postfix if stack is empty push x to stack while priority of x is not priority of element in the stack pop stack add to postfix push x to stack output in tabular format while stack is not empty open bracket with no close bracket pop stack add to postfix output in tabular format return postfix as str infix_2_prefix a b c doctest normalize_whitespace symbol stack postfix c c c b cb cb a cb a cb a a bc infix_2_prefix 1 a 2 b doctest normalize_whitespace symbol stack postfix b b b 2 b2 b2 b2 a b2a b2a b2a b2a b2a 1 b2a 1 b2a 1 1 a2b infix_2_prefix symbol stack postfix infix_2_prefix traceback most recent call last indexerror list index out of range infix_2_prefix traceback most recent call last valueerror invalid expression reverse the infix equation change to change to call infix_2_postfix on infix return reverse of postfix input an infix equation remove spaces from the input
def infix_2_postfix(infix: str) -> str: stack = [] post_fix = [] priority = { "^": 3, "*": 2, "/": 2, "%": 2, "+": 1, "-": 1, } print_width = max(len(infix), 7) print( "Symbol".center(8), "Stack".center(print_width), "Postfix".center(print_width), sep=" | ", ) print("-" * (print_width * 3 + 7)) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(x) elif x == "(": stack.append(x) elif x == ")": if len(stack) == 0: raise IndexError("list index out of range") while stack[-1] != "(": post_fix.append(stack.pop()) stack.pop() else: if len(stack) == 0: stack.append(x) else: while stack and stack[-1] != "(" and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop()) stack.append(x) print( x.center(8), ("".join(stack)).ljust(print_width), ("".join(post_fix)).ljust(print_width), sep=" | ", ) while len(stack) > 0: if stack[-1] == "(": raise ValueError("invalid expression") post_fix.append(stack.pop()) print( " ".center(8), ("".join(stack)).ljust(print_width), ("".join(post_fix)).ljust(print_width), sep=" | ", ) return "".join(post_fix) def infix_2_prefix(infix: str) -> str: reversed_infix = list(infix[::-1]) for i in range(len(reversed_infix)): if reversed_infix[i] == "(": reversed_infix[i] = ")" elif reversed_infix[i] == ")": reversed_infix[i] = "(" return (infix_2_postfix("".join(reversed_infix)))[::-1] if __name__ == "__main__": from doctest import testmod testmod() Infix = input("\nEnter an Infix Equation = ") Infix = "".join(Infix.split()) print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
get the next greatest element nge for all elements in a list maximum element present after the current one which is also greater than the current one nextgreatestelementslowarr expect true like nextgreatestelementslow but changes the loops to use enumerate instead of rangelen for the outer loop and for in a slice of arr for the inner loop nextgreatestelementfastarr expect true get the next greatest element nge for all elements in a list maximum element present after the current one which is also greater than the current one a naive way to solve this is to take two loops and check for the next bigger number but that will make the time complexity as on2 the better way to solve this would be to use a stack to keep track of maximum number giving a linear time solution nextgreatestelementarr expect true get the next greatest element nge for all elements in a list maximum element present after the current one which is also greater than the current one next_greatest_element_slow arr expect true like next_greatest_element_slow but changes the loops to use enumerate instead of range len for the outer loop and for in a slice of arr for the inner loop next_greatest_element_fast arr expect true get the next greatest element nge for all elements in a list maximum element present after the current one which is also greater than the current one a naive way to solve this is to take two loops and check for the next bigger number but that will make the time complexity as o n 2 the better way to solve this would be to use a stack to keep track of maximum number giving a linear time solution next_greatest_element arr expect true
from __future__ import annotations arr = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] expect = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def next_greatest_element_slow(arr: list[float]) -> list[float]: result = [] arr_size = len(arr) for i in range(arr_size): next_element: float = -1 for j in range(i + 1, arr_size): if arr[i] < arr[j]: next_element = arr[j] break result.append(next_element) return result def next_greatest_element_fast(arr: list[float]) -> list[float]: result = [] for i, outer in enumerate(arr): next_item: float = -1 for inner in arr[i + 1 :]: if outer < inner: next_item = inner break result.append(next_item) return result def next_greatest_element(arr: list[float]) -> list[float]: arr_size = len(arr) stack: list[float] = [] result: list[float] = [-1] * arr_size for index in reversed(range(arr_size)): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: result[index] = stack[-1] stack.append(arr[index]) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) setup = ( "from __main__ import arr, next_greatest_element_slow, " "next_greatest_element_fast, next_greatest_element" ) print( "next_greatest_element_slow():", timeit("next_greatest_element_slow(arr)", setup=setup), ) print( "next_greatest_element_fast():", timeit("next_greatest_element_fast(arr)", setup=setup), ) print( " next_greatest_element():", timeit("next_greatest_element(arr)", setup=setup), )
reverse polish nation is also known as polish postfix notation or simply postfix notation https en wikipedia orgwikireversepolishnotation classic examples of simple stack implementations valid operators are each operand may be an integer or another expression output enter a postfix equation space separated 5 6 9 symbol action stack 5 push5 5 6 push6 5 6 9 push9 5 6 9 pop9 5 6 pop6 5 push69 5 54 pop54 5 pop5 push554 59 result 59 defining valid unary operator symbols operators their respective operation converts the given data to the appropriate number if it is indeed a number else returns the data as it is with a false flag this function also serves as a check of whether the input is a number or not parameters token the data that needs to be converted to the appropriate operator or number returns float or str returns a float if token is a number or a str if token is an operator evaluate postfix expression using a stack evaluate0 0 0 evaluate0 0 0 evaluate1 1 0 evaluate1 1 0 evaluate1 1 1 1 evaluate2 1 3 9 0 evaluate2 1 9 3 11 7 evaluate2 1 9 3 0 30000000000000027 evaluate4 13 5 6 6 evaluate2 3 1 0 evaluate4 5 6 26 0 evaluate 0 evaluate4 6 7 9 8 traceback most recent call last arithmeticerror input is not a valid postfix expression parameters postfix the postfix expression is tokenized into operators and operands and stored as a python list verbose display stack contents while evaluating the expression if verbose is true returns float the evaluated value checking the list to find out whether the postfix expression is valid print table header output in tabular format if x is operator if only 1 value is inside the stack and or is encountered then this is unary or case output in tabular format output in tabular format output in tabular format evaluate the 2 values popped from stack push result to stack output in tabular format if everything is executed correctly the stack will contain only one element which is the result create a loop so that the user can evaluate postfix expressions multiple times defining valid unary operator symbols operators their respective operation converts the given data to the appropriate number if it is indeed a number else returns the data as it is with a false flag this function also serves as a check of whether the input is a number or not parameters token the data that needs to be converted to the appropriate operator or number returns float or str returns a float if token is a number or a str if token is an operator evaluate postfix expression using a stack evaluate 0 0 0 evaluate 0 0 0 evaluate 1 1 0 evaluate 1 1 0 evaluate 1 1 1 1 evaluate 2 1 3 9 0 evaluate 2 1 9 3 11 7 evaluate 2 1 9 3 0 30000000000000027 evaluate 4 13 5 6 6 evaluate 2 3 1 0 evaluate 4 5 6 26 0 evaluate 0 evaluate 4 6 7 9 8 traceback most recent call last arithmeticerror input is not a valid postfix expression parameters post_fix the postfix expression is tokenized into operators and operands and stored as a python list verbose display stack contents while evaluating the expression if verbose is true returns float the evaluated value checking the list to find out whether the postfix expression is valid print table header append x to stack output in tabular format if x is operator if only 1 value is inside the stack and or is encountered then this is unary or case pop stack negate b output in tabular format pop stack output in tabular format pop stack output in tabular format evaluate the 2 values popped from stack push result to stack type ignore index output in tabular format if everything is executed correctly the stack will contain only one element which is the result create a loop so that the user can evaluate postfix expressions multiple times
UNARY_OP_SYMBOLS = ("-", "+") OPERATORS = { "^": lambda p, q: p**q, "*": lambda p, q: p * q, "/": lambda p, q: p / q, "+": lambda p, q: p + q, "-": lambda p, q: p - q, } def parse_token(token: str | float) -> float | str: if token in OPERATORS: return token try: return float(token) except ValueError: msg = f"{token} is neither a number nor a valid operator" raise ValueError(msg) def evaluate(post_fix: list[str], verbose: bool = False) -> float: if not post_fix: return 0 valid_expression = [parse_token(token) for token in post_fix] if verbose: print("Symbol".center(8), "Action".center(12), "Stack", sep=" | ") print("-" * (30 + len(post_fix))) stack = [] for x in valid_expression: if x not in OPERATORS: stack.append(x) if verbose: print( f"{x}".rjust(8), f"push({x})".ljust(12), stack, sep=" | ", ) continue if x in UNARY_OP_SYMBOLS and len(stack) < 2: b = stack.pop() if x == "-": b *= -1 stack.append(b) if verbose: print( "".rjust(8), f"pop({b})".ljust(12), stack, sep=" | ", ) print( str(x).rjust(8), f"push({x}{b})".ljust(12), stack, sep=" | ", ) continue b = stack.pop() if verbose: print( "".rjust(8), f"pop({b})".ljust(12), stack, sep=" | ", ) a = stack.pop() if verbose: print( "".rjust(8), f"pop({a})".ljust(12), stack, sep=" | ", ) stack.append(OPERATORS[x](a, b)) if verbose: print( f"{x}".rjust(8), f"push({a}{x}{b})".ljust(12), stack, sep=" | ", ) if len(stack) != 1: raise ArithmeticError("Input is not a valid postfix expression") return float(stack[0]) if __name__ == "__main__": while True: expression = input("Enter a Postfix Expression (space separated): ").split(" ") prompt = "Do you want to see stack contents while evaluating? [y/N]: " verbose = input(prompt).strip().lower() == "y" output = evaluate(expression, verbose) print("Result = ", output) prompt = "Do you want to enter another expression? [y/N]: " if input(prompt).strip().lower() != "y": break
python3 program to evaluate a prefix expression return true if the given char c is an operand e g it is a number isoperand1 true isoperand false evaluate a given expression in prefix notation asserts that the given expression is valid evaluate 9 2 6 21 evaluate 10 2 4 1 4 0 iterate over the string in reverse order push operand to stack pop values from stack can calculate the result push the result onto the stack again driver code return true if the given char c is an operand e g it is a number is_operand 1 true is_operand false evaluate a given expression in prefix notation asserts that the given expression is valid evaluate 9 2 6 21 evaluate 10 2 4 1 4 0 iterate over the string in reverse order push operand to stack pop values from stack can calculate the result push the result onto the stack again driver code
calc = { "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y, } def is_operand(c): return c.isdigit() def evaluate(expression): stack = [] for c in expression.split()[::-1]: if is_operand(c): stack.append(int(c)) else: o1 = stack.pop() o2 = stack.pop() stack.append(calc[c](o1, o2)) return stack.pop() if __name__ == "__main__": test_expression = "+ 9 * 2 6" print(evaluate(test_expression)) test_expression = "/ * 10 2 + 4 1 " print(evaluate(test_expression))
a stack is an abstract data type that serves as a collection of elements with two principal operations push and pop push adds an element to the top of the stack and pop removes an element from the top of a stack the order in which elements come off of a stack are last in first out lifo https en wikipedia orgwikistackabstractdatatype push an element to the top of the stack s stack2 stack size 2 s push10 s push20 prints 10 20 s stack1 stack size 1 s push10 s push20 traceback most recent call last datastructures stacks stack stackoverflowerror pop an element off of the top of the stack s stack s push5 s push10 s pop 10 stack pop traceback most recent call last datastructures stacks stack stackunderflowerror peek at the topmost element of the stack s stack s push5 s push10 s peek 10 stack peek traceback most recent call last datastructures stacks stack stackunderflowerror check if a stack is empty s stack s isempty true s stack s push10 s isempty false s stack s isfull false s stack1 s push10 s isfull true return the size of the stack s stack3 s size 0 s stack3 s push10 s size 1 s stack3 s push10 s push20 s size 2 check if item is in stack s stack3 s push10 10 in s true s stack3 s push10 20 in s false teststack a stack is an abstract data type that serves as a collection of elements with two principal operations push and pop push adds an element to the top of the stack and pop removes an element from the top of a stack the order in which elements come off of a stack are last in first out lifo https en wikipedia org wiki stack_ abstract_data_type push an element to the top of the stack s stack 2 stack size 2 s push 10 s push 20 print s 10 20 s stack 1 stack size 1 s push 10 s push 20 traceback most recent call last data_structures stacks stack stackoverflowerror pop an element off of the top of the stack s stack s push 5 s push 10 s pop 10 stack pop traceback most recent call last data_structures stacks stack stackunderflowerror peek at the top most element of the stack s stack s push 5 s push 10 s peek 10 stack peek traceback most recent call last data_structures stacks stack stackunderflowerror check if a stack is empty s stack s is_empty true s stack s push 10 s is_empty false s stack s is_full false s stack 1 s push 10 s is_full true return the size of the stack s stack 3 s size 0 s stack 3 s push 10 s size 1 s stack 3 s push 10 s push 20 s size 2 check if item is in stack s stack 3 s push 10 10 in s true s stack 3 s push 10 20 in s false test_stack this should not happen this should happen this should not happen this should happen this should not happen this should happen
from __future__ import annotations from typing import Generic, TypeVar T = TypeVar("T") class StackOverflowError(BaseException): pass class StackUnderflowError(BaseException): pass class Stack(Generic[T]): def __init__(self, limit: int = 10): self.stack: list[T] = [] self.limit = limit def __bool__(self) -> bool: return bool(self.stack) def __str__(self) -> str: return str(self.stack) def push(self, data: T) -> None: if len(self.stack) >= self.limit: raise StackOverflowError self.stack.append(data) def pop(self) -> T: if not self.stack: raise StackUnderflowError return self.stack.pop() def peek(self) -> T: if not self.stack: raise StackUnderflowError return self.stack[-1] def is_empty(self) -> bool: return not bool(self.stack) def is_full(self) -> bool: return self.size() == self.limit def size(self) -> int: return len(self.stack) def __contains__(self, item: T) -> bool: return item in self.stack def test_stack() -> None: stack: Stack[int] = Stack(10) assert bool(stack) is False assert stack.is_empty() is True assert stack.is_full() is False assert str(stack) == "[]" try: _ = stack.pop() raise AssertionError except StackUnderflowError: assert True try: _ = stack.peek() raise AssertionError except StackUnderflowError: assert True for i in range(10): assert stack.size() == i stack.push(i) assert bool(stack) assert not stack.is_empty() assert stack.is_full() assert str(stack) == str(list(range(10))) assert stack.pop() == 9 assert stack.peek() == 8 stack.push(100) assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100]) try: stack.push(200) raise AssertionError except StackOverflowError: assert True assert not stack.is_empty() assert stack.size() == 10 assert 5 in stack assert 55 not in stack if __name__ == "__main__": test_stack() import doctest doctest.testmod()
https www geeksforgeeks orgimplementstackusingqueue stack stackwithqueues stack push1 stack push2 stack push3 stack peek 3 stack pop 3 stack peek 2 stack pop 2 stack pop 1 stack peek is none true stack pop traceback most recent call last indexerror pop from an empty deque https www geeksforgeeks org implement stack using queue stack stackwithqueues stack push 1 stack push 2 stack push 3 stack peek 3 stack pop 3 stack peek 2 stack pop 2 stack pop 1 stack peek is none true stack pop traceback most recent call last indexerror pop from an empty deque
from __future__ import annotations from collections import deque from dataclasses import dataclass, field @dataclass class StackWithQueues: main_queue: deque[int] = field(default_factory=deque) temp_queue: deque[int] = field(default_factory=deque) def push(self, item: int) -> None: self.temp_queue.append(item) while self.main_queue: self.temp_queue.append(self.main_queue.popleft()) self.main_queue, self.temp_queue = self.temp_queue, self.main_queue def pop(self) -> int: return self.main_queue.popleft() def peek(self) -> int | None: return self.main_queue[0] if self.main_queue else None if __name__ == "__main__": import doctest doctest.testmod() stack: StackWithQueues | None = StackWithQueues() while stack: print("\nChoose operation:") print("1. Push") print("2. Pop") print("3. Peek") print("4. Quit") choice = input("Enter choice (1/2/3/4): ") if choice == "1": element = int(input("Enter an integer to push: ").strip()) stack.push(element) print(f"{element} pushed onto the stack.") elif choice == "2": popped_element = stack.pop() if popped_element is not None: print(f"Popped element: {popped_element}") else: print("Stack is empty.") elif choice == "3": peeked_element = stack.peek() if peeked_element is not None: print(f"Top element: {peeked_element}") else: print("Stack is empty.") elif choice == "4": del stack stack = None else: print("Invalid choice. Please try again.")
a complete working python program to demonstrate all stack operations using a doubly linked list stack stack stack isempty true stack printstack stack elements are for i in range4 stack pushi stack isempty false stack printstack stack elements are 3210 stack top 3 lenstack 4 stack pop 3 stack printstack stack elements are 210 add a node to the stack if self head is none self head nodedata else newnode nodedata self head prev newnode newnode next self head newnode prev none self head newnode def popself t none return the top element of the stack return self head data if self head is not none else none def lenself int temp self head count 0 while temp is not none count 1 temp temp next return count def isemptyself bool return self head is none def printstackself none printstack elements are temp self head while temp is not none printtemp data end temp temp next code execution starts here if name main start with the empty stack stack stackint stack insert 4 at the beginning so stack becomes 4none printstack operations using doubly linkedlist stack push4 insert 5 at the beginning so stack becomes 45none stack push5 insert 6 at the beginning so stack becomes 456none stack push6 insert 7 at the beginning so stack becomes 4567none stack push7 print the stack stack printstack print the top element printntop element is stack top print the stack size printsize of the stack is lenstack pop the top element stack pop pop the top element stack pop two elements have now been popped off stack printstack print true if the stack is empty else false printnstack is empty stack isempty a complete working python program to demonstrate all stack operations using a doubly linked list assign data initialize next as null initialize prev as null stack stack stack is_empty true stack print_stack stack elements are for i in range 4 stack push i stack is_empty false stack print_stack stack elements are 3 2 1 0 stack top 3 len stack 4 stack pop 3 stack print_stack stack elements are 2 1 0 add a node to the stack pop the top element off the stack return the top element of the stack code execution starts here start with the empty stack insert 4 at the beginning so stack becomes 4 none insert 5 at the beginning so stack becomes 4 5 none insert 6 at the beginning so stack becomes 4 5 6 none insert 7 at the beginning so stack becomes 4 5 6 7 none print the stack print the top element print the stack size pop the top element pop the top element two elements have now been popped off print true if the stack is empty else false
from __future__ import annotations from typing import Generic, TypeVar T = TypeVar("T") class Node(Generic[T]): def __init__(self, data: T): self.data = data self.next: Node[T] | None = None self.prev: Node[T] | None = None class Stack(Generic[T]): def __init__(self) -> None: self.head: Node[T] | None = None def push(self, data: T) -> None: if self.head is None: self.head = Node(data) else: new_node = Node(data) self.head.prev = new_node new_node.next = self.head new_node.prev = None self.head = new_node def pop(self) -> T | None: if self.head is None: return None else: assert self.head is not None temp = self.head.data self.head = self.head.next if self.head is not None: self.head.prev = None return temp def top(self) -> T | None: return self.head.data if self.head is not None else None def __len__(self) -> int: temp = self.head count = 0 while temp is not None: count += 1 temp = temp.next return count def is_empty(self) -> bool: return self.head is None def print_stack(self) -> None: print("stack elements are:") temp = self.head while temp is not None: print(temp.data, end="->") temp = temp.next if __name__ == "__main__": stack: Stack[int] = Stack() print("Stack operations using Doubly LinkedList") stack.push(4) stack.push(5) stack.push(6) stack.push(7) stack.print_stack() print("\nTop element is ", stack.top()) print("Size of the stack is ", len(stack)) stack.pop() stack.pop() stack.print_stack() print("\nstack is empty:", stack.is_empty())
a stack using a linked list like structure from future import annotations from collections abc import iterator from typing import generic typevar t typevart class nodegenerict def initself data t self data data self next nodet none none def strself str return fself data class linkedstackgenerict def initself none self top nodet none none def iterself iteratort node self top while node yield node data node node next def strself str return joinstritem for item in self def lenself int return lentupleiterself def isemptyself bool return self top is none def pushself item t none node nodeitem if not self isempty node next self top self top node def popself t if self isempty raise indexerrorpop from empty stack assert isinstanceself top node popnode self top self top self top next return popnode data def peekself t if self isempty raise indexerrorpeek from empty stack assert self top is not none return self top data def clearself none self top none if name main from doctest import testmod testmod linked list stack implementing push to top pop from top and is_empty stack linkedstack stack is_empty true stack push 5 stack push 9 stack push python stack is_empty false stack pop python stack push algorithms stack pop algorithms stack pop 9 stack pop 5 stack is_empty true stack pop traceback most recent call last indexerror pop from empty stack stack linkedstack stack push c stack push b stack push a str stack a b c stack linkedstack len stack 0 true stack push c stack push b stack push a len stack 3 true stack linkedstack stack is_empty true stack push 1 stack is_empty false stack linkedstack stack push python stack push java stack push c str stack c java python stack linkedstack stack pop traceback most recent call last indexerror pop from empty stack stack push c stack push b stack push a stack pop a true stack pop b true stack pop c true stack linkedstack stack push java stack push c stack push python stack peek python stack linkedstack stack push java stack push c stack push python str stack python c java stack clear len stack 0 true
from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar T = TypeVar("T") class Node(Generic[T]): def __init__(self, data: T): self.data = data self.next: Node[T] | None = None def __str__(self) -> str: return f"{self.data}" class LinkedStack(Generic[T]): def __init__(self) -> None: self.top: Node[T] | None = None def __iter__(self) -> Iterator[T]: node = self.top while node: yield node.data node = node.next def __str__(self) -> str: return "->".join([str(item) for item in self]) def __len__(self) -> int: return len(tuple(iter(self))) def is_empty(self) -> bool: return self.top is None def push(self, item: T) -> None: node = Node(item) if not self.is_empty(): node.next = self.top self.top = node def pop(self) -> T: if self.is_empty(): raise IndexError("pop from empty stack") assert isinstance(self.top, Node) pop_node = self.top self.top = self.top.next return pop_node.data def peek(self) -> T: if self.is_empty(): raise IndexError("peek from empty stack") assert self.top is not None return self.top.data def clear(self) -> None: self.top = None if __name__ == "__main__": from doctest import testmod testmod()
the stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stock s price for all n days the span si of the stock s price on a given day i is defined as the maximum number of consecutive days just before the given day for which the price of the stock on the current day is less than or equal to its price on the given day create a stack and push index of fist element to it span value of first element is always 1 calculate span values for rest of the elements pop elements from stack while stack is not empty and top of stack is smaller than pricei if stack becomes empty then pricei is greater than all elements on left of it i e price0 price1 pricei1 else the pricei is greater than elements after top of stack push this element to stack a utility function to print elements of array driver program to test above function fill the span values in array s print the calculated span values create a stack and push index of fist element to it span value of first element is always 1 calculate span values for rest of the elements pop elements from stack while stack is not empty and top of stack is smaller than price i if stack becomes empty then price i is greater than all elements on left of it i e price 0 price 1 price i 1 else the price i is greater than elements after top of stack push this element to stack a utility function to print elements of array driver program to test above function fill the span values in array s print the calculated span values
def calculation_span(price, s): n = len(price) st = [] st.append(0) s[0] = 1 for i in range(1, n): while len(st) > 0 and price[st[0]] <= price[i]: st.pop() s[i] = i + 1 if len(st) <= 0 else (i - st[0]) st.append(i) def print_array(arr, n): for i in range(n): print(arr[i], end=" ") price = [10, 4, 5, 90, 120, 80] S = [0 for i in range(len(price) + 1)] calculation_span(price, S) print_array(S, len(price))
a radix tree is a data structure that represents a spaceoptimized trie prefix tree in whicheach node that is the only child is merged with its parent https en wikipedia orgwikiradixtree mapping from the first character of the prefix of the node a node will be a leaf if the tree contains its word compute the common substring of the prefix of the node and a word args word str word to compare returns str str str common substring remaining prefix remaining word radixnodemyprefix matchmystring my prefix string insert many words in the tree args words liststr list of words radixnodemyprefix insertmanymystring hello insert a word into the tree args word str word to insert radixnodemyprefix insertmystring root radixnode root insertmany myprefix myprefixa myprefixaa root printtree myprefix leaf a leaf a leaf case 1 if the word is the prefix of the node solution we set the current node as leaf case 2 the node has no edges that have a prefix to the word solution we create an edge from the current node to a new one containing the word case 3 the node prefix is equal to the matching solution we insert remaining word on the next node case 4 the word is greater equal to the matching solution create a node in between both nodes change prefixes and add the new node for the remaining word returns if the word is on the tree args word str word to check returns bool true if the word appears on the tree radixnodemyprefix findmystring false if there is remaining prefix the word can t be on the tree this applies when the word and the prefix are equal we have word remaining so we check the next node deletes a word from the tree if it exists args word str word to be deleted returns bool true if the word was found and deleted false if word is not found radixnodemyprefix deletemystring false if there is remaining prefix the word can t be on the tree we have word remaining so we check the next node if it is not a leaf we don t have to delete we delete the nodes if no edges go from it we merge the current node with its only child if there is more than 1 edge we just mark it as nonleaf if there is 1 edge we merge it with its child print the tree args height int optional height of the printed node pytests mapping from the first character of the prefix of the node a node will be a leaf if the tree contains its word compute the common substring of the prefix of the node and a word args word str word to compare returns str str str common substring remaining prefix remaining word radixnode myprefix match mystring my prefix string insert many words in the tree args words list str list of words radixnode myprefix insert_many mystring hello insert a word into the tree args word str word to insert radixnode myprefix insert mystring root radixnode root insert_many myprefix myprefixa myprefixaa root print_tree myprefix leaf a leaf a leaf case 1 if the word is the prefix of the node solution we set the current node as leaf case 2 the node has no edges that have a prefix to the word solution we create an edge from the current node to a new one containing the word case 3 the node prefix is equal to the matching solution we insert remaining word on the next node case 4 the word is greater equal to the matching solution create a node in between both nodes change prefixes and add the new node for the remaining word returns if the word is on the tree args word str word to check returns bool true if the word appears on the tree radixnode myprefix find mystring false if there is remaining prefix the word can t be on the tree this applies when the word and the prefix are equal we have word remaining so we check the next node deletes a word from the tree if it exists args word str word to be deleted returns bool true if the word was found and deleted false if word is not found radixnode myprefix delete mystring false if there is remaining prefix the word can t be on the tree we have word remaining so we check the next node if it is not a leaf we don t have to delete we delete the nodes if no edges go from it we merge the current node with its only child if there is more than 1 edge we just mark it as non leaf if there is 1 edge we merge it with its child print the tree args height int optional height of the printed node pytests
class RadixNode: def __init__(self, prefix: str = "", is_leaf: bool = False) -> None: self.nodes: dict[str, RadixNode] = {} self.is_leaf = is_leaf self.prefix = prefix def match(self, word: str) -> tuple[str, str, str]: x = 0 for q, w in zip(self.prefix, word): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def insert_many(self, words: list[str]) -> None: for word in words: self.insert(word) def insert(self, word: str) -> None: if self.prefix == word and not self.is_leaf: self.is_leaf = True elif word[0] not in self.nodes: self.nodes[word[0]] = RadixNode(prefix=word, is_leaf=True) else: incoming_node = self.nodes[word[0]] matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) if remaining_prefix == "": self.nodes[matching_string[0]].insert(remaining_word) else: incoming_node.prefix = remaining_prefix aux_node = self.nodes[matching_string[0]] self.nodes[matching_string[0]] = RadixNode(matching_string, False) self.nodes[matching_string[0]].nodes[remaining_prefix[0]] = aux_node if remaining_word == "": self.nodes[matching_string[0]].is_leaf = True else: self.nodes[matching_string[0]].insert(remaining_word) def find(self, word: str) -> bool: incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False else: matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) if remaining_prefix != "": return False elif remaining_word == "": return incoming_node.is_leaf else: return incoming_node.find(remaining_word) def delete(self, word: str) -> bool: incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False else: matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) if remaining_prefix != "": return False elif remaining_word != "": return incoming_node.delete(remaining_word) else: if not incoming_node.is_leaf: return False else: if len(incoming_node.nodes) == 0: del self.nodes[word[0]] if len(self.nodes) == 1 and not self.is_leaf: merging_node = next(iter(self.nodes.values())) self.is_leaf = merging_node.is_leaf self.prefix += merging_node.prefix self.nodes = merging_node.nodes elif len(incoming_node.nodes) > 1: incoming_node.is_leaf = False else: merging_node = next(iter(incoming_node.nodes.values())) incoming_node.is_leaf = merging_node.is_leaf incoming_node.prefix += merging_node.prefix incoming_node.nodes = merging_node.nodes return True def print_tree(self, height: int = 0) -> None: if self.prefix != "": print("-" * height, self.prefix, " (leaf)" if self.is_leaf else "") for value in self.nodes.values(): value.print_tree(height + 1) def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = RadixNode() root.insert_many(words) assert all(root.find(word) for word in words) assert not root.find("bandanas") assert not root.find("apps") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def pytests() -> None: assert test_trie() def main() -> None: root = RadixNode() words = "banana bananas bandanas bandana band apple all beast".split() root.insert_many(words) print("Words:", words) print("Tree:") root.print_tree() if __name__ == "__main__": main()
a trieprefix tree is a kind of search tree used to provide quick lookup of wordspatterns in a set of words a basic trie however has on2 space complexity making it impractical in practice it however provides omaxsearchstring length of longest word lookup time making it an optimal approach when space is not an issue inserts a list of words into the trie param words list of string words return none inserts a word into the trie param word word to be inserted return none tries to find word in a trie param word word to look for return returns true if word is found false otherwise deletes a word in a trie param word word to delete return none if word does not exist if char not in current trie node flag to check if node can be deleted prints all the words in a trie param node root node of trie param word word variable should be empty at start return none printwordsroot pytests mapping from char to trienode inserts a list of words into the trie param words list of string words return none inserts a word into the trie param word word to be inserted return none tries to find word in a trie param word word to look for return returns true if word is found false otherwise deletes a word in a trie param word word to delete return none if word does not exist if char not in current trie node flag to check if node can be deleted prints all the words in a trie param node root node of trie param word word variable should be empty at start return none print_words root pytests
class TrieNode: def __init__(self) -> None: self.nodes: dict[str, TrieNode] = {} self.is_leaf = False def insert_many(self, words: list[str]) -> None: for word in words: self.insert(word) def insert(self, word: str) -> None: curr = self for char in word: if char not in curr.nodes: curr.nodes[char] = TrieNode() curr = curr.nodes[char] curr.is_leaf = True def find(self, word: str) -> bool: curr = self for char in word: if char not in curr.nodes: return False curr = curr.nodes[char] return curr.is_leaf def delete(self, word: str) -> None: def _delete(curr: TrieNode, word: str, index: int) -> bool: if index == len(word): if not curr.is_leaf: return False curr.is_leaf = False return len(curr.nodes) == 0 char = word[index] char_node = curr.nodes.get(char) if not char_node: return False delete_curr = _delete(char_node, word, index + 1) if delete_curr: del curr.nodes[char] return len(curr.nodes) == 0 return delete_curr _delete(self, word, 0) def print_words(node: TrieNode, word: str) -> None: if node.is_leaf: print(word, end=" ") for key, value in node.nodes.items(): print_words(value, word + key) def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = TrieNode() root.insert_many(words) assert all(root.find(word) for word in words) assert root.find("banana") assert not root.find("bandanas") assert not root.find("apps") assert root.find("apple") assert root.find("all") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_trie() def main() -> None: print_results("Testing trie functionality", test_trie()) if __name__ == "__main__": main()
change the brightness of a pil image to a given level fundamental transformationoperation that ll be performed on every bit load image change brightness to 100 change the brightness of a pil image to a given level fundamental transformation operation that ll be performed on every bit load image change brightness to 100
from PIL import Image def change_brightness(img: Image, level: float) -> Image: def brightness(c: int) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("level must be between -255.0 (black) and 255.0 (white)") return img.point(brightness) if __name__ == "__main__": with Image.open("image_data/lena.jpg") as img: brigt_img = change_brightness(img, 100) brigt_img.save("image_data/lena_brightness.png", format="png")
changing contrast with pil this algorithm is used in https noivce pythonanywhere com python web app psfblack true ruff true function to change contrast fundamental transformationoperation that ll be performed on every bit load image change contrast to 170 function to change contrast fundamental transformation operation that ll be performed on every bit load image change contrast to 170
from PIL import Image def change_contrast(img: Image, level: int) -> Image: factor = (259 * (level + 255)) / (255 * (259 - level)) def contrast(c: int) -> int: return int(128 + factor * (c - 128)) return img.point(contrast) if __name__ == "__main__": with Image.open("image_data/lena.jpg") as img: cont_img = change_contrast(img, 170) cont_img.save("image_data/lena_high_contrast.png", format="png")
implemented an algorithm using opencv to convert a colored image into its negative getting number of pixels in the image converting each pixel s color to its negative read original image convert to its negative show result image getting number of pixels in the image converting each pixel s color to its negative read original image convert to its negative show result image
from cv2 import destroyAllWindows, imread, imshow, waitKey def convert_to_negative(img): pixel_h, pixel_v = img.shape[0], img.shape[1] for i in range(pixel_h): for j in range(pixel_v): img[i][j] = [255, 255, 255] - img[i][j] return img if __name__ == "__main__": img = imread("image_data/lena.jpg", 1) neg = convert_to_negative(img) imshow("negative of original image", img) waitKey(0) destroyAllWindows()
implementation burke s algorithm dithering burke s algorithm is using for converting grayscale image to black and white version source source https en wikipedia orgwikidither note best results are given with threshold 12 max greyscale value this implementation get rgb image and converts it to greyscale in runtime max greyscale value for ffffff error table size 4 columns and 1 row greater than input image because of lack of if statements burkes getgreyscale3 4 5 4 185 burkes getgreyscale0 0 0 0 0 burkes getgreyscale255 255 255 255 0 formula from https en wikipedia orgwikihslandhsv cf lightness section and fig 13c we use the first of four possible burkes error propagation is current pixel 832 432 232 432 832 432 232 create burke s instances with original images in greyscale burke s algorithm is using for converting grayscale image to black and white version source source https en wikipedia org wiki dither note best results are given with threshold 1 2 max greyscale value this implementation get rgb image and converts it to greyscale in runtime max greyscale value for ffffff error table size 4 columns and 1 row greater than input image because of lack of if statements burkes get_greyscale 3 4 5 4 185 burkes get_greyscale 0 0 0 0 0 burkes get_greyscale 255 255 255 255 0 formula from https en wikipedia org wiki hsl_and_hsv cf lightness section and fig 13c we use the first of four possible burkes error propagation is current pixel 8 32 4 32 2 32 4 32 8 32 4 32 2 32 create burke s instances with original images in greyscale
import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class Burkes: def __init__(self, input_img, threshold: int): self.min_threshold = 0 self.max_threshold = int(self.get_greyscale(255, 255, 255)) if not self.min_threshold < threshold < self.max_threshold: msg = f"Factor value should be from 0 to {self.max_threshold}" raise ValueError(msg) self.input_img = input_img self.threshold = threshold self.width, self.height = self.input_img.shape[1], self.input_img.shape[0] self.error_table = [ [0 for _ in range(self.height + 4)] for __ in range(self.width + 1) ] self.output_img = np.ones((self.width, self.height, 3), np.uint8) * 255 @classmethod def get_greyscale(cls, blue: int, green: int, red: int) -> float: return 0.114 * blue + 0.587 * green + 0.299 * red def process(self) -> None: for y in range(self.height): for x in range(self.width): greyscale = int(self.get_greyscale(*self.input_img[y][x])) if self.threshold > greyscale + self.error_table[y][x]: self.output_img[y][x] = (0, 0, 0) current_error = greyscale + self.error_table[y][x] else: self.output_img[y][x] = (255, 255, 255) current_error = greyscale + self.error_table[y][x] - 255 self.error_table[y][x + 1] += int(8 / 32 * current_error) self.error_table[y][x + 2] += int(4 / 32 * current_error) self.error_table[y + 1][x] += int(8 / 32 * current_error) self.error_table[y + 1][x + 1] += int(4 / 32 * current_error) self.error_table[y + 1][x + 2] += int(2 / 32 * current_error) self.error_table[y + 1][x - 1] += int(4 / 32 * current_error) self.error_table[y + 1][x - 2] += int(2 / 32 * current_error) if __name__ == "__main__": burkes_instances = [ Burkes(imread("image_data/lena.jpg", 1), threshold) for threshold in (1, 126, 130, 140) ] for burkes in burkes_instances: burkes.process() for burkes in burkes_instances: imshow( f"Original image with dithering threshold: {burkes.threshold}", burkes.output_img, ) waitKey(0) destroyAllWindows()
nonmaximum suppression if the edge strength of the current pixel is the largest compared to the other pixels in the mask with the same direction the value will be preserved otherwise the value will be suppressed highlow threshold detection if an edge pixels gradient value is higher than the high threshold value it is marked as a strong edge pixel if an edge pixels gradient value is smaller than the high threshold value and larger than the low threshold value it is marked as a weak edge pixel if an edge pixel s value is smaller than the low threshold value it will be suppressed edge tracking usually a weak edge pixel caused from true edges will be connected to a strong edge pixel while noise responses are unconnected as long as there is one strong edge pixel that is involved in its 8connected neighborhood that weak edge point can be identified as one that should be preserved gaussianfilter get the gradient and degree by sobelfilter read original image in gray mode canny edge detection non maximum suppression if the edge strength of the current pixel is the largest compared to the other pixels in the mask with the same direction the value will be preserved otherwise the value will be suppressed high low threshold detection if an edge pixel s gradient value is higher than the high threshold value it is marked as a strong edge pixel if an edge pixel s gradient value is smaller than the high threshold value and larger than the low threshold value it is marked as a weak edge pixel if an edge pixel s value is smaller than the low threshold value it will be suppressed edge tracking usually a weak edge pixel caused from true edges will be connected to a strong edge pixel while noise responses are unconnected as long as there is one strong edge pixel that is involved in its 8 connected neighborhood that weak edge point can be identified as one that should be preserved gaussian_filter get the gradient and degree by sobel_filter read original image in gray mode canny edge detection
import cv2 import numpy as np from digital_image_processing.filters.convolve import img_convolve from digital_image_processing.filters.sobel_filter import sobel_filter PI = 180 def gen_gaussian_kernel(k_size, sigma): center = k_size // 2 x, y = np.mgrid[0 - center : k_size - center, 0 - center : k_size - center] g = ( 1 / (2 * np.pi * sigma) * np.exp(-(np.square(x) + np.square(y)) / (2 * np.square(sigma))) ) return g def suppress_non_maximum(image_shape, gradient_direction, sobel_grad): destination = np.zeros(image_shape) for row in range(1, image_shape[0] - 1): for col in range(1, image_shape[1] - 1): direction = gradient_direction[row, col] if ( 0 <= direction < PI / 8 or 15 * PI / 8 <= direction <= 2 * PI or 7 * PI / 8 <= direction <= 9 * PI / 8 ): w = sobel_grad[row, col - 1] e = sobel_grad[row, col + 1] if sobel_grad[row, col] >= w and sobel_grad[row, col] >= e: destination[row, col] = sobel_grad[row, col] elif ( PI / 8 <= direction < 3 * PI / 8 or 9 * PI / 8 <= direction < 11 * PI / 8 ): sw = sobel_grad[row + 1, col - 1] ne = sobel_grad[row - 1, col + 1] if sobel_grad[row, col] >= sw and sobel_grad[row, col] >= ne: destination[row, col] = sobel_grad[row, col] elif ( 3 * PI / 8 <= direction < 5 * PI / 8 or 11 * PI / 8 <= direction < 13 * PI / 8 ): n = sobel_grad[row - 1, col] s = sobel_grad[row + 1, col] if sobel_grad[row, col] >= n and sobel_grad[row, col] >= s: destination[row, col] = sobel_grad[row, col] elif ( 5 * PI / 8 <= direction < 7 * PI / 8 or 13 * PI / 8 <= direction < 15 * PI / 8 ): nw = sobel_grad[row - 1, col - 1] se = sobel_grad[row + 1, col + 1] if sobel_grad[row, col] >= nw and sobel_grad[row, col] >= se: destination[row, col] = sobel_grad[row, col] return destination def detect_high_low_threshold( image_shape, destination, threshold_low, threshold_high, weak, strong ): for row in range(1, image_shape[0] - 1): for col in range(1, image_shape[1] - 1): if destination[row, col] >= threshold_high: destination[row, col] = strong elif destination[row, col] <= threshold_low: destination[row, col] = 0 else: destination[row, col] = weak def track_edge(image_shape, destination, weak, strong): for row in range(1, image_shape[0]): for col in range(1, image_shape[1]): if destination[row, col] == weak: if 255 in ( destination[row, col + 1], destination[row, col - 1], destination[row - 1, col], destination[row + 1, col], destination[row - 1, col - 1], destination[row + 1, col - 1], destination[row - 1, col + 1], destination[row + 1, col + 1], ): destination[row, col] = strong else: destination[row, col] = 0 def canny(image, threshold_low=15, threshold_high=30, weak=128, strong=255): gaussian_out = img_convolve(image, gen_gaussian_kernel(9, sigma=1.4)) sobel_grad, sobel_theta = sobel_filter(gaussian_out) gradient_direction = PI + np.rad2deg(sobel_theta) destination = suppress_non_maximum(image.shape, gradient_direction, sobel_grad) detect_high_low_threshold( image.shape, destination, threshold_low, threshold_high, weak, strong ) track_edge(image.shape, destination, weak, strong) return destination if __name__ == "__main__": lena = cv2.imread(r"../image_data/lena.jpg", 0) canny_destination = canny(lena) cv2.imshow("canny", canny_destination) cv2.waitKey(0)
implementation of bilateral filter inputs img a 2d image with values in between 0 and 1 vars variance in space dimension vari variance in intensity n kernel sizemust be an odd number output img a 2d zero padded image with values in between 0 and 1 for applying gaussian function for each element in matrix creates a gaussian kernel of given dimension for applying gaussian function for each element in matrix creates a gaussian kernel of given dimension
import math import sys import cv2 import numpy as np def vec_gaussian(img: np.ndarray, variance: float) -> np.ndarray: sigma = math.sqrt(variance) cons = 1 / (sigma * math.sqrt(2 * math.pi)) return cons * np.exp(-((img / sigma) ** 2) * 0.5) def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray: half = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray: arr = np.zeros((kernel_size, kernel_size)) for i in range(kernel_size): for j in range(kernel_size): arr[i, j] = math.sqrt( abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2 ) return vec_gaussian(arr, spatial_variance) def bilateral_filter( img: np.ndarray, spatial_variance: float, intensity_variance: float, kernel_size: int, ) -> np.ndarray: img2 = np.zeros(img.shape) gauss_ker = get_gauss_kernel(kernel_size, spatial_variance) size_x, size_y = img.shape for i in range(kernel_size // 2, size_x - kernel_size // 2): for j in range(kernel_size // 2, size_y - kernel_size // 2): img_s = get_slice(img, i, j, kernel_size) img_i = img_s - img_s[kernel_size // 2, kernel_size // 2] img_ig = vec_gaussian(img_i, intensity_variance) weights = np.multiply(gauss_ker, img_ig) vals = np.multiply(img_s, weights) val = np.sum(vals) / np.sum(weights) img2[i, j] = val return img2 def parse_args(args: list) -> tuple: filename = args[1] if args[1:] else "../image_data/lena.jpg" spatial_variance = float(args[2]) if args[2:] else 1.0 intensity_variance = float(args[3]) if args[3:] else 1.0 if args[4:]: kernel_size = int(args[4]) kernel_size = kernel_size + abs(kernel_size % 2 - 1) else: kernel_size = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": filename, spatial_variance, intensity_variance, kernel_size = parse_args(sys.argv) img = cv2.imread(filename, 0) cv2.imshow("input image", img) out = img / 255 out = out.astype("float32") out = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) out = out * 255 out = np.uint8(out) cv2.imshow("output image", out) cv2.waitKey(0) cv2.destroyAllWindows()