codeparrot/xlcost-text-to-code huggingface dataset:
Length of the longest substring without repeating characters | This functionr eturns true if all characters in strr [ i . . j ] are distinct , otherwise returns false ; Note : Default values in visited are false ; Returns length of the longest substring with all distinct characters . ; Result ; Driver code
def areDistinct ( strr , i , j ) : NEW_LINE INDENT visited = [ 0 ] * ( 26 ) NEW_LINE for k in range ( i , j + 1 ) : NEW_LINE INDENT if ( visited [ ord ( strr [ k ] ) - ord ( ' a ' ) ] == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT visited [ ord ( strr [ k ] ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT return True NEW_LINE DEDENT def longestUniqueSubsttr ( strr ) : NEW_LINE INDENT n = len ( strr ) NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT if ( areDistinct ( strr , i , j ) ) : NEW_LINE INDENT res = max ( res , j - i + 1 ) NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = " geeksforgeeks " NEW_LINE print ( " The ▁ input ▁ is ▁ " , strr ) NEW_LINE len = longestUniqueSubsttr ( strr ) NEW_LINE print ( " The ▁ length ▁ of ▁ the ▁ longest ▁ " " non - repeating ▁ character ▁ substring ▁ is ▁ " , len ) NEW_LINE DEDENT
Remove duplicates from a given string | Function to make the string unique ; loop to traverse the string and check for repeating chars using IndexOf ( ) method in Java ; character at i 'th index of s ; if c is present in str , it returns the index of c , else it returns - 1 print ( st . index ( c ) ) ; adding c to str if - 1 is returned ; Driver code ; Input string with repeating chars
def unique ( s ) : NEW_LINE INDENT st = " " NEW_LINE length = len ( s ) NEW_LINE for i in range ( length ) : NEW_LINE INDENT c = s [ i ] NEW_LINE if c not in st : NEW_LINE INDENT st += c NEW_LINE DEDENT DEDENT return st NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE print ( unique ( s ) ) NEW_LINE DEDENT
Sum of all subsets whose sum is a Perfect Number from a given array | Python3 program for the above approach ; Function to check is a given number is a perfect number or not ; Stores the sum of its divisors ; Add all divisors of x to sum_div ; If the sum of divisors is equal to the given number , return true ; Otherwise , return false ; Function to find sum of all subsets from an array whose sum is a perfect number ; Prthe current subset sum if it is a perfect number ; Check if sum is a perfect number or not ; Calculate sum of the subset including arr [ l ] ; Calculate sum of the subset excluding arr [ l ] ; Driver Code
import math NEW_LINE def isPerfect ( x ) : NEW_LINE INDENT sum_div = 1 NEW_LINE for i in range ( 2 , ( x // 2 ) + 1 ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT sum_div += i NEW_LINE DEDENT DEDENT if ( sum_div == x ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def subsetSum ( arr , l , r , sum ) : NEW_LINE INDENT if ( l > r ) : NEW_LINE INDENT if ( isPerfect ( sum ) != 0 ) : NEW_LINE INDENT print ( sum , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT subsetSum ( arr , l + 1 , r , sum + arr [ l ] ) NEW_LINE subsetSum ( arr , l + 1 , r , sum ) NEW_LINE DEDENT arr = [ 5 , 4 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE subsetSum ( arr , 0 , N - 1 , 0 ) NEW_LINE
Print all possible ways to split an array into K subsets | Utility function to find all possible ways to split array into K subsets ; If count of elements in K subsets are greater than or equal to N ; If count of subsets formed is equal to K ; Print K subsets by splitting array into K subsets ; Print current subset ; If current element is the last element of the subset ; Otherwise ; If any subset is occupied , then push the element in that first ; Recursively do the same for remaining elements ; Backtrack ; Otherwise , push it in an empty subset and increase the subset count by 1 ; Break to avoid the case of going in other empty subsets , if available , and forming the same combination ; Function to to find all possible ways to split array into K subsets ; Stores K subset by splitting array into K subsets ; Size of each subset must be less than the number of elements ; Driver Code ; Given array ; Given K ; Size of the array ; Prints all possible splits into subsets
def PartitionSub ( arr , i , N , K , nos , v ) : NEW_LINE INDENT if ( i >= N ) : NEW_LINE INDENT if ( nos == K ) : NEW_LINE INDENT for x in range ( len ( v ) ) : NEW_LINE INDENT print ( " { ▁ " , end = " " ) NEW_LINE for y in range ( len ( v [ x ] ) ) : NEW_LINE INDENT print ( v [ x ] [ y ] , end = " " ) NEW_LINE if ( y == len ( v [ x ] ) - 1 ) : NEW_LINE INDENT print ( " ▁ " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " , ▁ " , end = " " ) NEW_LINE DEDENT DEDENT if ( x == len ( v ) - 1 ) : NEW_LINE INDENT print ( " } " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " } , ▁ " , end = " " ) NEW_LINE DEDENT DEDENT print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE DEDENT return NEW_LINE DEDENT for j in range ( K ) : NEW_LINE INDENT if ( len ( v [ j ] ) > 0 ) : NEW_LINE INDENT v [ j ] . append ( arr [ i ] ) NEW_LINE PartitionSub ( arr , i + 1 , N , K , nos , v ) NEW_LINE v [ j ] . remove ( v [ j ] [ len ( v [ j ] ) - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT v [ j ] . append ( arr [ i ] ) NEW_LINE PartitionSub ( arr , i + 1 , N , K , nos + 1 , v ) NEW_LINE v [ j ] . remove ( v [ j ] [ len ( v [ j ] ) - 1 ] ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT def partKSubsets ( arr , N , K ) : NEW_LINE INDENT v = [ [ ] for i in range ( K ) ] NEW_LINE if ( K == 0 or K > N ) : NEW_LINE INDENT print ( " Not ▁ Possible " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ Subset ▁ Combinations ▁ are : ▁ " ) NEW_LINE PartitionSub ( arr , 0 , N , K , 0 , v ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE partKSubsets ( arr , N , K ) NEW_LINE DEDENT
Count the number of Prime Cliques in an undirected graph | Python3 implementation to Count the number of Prime Cliques in an undirected graph ; Stores the vertices ; Graph ; Degree of the vertices ; To store the count of prime cliques ; Function to create Sieve to check primes ; false here indicates that it is not prime ; Condition if prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to check if the given set of vertices in store array is a clique or not ; Run a loop for all set of edges ; If any edge is missing ; Function to find the count of all the cliques having prime size ; Check if any vertices from i + 1 can be inserted ; Add the vertex to store ; If the graph is not a clique of size k then it cannot be a clique by adding another edge ; Increase the count of prime cliques if the size of current clique is prime ; Check if another edge can be added ; Driver code
MAX = 100 NEW_LINE store = [ 0 for i in range ( MAX ) ] NEW_LINE n = 0 NEW_LINE graph = [ [ 0 for j in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE d = [ 0 for i in range ( MAX ) ] NEW_LINE ans = 0 NEW_LINE def SieveOfEratosthenes ( prime , p_size ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while ( p * p <= p_size ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , p_size + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def is_clique ( b ) : NEW_LINE INDENT for i in range ( 1 , b ) : NEW_LINE INDENT for j in range ( i + 1 , b ) : NEW_LINE INDENT if ( graph [ store [ i ] ] [ store [ j ] ] == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def primeCliques ( i , l , prime ) : NEW_LINE INDENT global ans NEW_LINE for j in range ( i + 1 , n + 1 ) : NEW_LINE INDENT store [ l ] = j NEW_LINE if ( is_clique ( l + 1 ) ) : NEW_LINE INDENT if ( prime [ l ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT primeCliques ( j , l + 1 , prime ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT edges = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 3 , 1 ] , [ 4 , 3 ] , [ 4 , 5 ] , [ 5 , 3 ] ] NEW_LINE size = len ( edges ) NEW_LINE n = 5 NEW_LINE prime = [ True for i in range ( n + 2 ) ] NEW_LINE SieveOfEratosthenes ( prime , n + 1 ) NEW_LINE for i in range ( size ) : NEW_LINE INDENT graph [ edges [ i ] [ 0 ] ] [ edges [ i ] [ 1 ] ] = 1 NEW_LINE graph [ edges [ i ] [ 1 ] ] [ edges [ i ] [ 0 ] ] = 1 NEW_LINE d [ edges [ i ] [ 0 ] ] += 1 NEW_LINE d [ edges [ i ] [ 1 ] ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE primeCliques ( 0 , 1 , prime ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Construct a Doubly linked linked list from 2D Matrix | define dimension of matrix ; struct node of doubly linked list with four pointer next , prev , up , down ; function to create a new node ; function to construct the doubly linked list ; Create Node with value contain in matrix at index ( i , j ) ; Assign address of curr into the prev pointer of temp ; Assign address of curr into the up pointer of temp ; Recursive call for next pointer ; Recursive call for down pointer ; Return newly constructed node whose all four node connected at it 's appropriate position ; Function to construct the doubly linked list ; function call for construct the doubly linked list ; function for displaying doubly linked list data ; pointer to move right ; pointer to move down ; loop till node -> down is not NULL ; loop till node -> right is not NULL ; Driver code ; initialise matrix
dim = 3 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . prev = None NEW_LINE self . up = None NEW_LINE self . down = None NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def createNode ( data ) : NEW_LINE INDENT temp = Node ( data ) ; NEW_LINE return temp ; NEW_LINE DEDENT def constructDoublyListUtil ( mtrx , i , j , curr ) : NEW_LINE INDENT if ( i >= dim or j >= dim ) : NEW_LINE INDENT return None ; NEW_LINE DEDENT temp = createNode ( mtrx [ i ] [ j ] ) ; NEW_LINE temp . prev = curr ; NEW_LINE temp . up = curr ; NEW_LINE temp . next = constructDoublyListUtil ( mtrx , i , j + 1 , temp ) ; NEW_LINE temp . down = constructDoublyListUtil ( mtrx , i + 1 , j , temp ) ; NEW_LINE return temp ; NEW_LINE DEDENT def constructDoublyList ( mtrx ) : NEW_LINE INDENT return constructDoublyListUtil ( mtrx , 0 , 0 , None ) ; NEW_LINE DEDENT def display ( head ) : NEW_LINE INDENT rPtr = None NEW_LINE dPtr = head ; NEW_LINE while ( dPtr != None ) : NEW_LINE INDENT rPtr = dPtr ; NEW_LINE while ( rPtr != None ) : NEW_LINE INDENT print ( rPtr . data , end = ' ▁ ' ) NEW_LINE rPtr = rPtr . next ; NEW_LINE DEDENT print ( ) NEW_LINE dPtr = dPtr . down ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mtrx = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE list = constructDoublyList ( mtrx ) ; NEW_LINE display ( list ) ; NEW_LINE DEDENT
Count of exponential paths in a Binary Tree | Python3 program to find the count exponential paths in Binary Tree ; Structure of a Tree node ; Function to create a new node ; Function to find x ; Take log10 of n ; Log ( n ) with base i ; Raising i to the power p ; Function to check whether the given node equals to x ^ y for some y > 0 ; Take logx ( n ) with base x ; Utility function to count the exponent path in a given Binary tree ; Base Condition , when node pointer becomes null or node value is not a number of pow ( x , y ) ; Increment count when encounter leaf node ; Left recursive call save the value of count ; Right recursive call and return value of count ; Function to count exponential paths ; Create Tree ; Retrieve the value of x ; Function call
import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( key ) : NEW_LINE INDENT temp = Node ( key ) NEW_LINE return temp NEW_LINE DEDENT def find_x ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT num = math . log10 ( n ) NEW_LINE x , no = 0 , 0 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT den = math . log10 ( i ) NEW_LINE p = num / den NEW_LINE no = int ( pow ( i , int ( p ) ) ) NEW_LINE if abs ( no - n ) < 1e-6 : NEW_LINE INDENT x = i NEW_LINE break NEW_LINE DEDENT DEDENT return x NEW_LINE DEDENT def is_key ( n , x ) : NEW_LINE INDENT p = math . log10 ( n ) / math . log10 ( x ) NEW_LINE no = int ( pow ( x , int ( p ) ) ) NEW_LINE if n == no : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def evenPaths ( node , count , x ) : NEW_LINE INDENT if node == None or not is_key ( node . key , x ) : NEW_LINE INDENT return count NEW_LINE DEDENT if node . left == None and node . right == None : NEW_LINE INDENT count += 1 NEW_LINE DEDENT count = evenPaths ( node . left , count , x ) NEW_LINE return evenPaths ( node . right , count , x ) NEW_LINE DEDENT def countExpPaths ( node , x ) : NEW_LINE INDENT return evenPaths ( node , 0 , x ) NEW_LINE DEDENT root = newNode ( 27 ) NEW_LINE root . left = newNode ( 9 ) NEW_LINE root . right = newNode ( 81 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE root . left . right = newNode ( 10 ) NEW_LINE root . right . left = newNode ( 70 ) NEW_LINE root . right . right = newNode ( 243 ) NEW_LINE root . right . right . left = newNode ( 81 ) NEW_LINE root . right . right . right = newNode ( 909 ) NEW_LINE x = find_x ( root . key ) NEW_LINE print ( countExpPaths ( root , x ) ) NEW_LINE
Number of pairs such that path between pairs has the two vertices A and B | Python 3 program to find the number of pairs such that the path between every pair contains two given vertices ; Function to perform DFS on the given graph by fixing the a vertex ; To mark a particular vertex as visited ; Variable to store the count of the vertices which can be reached from a ; Performing the DFS by iterating over the visited array ; If the vertex is not visited and removing the vertex b ; Function to return the number of pairs such that path between any two pairs consists of the given two vertices A and B ; Initializing the visited array and assigning it with 0 's ; Initially , the count of vertices is 0 ; Performing DFS by removing the vertex B ; Count the vertices which cannot be reached after removing the vertex B ; Again reinitializing the visited array ; Setting the count of vertices to 0 to perform the DFS again ; Performing the DFS by removing the vertex A ; Count the vertices which cannot be reached after removing the vertex A ; Multiplying both the vertices set ; Driver code ; Loop to store the graph
N = 1000001 NEW_LINE c = 0 NEW_LINE n = 0 NEW_LINE m = 0 NEW_LINE a = 0 NEW_LINE b = 0 NEW_LINE def dfs ( a , b , v , vis ) : NEW_LINE INDENT global c NEW_LINE vis [ a ] = 1 NEW_LINE c += 1 NEW_LINE for i in v [ a ] : NEW_LINE INDENT if ( vis [ i ] == 0 and i != b ) : NEW_LINE INDENT dfs ( i , b , v , vis ) NEW_LINE DEDENT DEDENT DEDENT def Calculate ( v ) : NEW_LINE INDENT global c NEW_LINE vis = [ 0 for i in range ( n + 1 ) ] NEW_LINE c = 0 NEW_LINE dfs ( a , b , v , vis ) NEW_LINE ans1 = n - c - 1 NEW_LINE vis = [ 0 for i in range ( len ( vis ) ) ] NEW_LINE c = 0 NEW_LINE dfs ( b , a , v , vis ) NEW_LINE ans2 = n - c - 1 NEW_LINE print ( ans1 * ans2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 NEW_LINE m = 7 NEW_LINE a = 3 NEW_LINE b = 5 NEW_LINE edges = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 3 , 4 ] , [ 4 , 5 ] , [ 5 , 6 ] , [ 6 , 7 ] , [ 7 , 5 ] ] NEW_LINE v = [ [ ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT v [ edges [ i ] [ 0 ] ] . append ( edges [ i ] [ 1 ] ) NEW_LINE v [ edges [ i ] [ 1 ] ] . append ( edges [ i ] [ 0 ] ) NEW_LINE DEDENT Calculate ( v ) NEW_LINE DEDENT
Travelling Salesman Problem implementation using BackTracking | Python3 implementation of the approach ; Function to find the minimum weight Hamiltonian Cycle ; If last node is reached and it has a link to the starting node i . e the source then keep the minimum value out of the total cost of traversal and " ans " Finally return to check for more possible values ; BACKTRACKING STEP Loop to traverse the adjacency list of currPos node and increasing the count by 1 and cost by graph [ currPos ] [ i ] value ; Mark as visited ; Mark ith node as unvisited ; n is the number of nodes i . e . V ; Boolean array to check if a node has been visited or not ; Mark 0 th node as visited ; Find the minimum weight Hamiltonian Cycle ; ans is the minimum weight Hamiltonian Cycle
V = 4 NEW_LINE answer = [ ] NEW_LINE def tsp ( graph , v , currPos , n , count , cost ) : NEW_LINE INDENT if ( count == n and graph [ currPos ] [ 0 ] ) : NEW_LINE INDENT answer . append ( cost + graph [ currPos ] [ 0 ] ) NEW_LINE return NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( v [ i ] == False and graph [ currPos ] [ i ] ) : NEW_LINE INDENT v [ i ] = True NEW_LINE tsp ( graph , v , i , n , count + 1 , cost + graph [ currPos ] [ i ] ) NEW_LINE v [ i ] = False NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE graph = [ [ 0 , 10 , 15 , 20 ] , [ 10 , 0 , 35 , 25 ] , [ 15 , 35 , 0 , 30 ] , [ 20 , 25 , 30 , 0 ] ] NEW_LINE v = [ False for i in range ( n ) ] NEW_LINE v [ 0 ] = True NEW_LINE tsp ( graph , v , 0 , n , 1 , 0 ) NEW_LINE print ( min ( answer ) ) NEW_LINE DEDENT
Generate all the binary strings of N bits | Function to print the output ; Function to generate all binary strings ; First assign "0" at ith position and try for all other permutations for remaining positions ; And then assign "1" at ith position and try for all other permutations for remaining positions ; Driver Code ; Print all binary strings
def printTheArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def generateAllBinaryStrings ( n , arr , i ) : NEW_LINE INDENT if i == n : NEW_LINE INDENT printTheArray ( arr , n ) NEW_LINE return NEW_LINE DEDENT arr [ i ] = 0 NEW_LINE generateAllBinaryStrings ( n , arr , i + 1 ) NEW_LINE arr [ i ] = 1 NEW_LINE generateAllBinaryStrings ( n , arr , i + 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE arr = [ None ] * n NEW_LINE generateAllBinaryStrings ( n , arr , 0 ) NEW_LINE DEDENT
Combinations where every element appears twice and distance between appearances is equal to the value | Find all combinations that satisfies given constraints ; if all elements are filled , print the solution ; Try all possible combinations for element elem ; if position i and ( i + elem + 1 ) are not occupied in the vector ; place elem at position i and ( i + elem + 1 ) ; recurse for next element ; backtrack ( remove elem from position i and ( i + elem + 1 ) ) ; create a vector of double the size of given number with ; all its elements initialized by 1 ; start from element 1 ; given number
def allCombinationsRec ( arr , elem , n ) : NEW_LINE INDENT if ( elem > n ) : NEW_LINE INDENT for i in ( arr ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT print ( " " ) NEW_LINE return NEW_LINE DEDENT for i in range ( 0 , 2 * n ) : NEW_LINE INDENT if ( arr [ i ] == - 1 and ( i + elem + 1 ) < 2 * n and arr [ i + elem + 1 ] == - 1 ) : NEW_LINE INDENT arr [ i ] = elem NEW_LINE arr [ i + elem + 1 ] = elem NEW_LINE allCombinationsRec ( arr , elem + 1 , n ) NEW_LINE arr [ i ] = - 1 NEW_LINE arr [ i + elem + 1 ] = - 1 NEW_LINE DEDENT DEDENT DEDENT def allCombinations ( n ) : NEW_LINE INDENT arr = [ - 1 ] * ( 2 * n ) NEW_LINE elem = 1 NEW_LINE allCombinationsRec ( arr , elem , n ) NEW_LINE DEDENT n = 3 NEW_LINE allCombinations ( n ) NEW_LINE
Printing all solutions in N | Python program for above approach ; Program to solve N - Queens Problem ; All_rows_filled is a bit mask having all N bits set ; If rowmask will have all bits set , means queen has been placed successfully in all rows and board is displayed ; We extract a bit mask ( safe ) by rowmask , ldmask and rdmask . all set bits of ' safe ' indicates the safe column index for queen placement of this iteration for row index ( row ) . ; Extracts the right - most set bit ( safe column index ) where queen can be placed for this row ; these bit masks will keep updated in each iteration for next row ; Reset right - most set bit to 0 so , next iteration will continue by placing the queen at another safe column index of this row ; Backtracking , replace ' Q ' by '  ; Program to print board ; Driver Code ; n = 4 board size ; Function Call
import math NEW_LINE result = [ ] NEW_LINE def solveBoard ( board , row , rowmask , ldmask , rdmask ) : NEW_LINE INDENT n = len ( board ) NEW_LINE all_rows_filled = ( 1 << n ) - 1 NEW_LINE if ( rowmask == all_rows_filled ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in board : NEW_LINE INDENT for j in range ( len ( i ) ) : NEW_LINE INDENT if i [ j ] == ' Q ' : NEW_LINE INDENT v . append ( j + 1 ) NEW_LINE DEDENT DEDENT DEDENT result . append ( v ) NEW_LINE DEDENT safe = all_rows_filled & ( ~ ( rowmask ldmask rdmask ) ) NEW_LINE while ( safe > 0 ) : NEW_LINE INDENT p = safe & ( - safe ) NEW_LINE col = ( int ) ( math . log ( p ) / math . log ( 2 ) ) NEW_LINE board [ row ] [ col ] = ' Q ' NEW_LINE solveBoard ( board , row + 1 , rowmask | p , ( ldmask p ) << 1 , ( rdmask p ) >> 1 ) NEW_LINE safe = safe & ( safe - 1 ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT board [ row ] [ col ] = ' ▁ ' NEW_LINE DEDENT def printBoard ( board ) : NEW_LINE INDENT for row in board : NEW_LINE INDENT print ( " | " + " | " . join ( row ) + " ▁ " ) NEW_LINE DEDENT DEDENT def main ( ) : NEW_LINE INDENT board = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT row = [ ] NEW_LINE for j in range ( n ) : NEW_LINE INDENT row . append ( ' ▁ ' ) NEW_LINE DEDENT board . append ( row ) NEW_LINE DEDENT rowmask = 0 NEW_LINE ldmask = 0 NEW_LINE rdmask = 0 NEW_LINE row = 0 NEW_LINE result . clear ( ) NEW_LINE solveBoard ( board , row , rowmask , ldmask , rdmask ) NEW_LINE result . sort ( ) NEW_LINE print ( result ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Find all distinct subsets of a given set using BitMasking Approach | Function to find all subsets of given set . Any repeated subset is considered only once in the output ; Run counter i from 000. . 0 to 111. . 1 ; consider each element in the set ; Check if jth bit in the i is set . If the bit is set , we consider jth element from set ; if subset is encountered for the first time If we use set < string > , we can directly insert ; consider every subset ; split the subset and print its elements ; Driver Code
def printPowerSet ( arr , n ) : NEW_LINE INDENT _list = [ ] NEW_LINE for i in range ( 2 ** n ) : NEW_LINE INDENT subset = " " NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( i & ( 1 << j ) ) != 0 : NEW_LINE INDENT subset += str ( arr [ j ] ) + " | " NEW_LINE DEDENT DEDENT if subset not in _list and len ( subset ) > 0 : NEW_LINE INDENT _list . append ( subset ) NEW_LINE DEDENT DEDENT for subset in _list : NEW_LINE INDENT arr = subset . split ( ' ▁ ' ) NEW_LINE for string in arr : NEW_LINE INDENT print ( string , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 12 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE printPowerSet ( arr , n ) NEW_LINE DEDENT