idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
19,800
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : if attrs is None : attrs = self . read_json ( ) if ignore is None : ignore = set ( ) ignore . add ( 'password' ) return super ( Registry , self ) . read ( entity , attrs , ignore , params )
Do not read the password argument .
19,801
def create_missing ( self ) : if getattr ( self , 'content_type' , '' ) == 'docker' : self . _fields [ 'docker_upstream_name' ] . required = True super ( Repository , self ) . create_missing ( )
Conditionally mark docker_upstream_name as required .
19,802
def upload_content ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . post ( self . path ( 'upload_content' ) , ** kwargs ) json = _handle_response ( response , self . _server_config , synchronous ) if json [ 'status' ] != 'success' : raise APIResponseError ( 'Received error when uploading file {0} to repository {1}: {2}' . format ( kwargs . get ( 'files' ) , self . id , json ) ) return json
Upload a file or files to the current repository .
19,803
def import_uploads ( self , uploads = None , upload_ids = None , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) if uploads : data = { 'uploads' : uploads } elif upload_ids : data = { 'upload_ids' : upload_ids } response = client . put ( self . path ( 'import_uploads' ) , data , ** kwargs ) json = _handle_response ( response , self . _server_config , synchronous ) return json
Import uploads into a repository
19,804
def available_repositories ( self , ** kwargs ) : if 'data' not in kwargs : kwargs [ 'data' ] = dict ( ) kwargs [ 'data' ] [ 'product_id' ] = self . product . id kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . get ( self . path ( 'available_repositories' ) , ** kwargs ) return _handle_response ( response , self . _server_config )
Lists available repositories for the repository set
19,805
def enable ( self , synchronous = True , ** kwargs ) : if 'data' not in kwargs : kwargs [ 'data' ] = dict ( ) kwargs [ 'data' ] [ 'product_id' ] = self . product . id kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . put ( self . path ( 'enable' ) , ** kwargs ) return _handle_response ( response , self . _server_config , synchronous )
Enables the RedHat Repository
19,806
def import_puppetclasses ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) if 'environment' in kwargs : if isinstance ( kwargs [ 'environment' ] , Environment ) : environment_id = kwargs . pop ( 'environment' ) . id else : environment_id = kwargs . pop ( 'environment' ) path = '{0}/environments/{1}/import_puppetclasses' . format ( self . path ( ) , environment_id ) else : path = '{0}/import_puppetclasses' . format ( self . path ( ) ) return _handle_response ( client . post ( path , ** kwargs ) , self . _server_config , synchronous )
Import puppet classes from puppet Capsule .
19,807
def _org_path ( self , which , payload ) : return Subscription ( self . _server_config , organization = payload [ 'organization_id' ] , ) . path ( which )
A helper method for generating paths with organization IDs in them .
19,808
def manifest_history ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . get ( self . _org_path ( 'manifest_history' , kwargs [ 'data' ] ) , ** kwargs ) return _handle_response ( response , self . _server_config , synchronous )
Obtain manifest history for subscriptions .
19,809
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : if ignore is None : ignore = set ( ) ignore . add ( 'organization' ) return super ( Subscription , self ) . read ( entity , attrs , ignore , params )
Ignore organization field as it s never returned by the server and is only added to entity to be able to use organization path dependent helpers .
19,810
def refresh_manifest ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . put ( self . _org_path ( 'refresh_manifest' , kwargs [ 'data' ] ) , ** kwargs ) return _handle_response ( response , self . _server_config , synchronous , timeout = 1500 , )
Refresh previously imported manifest for Red Hat provider .
19,811
def upload ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . post ( self . _org_path ( 'upload' , kwargs [ 'data' ] ) , ** kwargs ) return _handle_response ( response , self . _server_config , synchronous , timeout = 1500 , )
Upload a subscription manifest .
19,812
def create_payload ( self ) : data = super ( SyncPlan , self ) . create_payload ( ) if isinstance ( data . get ( 'sync_date' ) , datetime ) : data [ 'sync_date' ] = data [ 'sync_date' ] . strftime ( '%Y-%m-%d %H:%M:%S' ) return data
Convert sync_date to a string .
19,813
def update_payload ( self , fields = None ) : data = super ( SyncPlan , self ) . update_payload ( fields ) if isinstance ( data . get ( 'sync_date' ) , datetime ) : data [ 'sync_date' ] = data [ 'sync_date' ] . strftime ( '%Y-%m-%d %H:%M:%S' ) return data
Convert sync_date to a string if datetime object provided .
19,814
def deploy_script ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . get ( self . path ( 'deploy_script' ) , ** kwargs ) return _handle_response ( response , self . _server_config , synchronous )
Helper for Config s deploy_script method .
19,815
def ensure_local_net ( network_name : str = DOCKER_STARCRAFT_NETWORK , subnet_cidr : str = SUBNET_CIDR ) -> None : logger . info ( f"checking whether docker has network {network_name}" ) ipam_pool = docker . types . IPAMPool ( subnet = subnet_cidr ) ipam_config = docker . types . IPAMConfig ( pool_configs = [ ipam_pool ] ) networks = docker_client . networks . list ( names = DOCKER_STARCRAFT_NETWORK ) output = networks [ 0 ] . short_id if networks else None if not output : logger . info ( "network not found, creating ..." ) output = docker_client . networks . create ( DOCKER_STARCRAFT_NETWORK , ipam = ipam_config ) . short_id logger . debug ( f"docker network id: {output}" )
Create docker local net if not found .
19,816
def ensure_local_image ( local_image : str , parent_image : str = SC_PARENT_IMAGE , java_image : str = SC_JAVA_IMAGE , starcraft_base_dir : str = SCBW_BASE_DIR , starcraft_binary_link : str = SC_BINARY_LINK , ) -> None : logger . info ( f"checking if there is local image {local_image}" ) docker_images = docker_client . images . list ( local_image ) if len ( docker_images ) and docker_images [ 0 ] . short_id is not None : logger . info ( f"image {local_image} found locally." ) return logger . info ( "image not found locally, creating..." ) pkg_docker_dir = os . path . join ( os . path . abspath ( os . path . dirname ( __file__ ) ) , "local_docker" ) base_dir = os . path . join ( starcraft_base_dir , "docker" ) logger . info ( f"copying files from {pkg_docker_dir} to {base_dir}." ) distutils . dir_util . copy_tree ( pkg_docker_dir , base_dir ) starcraft_zip_file = f"{base_dir}/starcraft.zip" if not os . path . exists ( starcraft_zip_file ) : logger . info ( f"downloading starcraft.zip to {starcraft_zip_file}" ) download_file ( starcraft_binary_link , starcraft_zip_file ) logger . info ( f"pulling image {parent_image}, this may take a while..." ) pulled_image = docker_client . images . pull ( parent_image ) pulled_image . tag ( java_image ) logger . info ( f"building local image {local_image}, this may take a while..." ) docker_client . images . build ( path = base_dir , dockerfile = "game.dockerfile" , tag = local_image ) logger . info ( f"successfully built image {local_image}" )
Check if local_image is present locally . If it is not pull parent images and build . This includes pulling starcraft binary .
19,817
def check_dockermachine ( ) -> bool : logger . debug ( "checking docker-machine presence" ) try : out = subprocess . check_output ( [ "docker-machine" , "version" ] ) . decode ( "utf-8" ) . replace ( "docker-machine.exe" , "" ) . replace ( "docker-machine" , "" ) . strip ( ) logger . debug ( f"using docker machine version {out}" ) return True except Exception : logger . debug ( f"docker machine not present" ) return False
Checks that docker - machine is available on the computer
19,818
def dockermachine_ip ( ) -> Optional [ str ] : if not check_dockermachine ( ) : return None try : out = subprocess . check_output ( [ 'docker-machine' , 'ip' ] ) return out . decode ( "utf-8" ) . strip ( ) except Exception : logger . debug ( f"docker machine not present" ) return None
Gets IP address of the default docker machine Returns None if no docker - machine executable in the PATH and if there no Docker machine with name default present
19,819
def xoscmounts ( host_mount ) : callback_lower_drive_letter = lambda pat : pat . group ( 1 ) . lower ( ) host_mount = re . sub ( r"^([a-zA-Z])\:" , callback_lower_drive_letter , host_mount ) host_mount = re . sub ( r"^([a-z])" , "//\\1" , host_mount ) host_mount = re . sub ( r"\\" , "/" , host_mount ) return host_mount
Cross OS compatible mount dirs
19,820
def chisquare ( n_ij , weighted ) : if weighted : m_ij = n_ij / n_ij nan_mask = np . isnan ( m_ij ) m_ij [ nan_mask ] = 0.000001 w_ij = m_ij n_ij_col_sum = n_ij . sum ( axis = 1 ) n_ij_row_sum = n_ij . sum ( axis = 0 ) alpha , beta , eps = ( 1 , 1 , 1 ) while eps > 10e-6 : alpha = alpha * np . vstack ( n_ij_col_sum / m_ij . sum ( axis = 1 ) ) beta = n_ij_row_sum / ( alpha * w_ij ) . sum ( axis = 0 ) eps = np . max ( np . absolute ( w_ij * alpha * beta - m_ij ) ) m_ij = w_ij * alpha * beta else : m_ij = ( np . vstack ( n_ij . sum ( axis = 1 ) ) * n_ij . sum ( axis = 0 ) ) / n_ij . sum ( ) . astype ( float ) dof = ( n_ij . shape [ 0 ] - 1 ) * ( n_ij . shape [ 1 ] - 1 ) chi , p_val = stats . chisquare ( n_ij , f_exp = m_ij , ddof = n_ij . size - 1 - dof , axis = None ) return ( chi , p_val , dof )
Calculates the chisquare for a matrix of ind_v x dep_v for the unweighted and SPSS weighted case
19,821
def best_split ( self , ind , dep ) : if isinstance ( dep , ContinuousColumn ) : return self . best_con_split ( ind , dep ) else : return self . best_cat_heuristic_split ( ind , dep )
determine which splitting function to apply
19,822
def from_numpy ( ndarr , arr , alpha_merge = 0.05 , max_depth = 2 , min_parent_node_size = 30 , min_child_node_size = 30 , split_titles = None , split_threshold = 0 , weights = None , variable_types = None , dep_variable_type = 'categorical' ) : vectorised_array = [ ] variable_types = variable_types or [ 'nominal' ] * ndarr . shape [ 1 ] for ind , col_type in enumerate ( variable_types ) : title = None if split_titles is not None : title = split_titles [ ind ] if col_type == 'ordinal' : col = OrdinalColumn ( ndarr [ : , ind ] , name = title ) elif col_type == 'nominal' : col = NominalColumn ( ndarr [ : , ind ] , name = title ) else : raise NotImplementedError ( 'Unknown independent variable type ' + col_type ) vectorised_array . append ( col ) if dep_variable_type == 'categorical' : observed = NominalColumn ( arr , weights = weights ) elif dep_variable_type == 'continuous' : observed = ContinuousColumn ( arr , weights = weights ) else : raise NotImplementedError ( 'Unknown dependent variable type ' + dep_variable_type ) config = { 'alpha_merge' : alpha_merge , 'max_depth' : max_depth , 'min_parent_node_size' : min_parent_node_size , 'min_child_node_size' : min_child_node_size , 'split_threshold' : split_threshold } return Tree ( vectorised_array , observed , config )
Create a CHAID object from numpy
19,823
def build_tree ( self ) : self . _tree_store = [ ] self . node ( np . arange ( 0 , self . data_size , dtype = np . int ) , self . vectorised_array , self . observed )
Build chaid tree
19,824
def from_pandas_df ( df , i_variables , d_variable , alpha_merge = 0.05 , max_depth = 2 , min_parent_node_size = 30 , min_child_node_size = 30 , split_threshold = 0 , weight = None , dep_variable_type = 'categorical' ) : ind_df = df [ list ( i_variables . keys ( ) ) ] ind_values = ind_df . values dep_values = df [ d_variable ] . values weights = df [ weight ] if weight is not None else None return Tree . from_numpy ( ind_values , dep_values , alpha_merge , max_depth , min_parent_node_size , min_child_node_size , list ( ind_df . columns . values ) , split_threshold , weights , list ( i_variables . values ( ) ) , dep_variable_type )
Helper method to pre - process a pandas data frame in order to run CHAID analysis
19,825
def node ( self , rows , ind , dep , depth = 0 , parent = None , parent_decisions = None ) : depth += 1 if self . max_depth < depth : terminal_node = Node ( choices = parent_decisions , node_id = self . node_count , parent = parent , indices = rows , dep_v = dep ) self . _tree_store . append ( terminal_node ) self . node_count += 1 terminal_node . split . invalid_reason = InvalidSplitReason . MAX_DEPTH return self . _tree_store split = self . _stats . best_split ( ind , dep ) node = Node ( choices = parent_decisions , node_id = self . node_count , indices = rows , dep_v = dep , parent = parent , split = split ) self . _tree_store . append ( node ) parent = self . node_count self . node_count += 1 if not split . valid ( ) : return self . _tree_store for index , choices in enumerate ( split . splits ) : correct_rows = np . in1d ( ind [ split . column_id ] . arr , choices ) dep_slice = dep [ correct_rows ] ind_slice = [ vect [ correct_rows ] for vect in ind ] row_slice = rows [ correct_rows ] if self . min_parent_node_size < len ( dep_slice . arr ) : self . node ( row_slice , ind_slice , dep_slice , depth = depth , parent = parent , parent_decisions = split . split_map [ index ] ) else : terminal_node = Node ( choices = split . split_map [ index ] , node_id = self . node_count , parent = parent , indices = row_slice , dep_v = dep_slice ) terminal_node . split . invalid_reason = InvalidSplitReason . MIN_PARENT_NODE_SIZE self . _tree_store . append ( terminal_node ) self . node_count += 1 return self . _tree_store
internal method to create a node in the tree
19,826
def to_tree ( self ) : tree = TreeLibTree ( ) for node in self : tree . create_node ( node , node . node_id , parent = node . parent ) return tree
returns a TreeLib tree
19,827
def node_predictions ( self ) : pred = np . zeros ( self . data_size ) for node in self : if node . is_terminal : pred [ node . indices ] = node . node_id return pred
Determines which rows fall into which node
19,828
def model_predictions ( self ) : if isinstance ( self . observed , ContinuousColumn ) : return ValueError ( "Cannot make model predictions on a continuous scale" ) pred = np . zeros ( self . data_size ) . astype ( 'object' ) for node in self : if node . is_terminal : pred [ node . indices ] = max ( node . members , key = node . members . get ) return pred
Determines the highest frequency of categorical dependent variable in the terminal node where that row fell
19,829
def bell_set ( self , collection , ordinal = False ) : if len ( collection ) == 1 : yield [ collection ] return first = collection [ 0 ] for smaller in self . bell_set ( collection [ 1 : ] ) : for n , subset in enumerate ( smaller ) : if not ordinal or ( ordinal and is_sorted ( smaller [ : n ] + [ [ first ] + subset ] + smaller [ n + 1 : ] , self . _nan ) ) : yield smaller [ : n ] + [ [ first ] + subset ] + smaller [ n + 1 : ] if not ordinal or ( ordinal and is_sorted ( [ [ first ] ] + smaller , self . _nan ) ) : yield [ [ first ] ] + smaller
Calculates the Bell set
19,830
def substitute_values ( self , vect ) : try : unique = np . unique ( vect ) except : unique = set ( vect ) unique = [ x for x in unique if not isinstance ( x , float ) or not isnan ( x ) ] arr = np . copy ( vect ) for new_id , value in enumerate ( unique ) : np . place ( arr , arr == value , new_id ) self . metadata [ new_id ] = value arr = arr . astype ( np . float ) np . place ( arr , np . isnan ( arr ) , - 1 ) self . arr = arr if - 1 in arr : self . metadata [ - 1 ] = self . _missing_id
Internal method to substitute integers into the vector and construct metadata to convert back to the original vector .
19,831
def sub_split_values ( self , sub ) : for i , arr in enumerate ( self . splits ) : self . split_map [ i ] = [ sub . get ( x , x ) for x in arr ] for split in self . surrogates : split . sub_split_values ( sub )
Substitutes the splits with other values into the split_map
19,832
def name_columns ( self , sub ) : if self . column_id is not None and len ( sub ) > self . column_id : self . split_name = sub [ self . column_id ] for split in self . surrogates : split . name_columns ( sub )
Substitutes the split column index with a human readable string
19,833
def three_partition ( x ) : f = [ 0 ] * ( 1 << len ( x ) ) for i in range ( len ( x ) ) : for S in range ( 1 << i ) : f [ S | ( 1 << i ) ] = f [ S ] + x [ i ] for A in range ( 1 << len ( x ) ) : for B in range ( 1 << len ( x ) ) : if A & B == 0 and f [ A ] == f [ B ] and 3 * f [ A ] == f [ - 1 ] : return ( A , B , ( ( 1 << len ( x ) ) - 1 ) ^ A ^ B ) return None
partition a set of integers in 3 parts of same total value
19,834
def freivalds ( A , B , C ) : n = len ( A ) x = [ randint ( 0 , 1000000 ) for j in range ( n ) ] return mult ( A , mult ( B , x ) ) == mult ( C , x )
Tests matrix product AB = C by Freivalds
19,835
def min_scalar_prod ( x , y ) : x = sorted ( x ) y = sorted ( y ) return sum ( x [ i ] * y [ - i - 1 ] for i in range ( len ( x ) ) )
Permute vector to minimize scalar product
19,836
def laser_mirrors ( rows , cols , mir ) : n = len ( mir ) orien = [ None ] * ( n + 2 ) orien [ n ] = 0 orien [ n + 1 ] = 0 succ = [ [ None for direc in range ( 4 ) ] for i in range ( n + 2 ) ] L = [ ( mir [ i ] [ 0 ] , mir [ i ] [ 1 ] , i ) for i in range ( n ) ] L . append ( ( 0 , - 1 , n ) ) L . append ( ( 0 , cols , n + 1 ) ) last_r , last_i = None , None for ( r , c , i ) in sorted ( L ) : if last_r == r : succ [ i ] [ LEFT ] = last_i succ [ last_i ] [ RIGHT ] = i last_r , last_i = r , i last_c = None for ( r , c , i ) in sorted ( L , key = lambda rci : ( rci [ 1 ] , rci [ 0 ] ) ) : if last_c == c : succ [ i ] [ UP ] = last_i succ [ last_i ] [ DOWN ] = i last_c , last_i = c , i if solve ( succ , orien , n , RIGHT ) : return orien [ : n ] else : return None
Orienting mirrors to allow reachability by laser beam
19,837
def solve ( succ , orien , i , direc ) : assert orien [ i ] is not None j = succ [ i ] [ direc ] if j is None : return False if j == len ( orien ) - 1 : return True if orien [ j ] is None : for x in [ 0 , 1 ] : orien [ j ] = x if solve ( succ , orien , j , reflex [ direc ] [ x ] ) : return True orien [ j ] = None return False else : return solve ( succ , orien , j , reflex [ direc ] [ orien [ j ] ] )
Can a laser leaving mirror i in direction direc reach exit ?
19,838
def dancing_links ( size_universe , sets ) : header = Cell ( None , None , 0 , None ) col = [ ] for j in range ( size_universe ) : col . append ( Cell ( header , None , 0 , None ) ) for i in range ( len ( sets ) ) : row = None for j in sets [ i ] : col [ j ] . S += 1 row = Cell ( row , col [ j ] , i , col [ j ] ) sol = [ ] if solve ( header , sol ) : return sol else : return None
Exact set cover by the dancing links algorithm
19,839
def two_sat ( formula ) : n = max ( abs ( clause [ p ] ) for p in ( 0 , 1 ) for clause in formula ) graph = [ [ ] for node in range ( 2 * n ) ] for x , y in formula : graph [ _vertex ( - x ) ] . append ( _vertex ( y ) ) graph [ _vertex ( - y ) ] . append ( _vertex ( x ) ) sccp = tarjan ( graph ) comp_id = [ None ] * ( 2 * n ) assignment = [ None ] * ( 2 * n ) for component in sccp : rep = min ( component ) for vtx in component : comp_id [ vtx ] = rep if assignment [ vtx ] is None : assignment [ vtx ] = True assignment [ vtx ^ 1 ] = False for i in range ( n ) : if comp_id [ 2 * i ] == comp_id [ 2 * i + 1 ] : return None return assignment [ : : 2 ]
Solving a 2 - SAT boolean formula
19,840
def rectangles_from_grid ( P , black = 1 ) : rows = len ( P ) cols = len ( P [ 0 ] ) t = [ 0 ] * cols best = None for i in range ( rows ) : for j in range ( cols ) : if P [ i ] [ j ] == black : t [ j ] += 1 else : t [ j ] = 0 ( area , left , height , right ) = rectangles_from_histogram ( t ) alt = ( area , left , i , right , i - height ) if best is None or alt > best : best = alt return best
Largest area rectangle in a binary matrix
19,841
def min_mean_cycle ( graph , weight , start = 0 ) : INF = float ( 'inf' ) n = len ( graph ) dist = [ [ INF ] * n ] prec = [ [ None ] * n ] dist [ 0 ] [ start ] = 0 for ell in range ( 1 , n + 1 ) : dist . append ( [ INF ] * n ) prec . append ( [ None ] * n ) for node in range ( n ) : for neighbor in graph [ node ] : alt = dist [ ell - 1 ] [ node ] + weight [ node ] [ neighbor ] if alt < dist [ ell ] [ neighbor ] : dist [ ell ] [ neighbor ] = alt prec [ ell ] [ neighbor ] = node valmin = INF argmin = None for node in range ( n ) : valmax = - INF argmax = None for k in range ( n ) : alt = ( dist [ n ] [ node ] - dist [ k ] [ node ] ) / float ( n - k ) if alt >= valmax : valmax = alt argmax = k if argmax is not None and valmax < valmin : valmin = valmax argmin = ( node , argmax ) if valmin == INF : return None C = [ ] node , k = argmin for l in range ( n , k , - 1 ) : C . append ( node ) node = prec [ l ] [ node ] return C [ : : - 1 ] , valmin
Minimum mean cycle by Karp
19,842
def floyd_warshall ( weight ) : V = range ( len ( weight ) ) for k in V : for u in V : for v in V : weight [ u ] [ v ] = min ( weight [ u ] [ v ] , weight [ u ] [ k ] + weight [ k ] [ v ] ) for v in V : if weight [ v ] [ v ] < 0 : return True return False
All pairs shortest paths by Floyd - Warshall
19,843
def bellman_ford ( graph , weight , source = 0 ) : n = len ( graph ) dist = [ float ( 'inf' ) ] * n prec = [ None ] * n dist [ source ] = 0 for nb_iterations in range ( n ) : changed = False for node in range ( n ) : for neighbor in graph [ node ] : alt = dist [ node ] + weight [ node ] [ neighbor ] if alt < dist [ neighbor ] : dist [ neighbor ] = alt prec [ neighbor ] = node changed = True if not changed : return dist , prec , False return dist , prec , True
Single source shortest paths by Bellman - Ford
19,844
def roman2int ( s ) : val = 0 pos10 = 1000 beg = 0 for pos in range ( 3 , - 1 , - 1 ) : for digit in range ( 9 , - 1 , - 1 ) : r = roman [ pos ] [ digit ] if s . startswith ( r , beg ) : beg += len ( r ) val += digit * pos10 break pos10 //= 10 return val
Decode roman number
19,845
def int2roman ( val ) : s = '' pos10 = 1000 for pos in range ( 3 , - 1 , - 1 ) : digit = val // pos10 s += roman [ pos ] [ digit ] val %= pos10 pos10 //= 10 return s
Code roman number
19,846
def dijkstra ( graph , weight , source = 0 , target = None ) : n = len ( graph ) assert all ( weight [ u ] [ v ] >= 0 for u in range ( n ) for v in graph [ u ] ) prec = [ None ] * n black = [ False ] * n dist = [ float ( 'inf' ) ] * n dist [ source ] = 0 heap = [ ( 0 , source ) ] while heap : dist_node , node = heappop ( heap ) if not black [ node ] : black [ node ] = True if node == target : break for neighbor in graph [ node ] : dist_neighbor = dist_node + weight [ node ] [ neighbor ] if dist_neighbor < dist [ neighbor ] : dist [ neighbor ] = dist_neighbor prec [ neighbor ] = node heappush ( heap , ( dist_neighbor , neighbor ) ) return dist , prec
single source shortest paths by Dijkstra
19,847
def dijkstra_update_heap ( graph , weight , source = 0 , target = None ) : n = len ( graph ) assert all ( weight [ u ] [ v ] >= 0 for u in range ( n ) for v in graph [ u ] ) prec = [ None ] * n dist = [ float ( 'inf' ) ] * n dist [ source ] = 0 heap = OurHeap ( [ ( dist [ node ] , node ) for node in range ( n ) ] ) while heap : dist_node , node = heap . pop ( ) if node == target : break for neighbor in graph [ node ] : old = dist [ neighbor ] new = dist_node + weight [ node ] [ neighbor ] if new < old : dist [ neighbor ] = new prec [ neighbor ] = node heap . update ( ( old , neighbor ) , ( new , neighbor ) ) return dist , prec
single source shortest paths by Dijkstra with a heap implementing item updates
19,848
def manacher ( s ) : assert set . isdisjoint ( { '$' , '^' , '#' } , s ) if s == "" : return ( 0 , 1 ) t = "^#" + "#" . join ( s ) + "#$" c = 1 d = 1 p = [ 0 ] * len ( t ) for i in range ( 2 , len ( t ) - 1 ) : mirror = 2 * c - i p [ i ] = max ( 0 , min ( d - i , p [ mirror ] ) ) while t [ i + 1 + p [ i ] ] == t [ i - 1 - p [ i ] ] : p [ i ] += 1 if i + p [ i ] > d : c = i d = i + p [ i ] ( k , i ) = max ( ( p [ i ] , i ) for i in range ( 1 , len ( t ) - 1 ) ) return ( ( i - k ) // 2 , ( i + k ) // 2 )
Longest palindrome in a string by Manacher
19,849
def bfs ( graph , start = 0 ) : to_visit = deque ( ) dist = [ float ( 'inf' ) ] * len ( graph ) prec = [ None ] * len ( graph ) dist [ start ] = 0 to_visit . appendleft ( start ) while to_visit : node = to_visit . pop ( ) for neighbor in graph [ node ] : if dist [ neighbor ] == float ( 'inf' ) : dist [ neighbor ] = dist [ node ] + 1 prec [ neighbor ] = node to_visit . appendleft ( neighbor ) return dist , prec
Shortest path in unweighted graph by BFS
19,850
def read_graph ( filename , directed = False , weighted = False , default_weight = None ) : with open ( filename , 'r' ) as f : while True : line = f . readline ( ) if line [ 0 ] != '#' : break nb_nodes , nb_edges = tuple ( map ( int , line . split ( ) ) ) graph = [ [ ] for u in range ( nb_nodes ) ] if weighted : weight = [ [ default_weight ] * nb_nodes for v in range ( nb_nodes ) ] for v in range ( nb_nodes ) : weight [ v ] [ v ] = 0 for _ in range ( nb_edges ) : u , v , w = readtab ( f , int ) graph [ u ] . append ( v ) weight [ u ] [ v ] = w if not directed : graph [ v ] . append ( u ) weight [ v ] [ u ] = w return graph , weight else : for _ in range ( nb_edges ) : u , v = readtab ( f , int ) [ : 2 ] graph [ u ] . append ( v ) if not directed : graph [ v ] . append ( u ) return graph
Read a graph from a text file
19,851
def write_graph ( dotfile , graph , directed = False , node_label = None , arc_label = None , comment = "" , node_mark = set ( ) , arc_mark = set ( ) ) : with open ( dotfile , 'w' ) as f : if directed : f . write ( "digraph G{\n" ) else : f . write ( "graph G{\n" ) if comment : f . write ( 'label="%s";\n' % comment ) V = range ( len ( graph ) ) for u in V : if node_mark and u in node_mark : f . write ( '%d [style=filled, color="lightgrey", ' % u ) else : f . write ( '%d [' % u ) if node_label : f . write ( 'label="%u [%s]"];\n' % ( u , node_label [ u ] ) ) else : f . write ( 'shape=circle, label="%u"];\n' % u ) if isinstance ( arc_mark , list ) : arc_mark = set ( ( u , arc_mark [ u ] ) for u in V ) for u in V : for v in graph [ u ] : if not directed and u > v : continue if arc_label and arc_label [ u ] [ v ] == None : continue if directed : arc = "%d -> %d " % ( u , v ) else : arc = "%d -- %d " % ( u , v ) if arc_mark and ( ( v , u ) in arc_mark or ( not directed and ( u , v ) in arc_mark ) ) : pen = 'color="red"' else : pen = "" if arc_label : tag = 'label="%s"' % arc_label [ u ] [ v ] else : tag = "" if tag and pen : sep = ", " else : sep = "" f . write ( arc + "[" + tag + sep + pen + "];\n" ) f . write ( "}" )
Writes a graph to a file in the DOT format
19,852
def tree_prec_to_adj ( prec , root = 0 ) : n = len ( prec ) graph = [ [ prec [ u ] ] for u in range ( n ) ] graph [ root ] = [ ] for u in range ( n ) : if u != root : graph [ prec [ u ] ] . append ( u ) return graph
Transforms a tree given as predecessor table into adjacency list form
19,853
def matrix_to_listlist ( weight ) : graph = [ [ ] for _ in range ( len ( weight ) ) ] for u in range ( len ( graph ) ) : for v in range ( len ( graph ) ) : if weight [ u ] [ v ] != None : graph [ u ] . append ( v ) return graph
transforms a squared weight matrix in a adjacency table of type listlist encoding the directed graph corresponding to the entries of the matrix different from None
19,854
def listlist_and_matrix_to_listdict ( graph , weight = None ) : if weight : return [ { v : weight [ u ] [ v ] for v in graph [ u ] } for u in range ( len ( graph ) ) ] else : return [ { v : None for v in graph [ u ] } for u in range ( len ( graph ) ) ]
Transforms the weighted adjacency list representation of a graph of type listlist + optional weight matrix into the listdict representation
19,855
def listdict_to_listlist_and_matrix ( sparse ) : V = range ( len ( sparse ) ) graph = [ [ ] for _ in V ] weight = [ [ None for v in V ] for u in V ] for u in V : for v in sparse [ u ] : graph [ u ] . append ( v ) weight [ u ] [ v ] = sparse [ u ] [ v ] return graph , weight
Transforms the adjacency list representation of a graph of type listdict into the listlist + weight matrix representation
19,856
def extract_path ( prec , v ) : L = [ ] while v is not None : L . append ( v ) v = prec [ v ] assert v not in L return L [ : : - 1 ]
extracts a path in form of vertex list from source to vertex v given a precedence table prec leading to the source
19,857
def make_flow_labels ( graph , flow , capac ) : V = range ( len ( graph ) ) arc_label = [ { v : "" for v in graph [ u ] } for u in V ] for u in V : for v in graph [ u ] : if flow [ u ] [ v ] >= 0 : arc_label [ u ] [ v ] = "%s/%s" % ( flow [ u ] [ v ] , capac [ u ] [ v ] ) else : arc_label [ u ] [ v ] = None return arc_label
Generate arc labels for a flow in a graph with capacities .
19,858
def dilworth ( graph ) : n = len ( graph ) match = max_bipartite_matching ( graph ) part = [ None ] * n nb_chains = 0 for v in range ( n - 1 , - 1 , - 1 ) : if part [ v ] is None : u = v while u is not None : part [ u ] = nb_chains u = match [ u ] nb_chains += 1 return part
Decompose a DAG into a minimum number of chains by Dilworth
19,859
def extract ( code , tree , prefix = [ ] ) : if isinstance ( tree , list ) : l , r = tree prefix . append ( '0' ) extract ( code , l , prefix ) prefix . pop ( ) prefix . append ( '1' ) extract ( code , r , prefix ) prefix . pop ( ) else : code [ tree ] = '' . join ( prefix )
Extract Huffman code from a Huffman tree
19,860
def next_permutation ( tab ) : n = len ( tab ) pivot = None for i in range ( n - 1 ) : if tab [ i ] < tab [ i + 1 ] : pivot = i if pivot is None : return False for i in range ( pivot + 1 , n ) : if tab [ i ] > tab [ pivot ] : swap = i tab [ swap ] , tab [ pivot ] = tab [ pivot ] , tab [ swap ] i = pivot + 1 j = n - 1 while i < j : tab [ i ] , tab [ j ] = tab [ j ] , tab [ i ] i += 1 j -= 1 return True
find the next permutation of tab in the lexicographical order
19,861
def intervals_union ( S ) : E = [ ( low , - 1 ) for ( low , high ) in S ] E += [ ( high , + 1 ) for ( low , high ) in S ] nb_open = 0 last = None retval = [ ] for x , _dir in sorted ( E ) : if _dir == - 1 : if nb_open == 0 : last = x nb_open += 1 else : nb_open -= 1 if nb_open == 0 : retval . append ( ( last , x ) ) return retval
Union of intervals
19,862
def _augment ( graph , capacity , flow , val , u , target , visit ) : visit [ u ] = True if u == target : return val for v in graph [ u ] : cuv = capacity [ u ] [ v ] if not visit [ v ] and cuv > flow [ u ] [ v ] : res = min ( val , cuv - flow [ u ] [ v ] ) delta = _augment ( graph , capacity , flow , res , v , target , visit ) if delta > 0 : flow [ u ] [ v ] += delta flow [ v ] [ u ] -= delta return delta return 0
Find an augmenting path from u to target with value at most val
19,863
def ford_fulkerson ( graph , capacity , s , t ) : add_reverse_arcs ( graph , capacity ) n = len ( graph ) flow = [ [ 0 ] * n for _ in range ( n ) ] INF = float ( 'inf' ) while _augment ( graph , capacity , flow , INF , s , t , [ False ] * n ) > 0 : pass return ( flow , sum ( flow [ s ] ) )
Maximum flow by Ford - Fulkerson
19,864
def windows_k_distinct ( x , k ) : dist , i , j = 0 , 0 , 0 occ = { xi : 0 for xi in x } while j < len ( x ) : while dist == k : occ [ x [ i ] ] -= 1 if occ [ x [ i ] ] == 0 : dist -= 1 i += 1 while j < len ( x ) and ( dist < k or occ [ x [ j ] ] ) : if occ [ x [ j ] ] == 0 : dist += 1 occ [ x [ j ] ] += 1 j += 1 if dist == k : yield ( i , j )
Find all largest windows containing exactly k distinct elements
19,865
def bezout ( a , b ) : if b == 0 : return ( 1 , 0 ) else : u , v = bezout ( b , a % b ) return ( v , u - ( a // b ) * v )
Bezout coefficients for a and b
19,866
def predictive_text ( dic ) : freq = { } for word , weight in dic : prefix = "" for x in word : prefix += x if prefix in freq : freq [ prefix ] += weight else : freq [ prefix ] = weight prop = { } for prefix in freq : code = code_word ( prefix ) if code not in prop or freq [ prop [ code ] ] < freq [ prefix ] : prop [ code ] = prefix return prop
Predictive text for mobile phones
19,867
def rectangles_from_points ( S ) : answ = 0 pairs = { } for j in range ( len ( S ) ) : for i in range ( j ) : px , py = S [ i ] qx , qy = S [ j ] center = ( px + qx , py + qy ) dist = ( px - qx ) ** 2 + ( py - qy ) ** 2 sign = ( center , dist ) if sign in pairs : answ += len ( pairs [ sign ] ) pairs [ sign ] . append ( ( i , j ) ) else : pairs [ sign ] = [ ( i , j ) ] return answ
How many rectangles can be formed from a set of points
19,868
def cut_nodes_edges ( graph ) : n = len ( graph ) time = 0 num = [ None ] * n low = [ n ] * n father = [ None ] * n critical_childs = [ 0 ] * n times_seen = [ - 1 ] * n for start in range ( n ) : if times_seen [ start ] == - 1 : times_seen [ start ] = 0 to_visit = [ start ] while to_visit : node = to_visit [ - 1 ] if times_seen [ node ] == 0 : num [ node ] = time time += 1 low [ node ] = float ( 'inf' ) children = graph [ node ] if times_seen [ node ] == len ( children ) : to_visit . pop ( ) up = father [ node ] if up is not None : low [ up ] = min ( low [ up ] , low [ node ] ) if low [ node ] >= num [ up ] : critical_childs [ up ] += 1 else : child = children [ times_seen [ node ] ] times_seen [ node ] += 1 if times_seen [ child ] == - 1 : father [ child ] = node times_seen [ child ] = 0 to_visit . append ( child ) elif num [ child ] < num [ node ] and father [ node ] != child : low [ node ] = min ( low [ node ] , num [ child ] ) cut_edges = [ ] cut_nodes = [ ] for node in range ( n ) : if father [ node ] is None : if critical_childs [ node ] >= 2 : cut_nodes . append ( node ) else : if critical_childs [ node ] >= 1 : cut_nodes . append ( node ) if low [ node ] >= num [ node ] : cut_edges . append ( ( father [ node ] , node ) ) return cut_nodes , cut_edges
Bi - connected components
19,869
def cut_nodes_edges2 ( graph ) : N = len ( graph ) assert N <= 5000 recursionlimit = getrecursionlimit ( ) setrecursionlimit ( max ( recursionlimit , N + 42 ) ) edges = set ( ( i , j ) for i in range ( N ) for j in graph [ i ] if i <= j ) nodes = set ( ) NOT = - 2 FIN = - 3 marked = [ NOT ] * N def DFS ( n , prof = 0 ) : if marked [ n ] == FIN : return if marked [ n ] != NOT : return marked [ n ] marked [ n ] = prof m = float ( 'inf' ) count = 0 for v in graph [ n ] : if marked [ v ] != FIN and marked [ v ] != prof - 1 : count += 1 r = DFS ( v , prof + 1 ) if r <= prof : edges . discard ( tuple ( sorted ( ( n , v ) ) ) ) if prof and r >= prof : nodes . add ( n ) m = min ( m , r ) if prof == 0 and count >= 2 : nodes . add ( n ) marked [ n ] = FIN return m for r in range ( N ) : DFS ( r ) setrecursionlimit ( recursionlimit ) return nodes , edges
Bi - connected components alternative recursive implementation
19,870
def area ( p ) : A = 0 for i in range ( len ( p ) ) : A += p [ i - 1 ] [ 0 ] * p [ i ] [ 1 ] - p [ i ] [ 0 ] * p [ i - 1 ] [ 1 ] return A / 2.
Area of a polygone
19,871
def is_simple ( polygon ) : n = len ( polygon ) order = list ( range ( n ) ) order . sort ( key = lambda i : polygon [ i ] ) rank_to_y = list ( set ( p [ 1 ] for p in polygon ) ) rank_to_y . sort ( ) y_to_rank = { y : rank for rank , y in enumerate ( rank_to_y ) } S = RangeMinQuery ( [ 0 ] * len ( rank_to_y ) ) last_y = None for i in order : x , y = polygon [ i ] rank = y_to_rank [ y ] right_x = max ( polygon [ i - 1 ] [ 0 ] , polygon [ ( i + 1 ) % n ] [ 0 ] ) left = x < right_x below_y = min ( polygon [ i - 1 ] [ 1 ] , polygon [ ( i + 1 ) % n ] [ 1 ] ) high = y > below_y if left : if S [ rank ] : return False S [ rank ] = - 1 else : S [ rank ] = 0 if high : lo = y_to_rank [ below_y ] if ( below_y != last_y or last_y == y or rank - lo >= 2 and S . range_min ( lo + 1 , rank ) ) : return False last_y = y return True
Test if a rectilinear polygon is is_simple
19,872
def closest_points ( S ) : shuffle ( S ) assert len ( S ) >= 2 p = S [ 0 ] q = S [ 1 ] d = dist ( p , q ) while d > 0 : r = improve ( S , d ) if r : d , p , q = r else : break return p , q
Closest pair of points
19,873
def longest_increasing_subsequence ( x ) : n = len ( x ) p = [ None ] * n h = [ None ] b = [ float ( '-inf' ) ] for i in range ( n ) : if x [ i ] > b [ - 1 ] : p [ i ] = h [ - 1 ] h . append ( i ) b . append ( x [ i ] ) else : k = bisect_left ( b , x [ i ] ) h [ k ] = i b [ k ] = x [ i ] p [ i ] = h [ k - 1 ] q = h [ - 1 ] s = [ ] while q is not None : s . append ( x [ q ] ) q = p [ q ] return s [ : : - 1 ]
Longest increasing subsequence
19,874
def dfs_recursive ( graph , node , seen ) : seen [ node ] = True for neighbor in graph [ node ] : if not seen [ neighbor ] : dfs_recursive ( graph , neighbor , seen )
DFS detect connected component recursive implementation
19,875
def dfs_iterative ( graph , start , seen ) : seen [ start ] = True to_visit = [ start ] while to_visit : node = to_visit . pop ( ) for neighbor in graph [ node ] : if not seen [ neighbor ] : seen [ neighbor ] = True to_visit . append ( neighbor )
DFS detect connected component iterative implementation
19,876
def dfs_tree ( graph , start = 0 ) : to_visit = [ start ] prec = [ None ] * len ( graph ) while to_visit : node = to_visit . pop ( ) for neighbor in graph [ node ] : if prec [ neighbor ] is None : prec [ neighbor ] = node to_visit . append ( neighbor ) return prec
DFS build DFS tree in unweighted graph
19,877
def find_cycle ( graph ) : n = len ( graph ) prec = [ None ] * n for u in range ( n ) : if prec [ u ] is None : S = [ u ] prec [ u ] = u while S : u = S . pop ( ) for v in graph [ u ] : if v != prec [ u ] : if prec [ v ] is not None : cycle = [ v , u ] while u != prec [ v ] and u != prec [ u ] : u = prec [ u ] cycle . append ( u ) return cycle else : prec [ v ] = u S . append ( v ) return None
find a cycle in an undirected graph
19,878
def arithm_expr_eval ( cell , expr ) : if isinstance ( expr , tuple ) : ( left , op , right ) = expr lval = arithm_expr_eval ( cell , left ) rval = arithm_expr_eval ( cell , right ) if op == '+' : return lval + rval if op == '-' : return lval - rval if op == '*' : return lval * rval if op == '/' : return lval // rval elif isinstance ( expr , int ) : return expr else : cell [ expr ] = arithm_expr_eval ( cell , cell [ expr ] ) return cell [ expr ]
Evaluates a given expression
19,879
def arithm_expr_parse ( line ) : vals = [ ] ops = [ ] for tok in line + [ ';' ] : if tok in priority : while ( tok != '(' and ops and priority [ ops [ - 1 ] ] >= priority [ tok ] ) : right = vals . pop ( ) left = vals . pop ( ) vals . append ( ( left , ops . pop ( ) , right ) ) if tok == ')' : ops . pop ( ) else : ops . append ( tok ) elif tok . isdigit ( ) : vals . append ( int ( tok ) ) else : vals . append ( tok ) return vals . pop ( )
Constructs an arithmetic expression tree
19,880
def _alternate ( u , bigraph , visitU , visitV , matchV ) : visitU [ u ] = True for v in bigraph [ u ] : if not visitV [ v ] : visitV [ v ] = True assert matchV [ v ] is not None _alternate ( matchV [ v ] , bigraph , visitU , visitV , matchV )
extend alternating tree from free vertex u . visitU visitV marks all vertices covered by the tree .
19,881
def bipartite_vertex_cover ( bigraph ) : V = range ( len ( bigraph ) ) matchV = max_bipartite_matching ( bigraph ) matchU = [ None for u in V ] for v in V : if matchV [ v ] is not None : matchU [ matchV [ v ] ] = v visitU = [ False for u in V ] visitV = [ False for v in V ] for u in V : if matchU [ u ] is None : _alternate ( u , bigraph , visitU , visitV , matchV ) inverse = [ not b for b in visitU ] return ( inverse , visitV )
Bipartite minimum vertex cover by Koenig s theorem
19,882
def union_rectangles ( R ) : if R == [ ] : return 0 X = [ ] Y = [ ] for j in range ( len ( R ) ) : ( x1 , y1 , x2 , y2 ) = R [ j ] assert x1 <= x2 and y1 <= y2 X . append ( x1 ) X . append ( x2 ) Y . append ( ( y1 , + 1 , j ) ) Y . append ( ( y2 , - 1 , j ) ) X . sort ( ) Y . sort ( ) X2i = { X [ i ] : i for i in range ( len ( X ) ) } L = [ X [ i + 1 ] - X [ i ] for i in range ( len ( X ) - 1 ) ] C = Cover_query ( L ) area = 0 last = 0 for ( y , delta , j ) in Y : area += ( y - last ) * C . cover ( ) last = y ( x1 , y1 , x2 , y2 ) = R [ j ] i = X2i [ x1 ] k = X2i [ x2 ] C . change ( i , k , delta ) return area
Area of union of rectangles
19,883
def read ( filename ) : formula = [ ] for line in open ( filename , 'r' ) : line = line . strip ( ) if line [ 0 ] == "#" : continue lit = line . split ( ":-" ) if len ( lit ) == 1 : posvar = lit [ 0 ] negvars = [ ] else : assert len ( lit ) == 2 posvar = lit [ 0 ] . strip ( ) if posvar == '' : posvar = None negvars = lit [ 1 ] . split ( ',' ) for i in range ( len ( negvars ) ) : negvars [ i ] = negvars [ i ] . strip ( ) formula . append ( ( posvar , negvars ) ) return formula
reads a Horn SAT formula from a text file
19,884
def horn_sat ( formula ) : CLAUSES = range ( len ( formula ) ) score = [ 0 for c in CLAUSES ] posvar_in_clause = [ None for c in CLAUSES ] clauses_with_negvar = defaultdict ( set ) for c in CLAUSES : posvar , negvars = formula [ c ] score [ c ] = len ( set ( negvars ) ) posvar_in_clause [ c ] = posvar for v in negvars : clauses_with_negvar [ v ] . add ( c ) pool = [ set ( ) for s in range ( max ( score ) + 1 ) ] for c in CLAUSES : pool [ score [ c ] ] . add ( c ) solution = set ( ) while pool [ 0 ] : curr = pool [ 0 ] . pop ( ) v = posvar_in_clause [ curr ] if v == None : return None if v in solution or curr in clauses_with_negvar [ v ] : continue solution . add ( v ) for c in clauses_with_negvar [ v ] : pool [ score [ c ] ] . remove ( c ) score [ c ] -= 1 pool [ score [ c ] ] . add ( c ) return solution
Solving a HORN Sat formula
19,885
def dinic ( graph , capacity , source , target ) : assert source != target add_reverse_arcs ( graph , capacity ) Q = deque ( ) total = 0 n = len ( graph ) flow = [ [ 0 ] * n for u in range ( n ) ] while True : Q . appendleft ( source ) lev = [ None ] * n lev [ source ] = 0 while Q : u = Q . pop ( ) for v in graph [ u ] : if lev [ v ] is None and capacity [ u ] [ v ] > flow [ u ] [ v ] : lev [ v ] = lev [ u ] + 1 Q . appendleft ( v ) if lev [ target ] is None : return flow , total up_bound = sum ( capacity [ source ] [ v ] for v in graph [ source ] ) - total total += _dinic_step ( graph , capacity , lev , flow , source , target , up_bound )
Maximum flow by Dinic
19,886
def pop ( self ) : root = self . heap [ 1 ] del self . rank [ root ] x = self . heap . pop ( ) if self : self . heap [ 1 ] = x self . rank [ x ] = 1 self . down ( 1 ) return root
Remove and return smallest element
19,887
def update ( self , old , new ) : i = self . rank [ old ] del self . rank [ old ] self . heap [ i ] = new self . rank [ new ] = i if old < new : self . down ( i ) else : self . up ( i )
Replace an element in the heap
19,888
def kruskal ( graph , weight ) : uf = UnionFind ( len ( graph ) ) edges = [ ] for u in range ( len ( graph ) ) : for v in graph [ u ] : edges . append ( ( weight [ u ] [ v ] , u , v ) ) edges . sort ( ) mst = [ ] for w , u , v in edges : if uf . union ( u , v ) : mst . append ( ( u , v ) ) return mst
Minimum spanning tree by Kruskal
19,889
def union ( self , x , y ) : repr_x = self . find ( x ) repr_y = self . find ( y ) if repr_x == repr_y : return False if self . rank [ repr_x ] == self . rank [ repr_y ] : self . rank [ repr_x ] += 1 self . up [ repr_y ] = repr_x elif self . rank [ repr_x ] > self . rank [ repr_y ] : self . up [ repr_y ] = repr_x else : self . up [ repr_x ] = repr_y return True
Merges part that contain x and part containing y
19,890
def insert ( self , anchor ) : self . prec = anchor . prec self . succ = anchor self . succ . prec = self self . prec . succ = self
insert list item before anchor
19,891
def append ( self , item ) : if not self . items : self . items = item item . insert ( self . items )
add item to the end of the item list
19,892
def remove ( self ) : DoubleLinkedListItem . remove ( self ) if self . succ is self : self . theclass . items = None elif self . theclass . items is self : self . theclass . items = self . succ
remove item from its class
19,893
def tolist ( self ) : return [ [ x . val for x in theclass . items ] for theclass in self . classes ]
produce a list representation of the partition
19,894
def order ( self ) : return [ x . val for theclass in self . classes for x in theclass . items ]
Produce a flatten list of the partition ordered by classes
19,895
def eratosthene ( n ) : P = [ True ] * n answ = [ 2 ] for i in range ( 3 , n , 2 ) : if P [ i ] : answ . append ( i ) for j in range ( 2 * i , n , i ) : P [ j ] = False return answ
Prime numbers by sieve of Eratosthene
19,896
def _augment ( graph , capacity , flow , source , target ) : n = len ( graph ) A = [ 0 ] * n augm_path = [ None ] * n Q = deque ( ) Q . append ( source ) augm_path [ source ] = source A [ source ] = float ( 'inf' ) while Q : u = Q . popleft ( ) for v in graph [ u ] : cuv = capacity [ u ] [ v ] residual = cuv - flow [ u ] [ v ] if residual > 0 and augm_path [ v ] is None : augm_path [ v ] = u A [ v ] = min ( A [ u ] , residual ) if v == target : break else : Q . append ( v ) return ( augm_path , A [ target ] )
find a shortest augmenting path
19,897
def edmonds_karp ( graph , capacity , source , target ) : add_reverse_arcs ( graph , capacity ) V = range ( len ( graph ) ) flow = [ [ 0 for v in V ] for u in V ] while True : augm_path , delta = _augment ( graph , capacity , flow , source , target ) if delta == 0 : break v = target while v != source : u = augm_path [ v ] flow [ u ] [ v ] += delta flow [ v ] [ u ] -= delta v = u return ( flow , sum ( flow [ source ] ) )
Maximum flow by Edmonds - Karp
19,898
def gauss_jordan ( A , x , b ) : n = len ( x ) m = len ( b ) assert len ( A ) == m and len ( A [ 0 ] ) == n S = [ ] for i in range ( m ) : S . append ( A [ i ] [ : ] + [ b [ i ] ] ) S . append ( list ( range ( n ) ) ) k = diagonalize ( S , n , m ) if k < m : for i in range ( k , m ) : if not is_zero ( S [ i ] [ n ] ) : return GJ_ZERO_SOLUTIONS for j in range ( k ) : x [ S [ m ] [ j ] ] = S [ j ] [ n ] if k < n : for j in range ( k , n ) : x [ S [ m ] [ j ] ] = 0 return GJ_SEVERAL_SOLUTIONS return GJ_SINGLE_SOLUTION
Linear equation system Ax = b by Gauss - Jordan
19,899
def rabin_karp_matching ( s , t ) : hash_s = 0 hash_t = 0 len_s = len ( s ) len_t = len ( t ) last_pos = pow ( DOMAIN , len_t - 1 ) % PRIME if len_s < len_t : return - 1 for i in range ( len_t ) : hash_s = ( DOMAIN * hash_s + ord ( s [ i ] ) ) % PRIME hash_t = ( DOMAIN * hash_t + ord ( t [ i ] ) ) % PRIME for i in range ( len_s - len_t + 1 ) : if hash_s == hash_t : if matches ( s , t , i , 0 , len_t ) : return i if i < len_s - len_t : hash_s = roll_hash ( hash_s , ord ( s [ i ] ) , ord ( s [ i + len_t ] ) , last_pos ) return - 1
Find a substring by Rabin - Karp