text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Convert a Binary Tree into Doubly Linked List in spiral fashion | Binary tree node ; Given a reference to the head of a list and a node , inserts the node on the front of the list . ; Make right of given node as head and left as None ; change left of head node to given node ; move the head to point to the given node ; Function to prints contents of DLL ; Function to prcorner node at each level ; Base Case ; Create an empty deque for doing spiral level order traversal and enqueue root ; create a stack to store Binary Tree nodes to insert into DLL later ; nodeCount indicates number of Nodes at current level . ; Dequeue all Nodes of current level and Enqueue all Nodes of next level odd level ; dequeue node from front & push it to stack ; insert its left and right children in the back of the deque ; even level ; dequeue node from the back & push it to stack ; inserts its right and left children in the front of the deque ; head pointer for DLL ; pop all nodes from stack and push them in the beginning of the list ; Driver Code ; Let us create Binary Tree as shown in above example ; root . right . left . left = newNode ( 12 ) ; root . right . right . right = newNode ( 15 )
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def push ( head_ref , node ) : NEW_LINE INDENT node . right = ( head_ref ) NEW_LINE node . left = None NEW_LINE if ( ( head_ref ) != None ) : NEW_LINE INDENT ( head_ref ) . left = node NEW_LINE DEDENT ( head_ref ) = node NEW_LINE DEDENT def printList ( node ) : NEW_LINE INDENT i = 0 NEW_LINE while ( i < len ( node ) ) : NEW_LINE INDENT print ( node [ i ] . data , end = " ▁ " ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT def spiralLevelOrder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE stk = [ ] NEW_LINE level = 0 NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT nodeCount = len ( q ) NEW_LINE if ( level & 1 ) : NEW_LINE INDENT while ( nodeCount > 0 ) : NEW_LINE INDENT node = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE stk . append ( node ) NEW_LINE if ( node . left != None ) : NEW_LINE INDENT q . append ( node . left ) NEW_LINE DEDENT if ( node . right != None ) : NEW_LINE INDENT q . append ( node . right ) NEW_LINE DEDENT nodeCount -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT while ( nodeCount > 0 ) : NEW_LINE INDENT node = q [ - 1 ] NEW_LINE q . pop ( - 1 ) NEW_LINE stk . append ( node ) NEW_LINE if ( node . right != None ) : NEW_LINE INDENT q . insert ( 0 , node . right ) NEW_LINE DEDENT if ( node . left != None ) : NEW_LINE INDENT q . insert ( 0 , node . left ) NEW_LINE DEDENT nodeCount -= 1 NEW_LINE DEDENT DEDENT level += 1 NEW_LINE DEDENT head = [ ] NEW_LINE while ( len ( stk ) ) : NEW_LINE INDENT head . append ( stk [ 0 ] ) NEW_LINE stk . pop ( 0 ) NEW_LINE DEDENT print ( " Created ▁ DLL ▁ is : " ) NEW_LINE printList ( head ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . left . left . left = newNode ( 8 ) NEW_LINE root . left . left . right = newNode ( 9 ) NEW_LINE root . left . right . left = newNode ( 10 ) NEW_LINE root . left . right . right = newNode ( 11 ) NEW_LINE root . right . left . right = newNode ( 13 ) NEW_LINE root . right . right . left = newNode ( 14 ) NEW_LINE spiralLevelOrder ( root ) NEW_LINE DEDENT
Reverse individual words | reverses individual words of a string ; Traverse given string and push all characters to stack until we see a space . ; When we see a space , we print contents of stack . ; Since there may not be space after last word . ; Driver Code
def reverserWords ( string ) : NEW_LINE INDENT st = list ( ) NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if string [ i ] != " ▁ " : NEW_LINE INDENT st . append ( string [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT while len ( st ) > 0 : NEW_LINE INDENT print ( st [ - 1 ] , end = " " ) NEW_LINE st . pop ( ) NEW_LINE DEDENT print ( end = " ▁ " ) NEW_LINE DEDENT DEDENT while len ( st ) > 0 : NEW_LINE INDENT print ( st [ - 1 ] , end = " " ) NEW_LINE st . pop ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " Geeks ▁ for ▁ Geeks " NEW_LINE reverserWords ( string ) NEW_LINE DEDENT
Count subarrays where second highest lie before highest | Python3 program to count number of distinct instance where second highest number lie before highest number in all subarrays . ; Finding the next greater element of the array . ; Finding the previous greater element of the array . ; Wrapper Function ; Finding previous largest element ; Finding next largest element ; Driver Code
from typing import List NEW_LINE MAXN = 100005 NEW_LINE def makeNext ( arr : List [ int ] , n : int , nextBig : List [ int ] ) -> None : NEW_LINE INDENT s = [ ] NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT nextBig [ i ] = i NEW_LINE while len ( s ) and s [ - 1 ] [ 0 ] < arr [ i ] : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT if len ( s ) : NEW_LINE INDENT nextBig [ i ] = s [ - 1 ] [ 1 ] NEW_LINE DEDENT s . append ( ( arr [ i ] , i ) ) NEW_LINE DEDENT DEDENT def makePrev ( arr : List [ int ] , n : int , prevBig : List [ int ] ) -> None : NEW_LINE INDENT s = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT prevBig [ i ] = - 1 NEW_LINE while ( len ( s ) and s [ - 1 ] [ 0 ] < arr [ i ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT if ( len ( s ) ) : NEW_LINE INDENT prevBig [ i ] = s [ - 1 ] [ 1 ] NEW_LINE DEDENT s . append ( ( arr [ i ] , i ) ) NEW_LINE DEDENT DEDENT def wrapper ( arr : List [ int ] , n : int ) -> int : NEW_LINE INDENT nextBig = [ 0 ] * MAXN NEW_LINE prevBig = [ 0 ] * MAXN NEW_LINE maxi = [ 0 ] * MAXN NEW_LINE ans = 0 NEW_LINE makePrev ( arr , n , prevBig ) NEW_LINE makeNext ( arr , n , nextBig ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( nextBig [ i ] != i ) : NEW_LINE INDENT maxi [ nextBig [ i ] - i ] = max ( maxi [ nextBig [ i ] - i ] , i - prevBig [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT ans += maxi [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( wrapper ( arr , n ) ) NEW_LINE DEDENT
Program for Tower of Hanoi | Recursive Python function to solve tower of hanoi ; Number of disks ; A , C , B are the name of rods
def TowerOfHanoi ( n , from_rod , to_rod , aux_rod ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT print ( " Move ▁ disk ▁ 1 ▁ from ▁ rod " , from_rod , " to ▁ rod " , to_rod ) NEW_LINE return NEW_LINE DEDENT TowerOfHanoi ( n - 1 , from_rod , aux_rod , to_rod ) NEW_LINE print ( " Move ▁ disk " , n , " from ▁ rod " , from_rod , " to ▁ rod " , to_rod ) NEW_LINE TowerOfHanoi ( n - 1 , aux_rod , to_rod , from_rod ) NEW_LINE DEDENT n = 4 NEW_LINE TowerOfHanoi ( n , ' A ' , ' C ' , ' B ' ) NEW_LINE
Find maximum of minimum for every window size in a given array | A naive method to find maximum of minimum of all windows of different sizes ; Consider all windows of different sizes starting from size 1 ; Initialize max of min for current window size k ; Traverse through all windows of current size k ; Find minimum of current window ; Update maxOfMin if required ; Print max of min for current window size ; Driver Code
INT_MIN = - 1000000 NEW_LINE def printMaxOfMin ( arr , n ) : NEW_LINE INDENT for k in range ( 1 , n + 1 ) : NEW_LINE INDENT maxOfMin = INT_MIN ; NEW_LINE for i in range ( n - k + 1 ) : NEW_LINE INDENT min = arr [ i ] NEW_LINE for j in range ( k ) : NEW_LINE INDENT if ( arr [ i + j ] < min ) : NEW_LINE INDENT min = arr [ i + j ] NEW_LINE DEDENT DEDENT if ( min > maxOfMin ) : NEW_LINE INDENT maxOfMin = min NEW_LINE DEDENT DEDENT print ( maxOfMin , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 10 , 20 , 30 , 50 , 10 , 70 , 30 ] NEW_LINE n = len ( arr ) NEW_LINE printMaxOfMin ( arr , n ) NEW_LINE
Find maximum of minimum for every window size in a given array | An efficient Python3 program to find maximum of all minimums of windows of different sizes ; Used to find previous and next smaller ; Initialize elements of left [ ] and right [ ] ; Fill elements of left [ ] using logic discussed on www . geeksforgeeks . org / next - greater - element https : ; Empty the stack as stack is going to be used for right [ ] ; Fill elements of right [ ] using same logic ; Create and initialize answer array ; Fill answer array by comparing minimums of all . Lengths computed using left [ ] and right [ ] ; Length of the interval ; arr [ i ] is a possible answer for this Length ' Len ' interval , check if arr [ i ] is more than max for 'Len ; Some entries in ans [ ] may not be filled yet . Fill them by taking values from right side of ans [ ] ; Print the result ; Driver Code
def printMaxOfMin ( arr , n ) : NEW_LINE INDENT s = [ ] NEW_LINE left = [ - 1 ] * ( n + 1 ) NEW_LINE right = [ n ] * ( n + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( len ( s ) != 0 and arr [ s [ - 1 ] ] >= arr [ i ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT if ( len ( s ) != 0 ) : NEW_LINE INDENT left [ i ] = s [ - 1 ] NEW_LINE DEDENT s . append ( i ) NEW_LINE DEDENT while ( len ( s ) != 0 ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT while ( len ( s ) != 0 and arr [ s [ - 1 ] ] >= arr [ i ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT if ( len ( s ) != 0 ) : NEW_LINE INDENT right [ i ] = s [ - 1 ] NEW_LINE DEDENT s . append ( i ) NEW_LINE DEDENT ans = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT ans [ i ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT Len = right [ i ] - left [ i ] - 1 NEW_LINE ans [ Len ] = max ( ans [ Len ] , arr [ i ] ) NEW_LINE DEDENT for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT ans [ i ] = max ( ans [ i ] , ans [ i + 1 ] ) NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 20 , 30 , 50 , 10 , 70 , 30 ] NEW_LINE n = len ( arr ) NEW_LINE printMaxOfMin ( arr , n ) NEW_LINE DEDENT
Length of the longest valid substring | method to get length of the longest valid ; Create a stack and push - 1 as initial index to it . ; Initialize result ; Traverse all characters of given string ; If opening bracket , push index of it ; If closing bracket ; Pop the previous opening bracket 's index ; Check if this length formed with base of current valid substring is more than max so far ; If stack is empty . push current index as base for next valid substring ( if any ) ; Driver code ; Function call ; Function call
def findMaxLen ( string ) : NEW_LINE INDENT n = len ( string ) NEW_LINE stk = [ ] NEW_LINE stk . append ( - 1 ) NEW_LINE result = 0 NEW_LINE for i in xrange ( n ) : NEW_LINE INDENT if string [ i ] == ' ( ' : NEW_LINE INDENT stk . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT if len ( stk ) != 0 : NEW_LINE stk . pop ( ) NEW_LINE if len ( stk ) != 0 : NEW_LINE INDENT result = max ( result , i - stk [ len ( stk ) - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT stk . append ( i ) NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT string = " ( ( ( ) ( ) " NEW_LINE print findMaxLen ( string ) NEW_LINE string = " ( ) ( ( ) ) ) ) ) " NEW_LINE print findMaxLen ( string ) NEW_LINE
Convert a tree to forest of even nodes | Return the number of nodes of subtree having node as a root . ; Mark node as visited . ; Traverse the adjacency list to find non - visited node . ; Finding number of nodes of the subtree of a subtree . ; If nodes are even , increment number of edges to removed . Else leave the node as child of subtree . ; Return the maximum number of edge to remove to make forest . ; Driver Code
def dfs ( tree , visit , ans , node ) : NEW_LINE INDENT num = 0 NEW_LINE temp = 0 NEW_LINE visit [ node ] = 1 NEW_LINE for i in range ( len ( tree [ node ] ) ) : NEW_LINE INDENT if ( visit [ tree [ node ] [ i ] ] == 0 ) : NEW_LINE INDENT temp = dfs ( tree , visit , ans , tree [ node ] [ i ] ) NEW_LINE if ( temp % 2 ) : NEW_LINE INDENT num += temp NEW_LINE DEDENT else : NEW_LINE INDENT ans [ 0 ] += 1 NEW_LINE DEDENT DEDENT DEDENT return num + 1 NEW_LINE DEDENT def minEdge ( tree , n ) : NEW_LINE INDENT visit = [ 0 ] * ( n + 2 ) NEW_LINE ans = [ 0 ] NEW_LINE dfs ( tree , visit , ans , 1 ) NEW_LINE return ans [ 0 ] NEW_LINE DEDENT N = 12 NEW_LINE n = 10 NEW_LINE tree = [ [ ] for i in range ( n + 2 ) ] NEW_LINE tree [ 1 ] . append ( 3 ) NEW_LINE tree [ 3 ] . append ( 1 ) NEW_LINE tree [ 1 ] . append ( 6 ) NEW_LINE tree [ 6 ] . append ( 1 ) NEW_LINE tree [ 1 ] . append ( 2 ) NEW_LINE tree [ 2 ] . append ( 1 ) NEW_LINE tree [ 3 ] . append ( 4 ) NEW_LINE tree [ 4 ] . append ( 3 ) NEW_LINE tree [ 6 ] . append ( 8 ) NEW_LINE tree [ 8 ] . append ( 6 ) NEW_LINE tree [ 2 ] . append ( 7 ) NEW_LINE tree [ 7 ] . append ( 2 ) NEW_LINE tree [ 2 ] . append ( 5 ) NEW_LINE tree [ 5 ] . append ( 2 ) NEW_LINE tree [ 4 ] . append ( 9 ) NEW_LINE tree [ 9 ] . append ( 4 ) NEW_LINE tree [ 4 ] . append ( 10 ) NEW_LINE tree [ 10 ] . append ( 4 ) NEW_LINE print ( minEdge ( tree , n ) ) NEW_LINE
Length of the longest valid substring | Python3 program to find length of the longest valid substring ; Initialize curMax to zero ; Iterate over the string starting from second index ; Driver Code ; Function call ; Function call
def findMaxLen ( s ) : NEW_LINE INDENT if ( len ( s ) <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT curMax = 0 NEW_LINE longest = [ 0 ] * ( len ( s ) ) NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT if ( ( s [ i ] == ' ) ' and i - longest [ i - 1 ] - 1 >= 0 and s [ i - longest [ i - 1 ] - 1 ] == ' ( ' ) ) : NEW_LINE INDENT longest [ i ] = longest [ i - 1 ] + 2 NEW_LINE if ( i - longest [ i - 1 ] - 2 >= 0 ) : NEW_LINE INDENT longest [ i ] += ( longest [ i - longest [ i - 1 ] - 2 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT longest [ i ] += 0 NEW_LINE DEDENT curMax = max ( longest [ i ] , curMax ) NEW_LINE DEDENT DEDENT return curMax NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Str = " ( ( ( ) ( ) " NEW_LINE print ( findMaxLen ( Str ) ) NEW_LINE Str = " ( ) ( ( ) ) ) ) ) " NEW_LINE print ( findMaxLen ( Str ) ) NEW_LINE DEDENT
Length of the longest valid substring | Function to return the length of the longest valid substring ; Variables for left and right counter . maxlength to store the maximum length found so far ; Iterating the string from left to right ; If " ( " is encountered , then left counter is incremented else right counter is incremented ; Whenever left is equal to right , it signifies that the subsequence is valid and ; Reseting the counters when the subsequence becomes invalid ; Iterating the string from right to left ; If " ( " is encountered , then left counter is incremented else right counter is incremented ; Whenever left is equal to right , it signifies that the subsequence is valid and ; Reseting the counters when the subsequence becomes invalid ; Function call
def solve ( s , n ) : NEW_LINE INDENT left = 0 NEW_LINE right = 0 NEW_LINE maxlength = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT left += 1 NEW_LINE DEDENT else : NEW_LINE INDENT right += 1 NEW_LINE DEDENT if ( left == right ) : NEW_LINE INDENT maxlength = max ( maxlength , 2 * right ) NEW_LINE DEDENT elif ( right > left ) : NEW_LINE INDENT left = right = 0 NEW_LINE DEDENT DEDENT left = right = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT left += 1 NEW_LINE DEDENT else : NEW_LINE INDENT right += 1 NEW_LINE DEDENT if ( left == right ) : NEW_LINE INDENT maxlength = max ( maxlength , 2 * left ) NEW_LINE DEDENT elif ( left > right ) : NEW_LINE INDENT left = right = 0 NEW_LINE DEDENT DEDENT return maxlength NEW_LINE DEDENT print ( solve ( " ( ( ( ) ( ) ( ) ( ) ( ( ( ( ) ) " , 16 ) ) NEW_LINE
Expression contains redundant bracket or not | Function to check redundant brackets in a balanced expression ; create a stack of characters ; Iterate through the given expression ; if current character is close parenthesis ') ; If immediate pop have open parenthesis ' ( ' duplicate brackets found ; Check for operators in expression ; Fetch top element of stack ; If operators not found ; append open parenthesis ' ( ' , ; operators and operands to stack ; Function to check redundant brackets ; Driver code
def checkRedundancy ( Str ) : NEW_LINE INDENT st = [ ] NEW_LINE for ch in Str : NEW_LINE INDENT if ( ch == ' ) ' ) : NEW_LINE INDENT top = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE flag = True NEW_LINE while ( top != ' ( ' ) : NEW_LINE INDENT if ( top == ' + ' or top == ' - ' or top == ' * ' or top == ' / ' ) : NEW_LINE INDENT flag = False NEW_LINE DEDENT top = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE DEDENT if ( flag == True ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT st . append ( ch ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def findRedundant ( Str ) : NEW_LINE INDENT ans = checkRedundancy ( Str ) NEW_LINE if ( ans == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Str = " ( ( a + b ) ) " NEW_LINE findRedundant ( Str ) NEW_LINE Str = " ( a + ( b ) / c ) " NEW_LINE findRedundant ( Str ) NEW_LINE Str = " ( a + b * ( c - d ) ) " NEW_LINE findRedundant ( Str ) NEW_LINE DEDENT
Check if two expressions with brackets are same | Python3 program to check if two expressions evaluate to same . ; Return local sign of the operand . For example , in the expr a - b - ( c ) , local signs of the operands are + a , - b , + c ; Evaluate expressions into the count vector of the 26 alphabets . If add is True , then add count to the count vector of the alphabets , else remove count from the count vector . ; stack stores the global sign for operands . ; + means True global sign is positive initially ; global sign for the bracket is pushed to the stack ; global sign is popped out which was pushed in for the last bracket ; global sign is positive ( we use different values in two calls of functions so that we finally check if all vector elements are 0. ; global sign is negative here ; Returns True if expr1 and expr2 represent same expressions ; Create a vector for all operands and initialize the vector as 0. ; Put signs of all operands in expr1 ; Subtract signs of operands in expr2 ; If expressions are same , vector must be 0. ; Driver Code
MAX_CHAR = 26 ; NEW_LINE def adjSign ( s , i ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT if ( s [ i - 1 ] == ' - ' ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def eval ( s , v , add ) : NEW_LINE INDENT stk = [ ] NEW_LINE stk . append ( True ) ; NEW_LINE i = 0 ; NEW_LINE while ( i < len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' + ' or s [ i ] == ' - ' ) : NEW_LINE i += 1 NEW_LINE continue ; NEW_LINE if ( s [ i ] == ' ( ' ) : NEW_LINE if ( adjSign ( s , i ) ) : NEW_LINE INDENT stk . append ( stk [ - 1 ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT stk . append ( not stk [ - 1 ] ) ; NEW_LINE DEDENT elif ( s [ i ] == ' ) ' ) : NEW_LINE stk . pop ( ) ; NEW_LINE else : NEW_LINE if ( stk [ - 1 ] ) : NEW_LINE INDENT v [ ord ( s [ i ] ) - ord ( ' a ' ) ] += ( 1 if add else - 1 ) if adjSign ( s , i ) else ( - 1 if add else 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT v [ ord ( s [ i ] ) - ord ( ' a ' ) ] += ( - 1 if add else 1 ) if adjSign ( s , i ) else ( 1 if add else - 1 ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT def areSame ( expr1 , expr2 ) : NEW_LINE INDENT v = [ 0 for i in range ( MAX_CHAR ) ] ; NEW_LINE eval ( expr1 , v , True ) ; NEW_LINE eval ( expr2 , v , False ) ; NEW_LINE for i in range ( MAX_CHAR ) : NEW_LINE INDENT if ( v [ i ] != 0 ) : NEW_LINE return False ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT expr1 = " - ( a + b + c ) " NEW_LINE expr2 = " - a - b - c " ; NEW_LINE if ( areSame ( expr1 , expr2 ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Find index of closing bracket for a given opening bracket in an expression | Python program to find index of closing bracket for a given opening bracket . ; Function to find index of closing bracket for given opening bracket . ; If input is invalid . ; Create a deque to use it as a stack . ; Traverse through all elements starting from i . ; Push all starting brackets ; Pop a starting bracket for every closing bracket ; If deque becomes empty ; test function ; Driver code to test above method . ; should be 8 ; should be 7 ; should be 12 ; No matching bracket ; execution
from collections import deque NEW_LINE def getIndex ( s , i ) : NEW_LINE INDENT if s [ i ] != ' [ ' : NEW_LINE INDENT return - 1 NEW_LINE DEDENT d = deque ( ) NEW_LINE for k in range ( i , len ( s ) ) : NEW_LINE INDENT if s [ k ] == ' [ ' : NEW_LINE INDENT d . append ( s [ i ] ) NEW_LINE DEDENT elif s [ k ] == ' ] ' : NEW_LINE INDENT d . popleft ( ) NEW_LINE DEDENT if not d : NEW_LINE INDENT return k NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def test ( s , i ) : NEW_LINE INDENT matching_index = getIndex ( s , i ) NEW_LINE print ( s + " , ▁ " + str ( i ) + " : ▁ " + str ( matching_index ) ) NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT test ( " [ ABC [ 23 ] ] [89 ] " , 0 ) NEW_LINE test ( " [ ABC [ 23 ] ] [89 ] " , 4 ) NEW_LINE test ( " [ ABC [ 23 ] ] [89 ] " , 9 ) NEW_LINE test ( " [ ABC [ 23 ] ] [89 ] " , 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Convert a given Binary tree to a tree that holds Logical AND property | Program to convert an aribitary binary tree to a tree that holds children sum property Helper function that allocates a new node with the given data and None left and right poers . ; Construct to create a new node ; Convert the given tree to a tree where each node is logical AND of its children The main idea is to do Postorder traversal ; first recur on left child ; then recur on right child ; first recur on left child ; then print the data of node ; now recur on right child ; Driver Code ; Create following Binary Tree 1 / \ 1 0 / \ / \ 0 1 1 1
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def convertTree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT convertTree ( root . left ) NEW_LINE convertTree ( root . right ) NEW_LINE if ( root . left != None and root . right != None ) : NEW_LINE INDENT root . data = ( ( root . left . data ) & ( root . right . data ) ) NEW_LINE DEDENT DEDENT def printInorder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT printInorder ( root . left ) NEW_LINE print ( root . data , end = " ▁ " ) NEW_LINE printInorder ( root . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 0 ) NEW_LINE root . left = newNode ( 1 ) NEW_LINE root . right = newNode ( 0 ) NEW_LINE root . left . left = newNode ( 0 ) NEW_LINE root . left . right = newNode ( 1 ) NEW_LINE root . right . left = newNode ( 1 ) NEW_LINE root . right . right = newNode ( 1 ) NEW_LINE print ( " Inorder ▁ traversal ▁ before ▁ conversion " , end = " ▁ " ) NEW_LINE printInorder ( root ) NEW_LINE convertTree ( root ) NEW_LINE print ( " Inorder traversal after conversion " , ▁ end ▁ = ▁ " " ) NEW_LINE printInorder ( root ) NEW_LINE DEDENT
Find if an expression has duplicate parenthesis or not | Function to find duplicate parenthesis in a balanced expression ; create a stack of characters ; Iterate through the given expression ; if current character is close parenthesis ' ) ' ; pop character from the stack ; stores the number of characters between a closing and opening parenthesis if this count is less than or equal to 1 then the brackets are redundant else not ; push open parenthesis ' ( ' , operators and operands to stack ; No duplicates found ; Driver Code ; input balanced expression
def findDuplicateparenthesis ( string ) : NEW_LINE INDENT Stack = [ ] NEW_LINE for ch in string : NEW_LINE INDENT if ch == ' ) ' : NEW_LINE INDENT top = Stack . pop ( ) NEW_LINE elementsInside = 0 NEW_LINE while top != ' ( ' : NEW_LINE INDENT elementsInside += 1 NEW_LINE top = Stack . pop ( ) NEW_LINE DEDENT if elementsInside < 1 : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT Stack . append ( ch ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " ( ( ( a + ( b ) ) + ( c + d ) ) ) " NEW_LINE if findDuplicateparenthesis ( string ) == True : NEW_LINE INDENT print ( " Duplicate ▁ Found " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ Duplicates ▁ Found " ) NEW_LINE DEDENT DEDENT
Find next Smaller of next Greater in an array | function find Next greater element ; create empty stack ; Traverse all array elements in reverse order order == ' G ' we compute next greater elements of every element order == ' S ' we compute right smaller element of every element ; Keep removing top element from S while the top element is smaller then or equal to arr [ i ] ( if Key is G ) element is greater then or equal to arr [ i ] ( if order is S ) ; store the next greater element of current element ; If all elements in S were smaller than arr [ i ] ; Push this element ; Function to find Right smaller element of next greater element ; stores indexes of next greater elements ; stores indexes of right smaller elements ; Find next greater element Here G indicate next greater element ; Find right smaller element using same function nextGreater ( ) Here S indicate right smaller elements ; If NG [ i ] = = - 1 then there is no smaller element on right side . We can find Right smaller of next greater by arr [ RS [ NG [ i ] ] ] ; Driver program
def nextGreater ( arr , n , next , order ) : NEW_LINE INDENT S = [ ] NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT while ( S != [ ] and ( arr [ S [ len ( S ) - 1 ] ] <= arr [ i ] if ( order == ' G ' ) else arr [ S [ len ( S ) - 1 ] ] >= arr [ i ] ) ) : NEW_LINE INDENT S . pop ( ) NEW_LINE DEDENT if ( S != [ ] ) : NEW_LINE INDENT next [ i ] = S [ len ( S ) - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT next [ i ] = - 1 NEW_LINE DEDENT S . append ( i ) NEW_LINE DEDENT DEDENT def nextSmallerOfNextGreater ( arr , n ) : NEW_LINE INDENT NG = [ None ] * n NEW_LINE RS = [ None ] * n NEW_LINE nextGreater ( arr , n , NG , ' G ' ) NEW_LINE nextGreater ( arr , n , RS , ' S ' ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( NG [ i ] != - 1 and RS [ NG [ i ] ] != - 1 ) : NEW_LINE INDENT print ( arr [ RS [ NG [ i ] ] ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 1 , 9 , 2 , 5 , 1 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE nextSmallerOfNextGreater ( arr , n ) NEW_LINE DEDENT
Convert Ternary Expression to a Binary Tree | Class to define a node structure of the tree ; Function to convert ternary expression to a Binary tree It returns the root node of the tree ; Base case ; Create a new node object for the expression at ith index ; Move ahead in str ; if current character of ternary expression is ' ? ' then we add next character as a left child of current node ; else we have to add it as a right child of current node expression [ 0 ] = = ': ; Function to print the tree in a pre - order traversal pattern ; Driver Code
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def convert_expression ( expression , i ) : NEW_LINE INDENT if i >= len ( expression ) : NEW_LINE INDENT return None NEW_LINE DEDENT root = Node ( expression [ i ] ) NEW_LINE i += 1 NEW_LINE if ( i < len ( expression ) and expression [ i ] == " ? " ) : NEW_LINE INDENT root . left = convert_expression ( expression , i + 1 ) NEW_LINE DEDENT elif i < len ( expression ) : NEW_LINE INDENT root . right = convert_expression ( expression , i + 1 ) NEW_LINE DEDENT return root NEW_LINE DEDENT def print_tree ( root ) : NEW_LINE INDENT if not root : NEW_LINE INDENT return NEW_LINE DEDENT print ( root . data , end = ' ▁ ' ) NEW_LINE print_tree ( root . left ) NEW_LINE print_tree ( root . right ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string_expression = " a ? b ? c : d : e " NEW_LINE root_node = convert_expression ( string_expression , 0 ) NEW_LINE print_tree ( root_node ) NEW_LINE DEDENT
Count natural numbers whose all permutation are greater than that number | Return the count of the number having all permutation greater than or equal to the number . ; Pushing 1 to 9 because all number from 1 to 9 have this property . ; take a number from stack and add a digit smaller than last digit of it . ; Driver Code
def countNumber ( n ) : NEW_LINE INDENT result = 0 NEW_LINE s = [ ] NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT if ( i <= n ) : NEW_LINE INDENT s . append ( i ) NEW_LINE result += 1 NEW_LINE DEDENT while len ( s ) != 0 : NEW_LINE INDENT tp = s [ - 1 ] NEW_LINE s . pop ( ) NEW_LINE for j in range ( tp % 10 , 10 ) : NEW_LINE INDENT x = tp * 10 + j NEW_LINE if ( x <= n ) : NEW_LINE INDENT s . append ( x ) NEW_LINE result += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 15 NEW_LINE print ( countNumber ( n ) ) NEW_LINE DEDENT
Delete consecutive same words in a sequence | Function to find the size of manipulated sequence ; Start traversing the sequence ; Compare the current string with next one Erase both if equal ; Erase function delete the element and also shifts other element that 's why i is not updated ; Update i , as to check from previous element again ; Reduce sequence size ; Increment i , if not equal ; Return modified size ; Driver Code
def removeConsecutiveSame ( v ) : NEW_LINE INDENT n = len ( v ) NEW_LINE i = 0 NEW_LINE while ( i < n - 1 ) : NEW_LINE INDENT if ( ( i + 1 ) < len ( v ) ) and ( v [ i ] == v [ i + 1 ] ) : NEW_LINE INDENT v = v [ : i ] NEW_LINE v = v [ : i ] NEW_LINE if ( i > 0 ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT n = n - 2 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT return len ( v [ : i - 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT v = [ " tom " , " jerry " , " jerry " , " tom " ] NEW_LINE print ( removeConsecutiveSame ( v ) ) NEW_LINE DEDENT
Delete consecutive same words in a sequence | Function to find the size of manipulated sequence ; Start traversing the sequence ; Push the current string if the stack is empty ; compare the current string with stack top if equal , pop the top ; Otherwise push the current string ; Return stack size ; Driver code
def removeConsecutiveSame ( v ) : NEW_LINE INDENT st = [ ] NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT if ( len ( st ) == 0 ) : NEW_LINE INDENT st . append ( v [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT Str = st [ - 1 ] NEW_LINE if ( Str == v [ i ] ) : NEW_LINE INDENT st . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT st . append ( v [ i ] ) NEW_LINE DEDENT DEDENT DEDENT return len ( st ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = [ " ab " , " aa " , " aa " , " bcd " , " ab " ] NEW_LINE print ( removeConsecutiveSame ( V ) ) NEW_LINE DEDENT
Decode a string recursively encoded as count followed by substring | Returns decoded string for ' str ' ; Traversing the string ; If number , convert it into number and push it into integerstack . ; If closing bracket ' ] ' , pop elemment until ' [ ' opening bracket is not found in the character stack . ; Repeating the popped string ' temo ' count number of times . ; Push it in the character stack . ; If ' [ ' opening bracket , push it into character stack . ; Pop all the elmenet , make a string and return . ; Driven code
def decode ( Str ) : NEW_LINE INDENT integerstack = [ ] NEW_LINE stringstack = [ ] NEW_LINE temp = " " NEW_LINE result = " " NEW_LINE i = 0 NEW_LINE while i < len ( Str ) : NEW_LINE INDENT count = 0 NEW_LINE if ( Str [ i ] >= '0' and Str [ i ] <= '9' ) : NEW_LINE INDENT while ( Str [ i ] >= '0' and Str [ i ] <= '9' ) : NEW_LINE INDENT count = count * 10 + ord ( Str [ i ] ) - ord ( '0' ) NEW_LINE i += 1 NEW_LINE DEDENT i -= 1 NEW_LINE integerstack . append ( count ) NEW_LINE DEDENT elif ( Str [ i ] == ' ] ' ) : NEW_LINE INDENT temp = " " NEW_LINE count = 0 NEW_LINE if ( len ( integerstack ) != 0 ) : NEW_LINE INDENT count = integerstack [ - 1 ] NEW_LINE integerstack . pop ( ) NEW_LINE DEDENT while ( len ( stringstack ) != 0 and stringstack [ - 1 ] != ' [ ' ) : NEW_LINE INDENT temp = stringstack [ - 1 ] + temp NEW_LINE stringstack . pop ( ) NEW_LINE DEDENT if ( len ( stringstack ) != 0 and stringstack [ - 1 ] == ' [ ' ) : NEW_LINE INDENT stringstack . pop ( ) NEW_LINE DEDENT for j in range ( count ) : NEW_LINE INDENT result = result + temp NEW_LINE DEDENT for j in range ( len ( result ) ) : NEW_LINE INDENT stringstack . append ( result [ j ] ) NEW_LINE DEDENT result = " " NEW_LINE DEDENT elif ( Str [ i ] == ' [ ' ) : NEW_LINE INDENT if ( Str [ i - 1 ] >= '0' and Str [ i - 1 ] <= '9' ) : NEW_LINE INDENT stringstack . append ( Str [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT stringstack . append ( Str [ i ] ) NEW_LINE integerstack . append ( 1 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT stringstack . append ( Str [ i ] ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT while len ( stringstack ) != 0 : NEW_LINE INDENT result = stringstack [ - 1 ] + result NEW_LINE stringstack . pop ( ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Str = "3 [ b2 [ ca ] ] " NEW_LINE print ( decode ( Str ) ) NEW_LINE DEDENT
Iterative method to find ancestors of a given binary tree | A class to create a new tree node ; Iterative Function to print all ancestors of a given key ; Create a stack to hold ancestors ; Traverse the complete tree in postorder way till we find the key ; Traverse the left side . While traversing , push the nodes into the stack so that their right subtrees can be traversed later ; push current node ; move to next node ; If the node whose ancestors are to be printed is found , then break the while loop . ; Check if right sub - tree exists for the node at top If not then pop that node because we don 't need this node any more. ; If the popped node is right child of top , then remove the top as well . Left child of the top must have processed before . ; if stack is not empty then simply set the root as right child of top and start traversing right sub - tree . ; If stack is not empty , print contents of stack Here assumption is that the key is there in tree ; Driver code ; Let us construct a binary tree
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def printAncestors ( root , key ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT st = [ ] NEW_LINE while ( 1 ) : NEW_LINE INDENT while ( root and root . data != key ) : NEW_LINE INDENT st . append ( root ) NEW_LINE root = root . left NEW_LINE DEDENT if ( root and root . data == key ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( st [ - 1 ] . right == None ) : NEW_LINE INDENT root = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE while ( len ( st ) != 0 and st [ - 1 ] . right == root ) : NEW_LINE INDENT root = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE DEDENT DEDENT root = None if len ( st ) == 0 else st [ - 1 ] . right NEW_LINE DEDENT while ( len ( st ) != 0 ) : NEW_LINE INDENT print ( st [ - 1 ] . data , end = " ▁ " ) NEW_LINE st . pop ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 7 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 8 ) NEW_LINE root . right . right = newNode ( 9 ) NEW_LINE root . left . left . left = newNode ( 4 ) NEW_LINE root . left . right . right = newNode ( 6 ) NEW_LINE root . right . right . left = newNode ( 10 ) NEW_LINE key = 6 NEW_LINE printAncestors ( root , key ) NEW_LINE DEDENT
Tracking current Maximum Element in a Stack | Python3 program to keep track of maximum element in a stack ; main stack ; tack to keep track of max element ; If current element is greater than the top element of track stack , append the current element to track stack otherwise append the element at top of track stack again into it . ; Driver Code
class StackWithMax : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . mainStack = [ ] NEW_LINE self . trackStack = [ ] NEW_LINE DEDENT def push ( self , x ) : NEW_LINE INDENT self . mainStack . append ( x ) NEW_LINE if ( len ( self . mainStack ) == 1 ) : NEW_LINE INDENT self . trackStack . append ( x ) NEW_LINE return NEW_LINE DEDENT if ( x > self . trackStack [ - 1 ] ) : NEW_LINE INDENT self . trackStack . append ( x ) NEW_LINE DEDENT else : NEW_LINE INDENT self . trackStack . append ( self . trackStack [ - 1 ] ) NEW_LINE DEDENT DEDENT def getMax ( self ) : NEW_LINE INDENT return self . trackStack [ - 1 ] NEW_LINE DEDENT def pop ( self ) : NEW_LINE INDENT self . mainStack . pop ( ) NEW_LINE self . trackStack . pop ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = StackWithMax ( ) NEW_LINE s . push ( 20 ) NEW_LINE print ( s . getMax ( ) ) NEW_LINE s . push ( 10 ) NEW_LINE print ( s . getMax ( ) ) NEW_LINE s . push ( 50 ) NEW_LINE print ( s . getMax ( ) ) NEW_LINE DEDENT
Reverse a number using stack | Stack to maintain order of digits ; Function to push digits into stack ; Function to reverse the number ; Function call to push number 's digits to stack ; Popping the digits and forming the reversed number ; Return the reversed number formed ; Driver Code ; Function call to reverse number
st = [ ] ; NEW_LINE def push_digits ( number ) : NEW_LINE INDENT while ( number != 0 ) : NEW_LINE INDENT st . append ( number % 10 ) ; NEW_LINE number = int ( number / 10 ) ; NEW_LINE DEDENT DEDENT def reverse_number ( number ) : NEW_LINE INDENT push_digits ( number ) ; NEW_LINE reverse = 0 ; NEW_LINE i = 1 ; NEW_LINE while ( len ( st ) > 0 ) : NEW_LINE INDENT reverse = reverse + ( st [ len ( st ) - 1 ] * i ) ; NEW_LINE st . pop ( ) ; NEW_LINE i = i * 10 ; NEW_LINE DEDENT return reverse ; NEW_LINE DEDENT number = 39997 ; NEW_LINE print ( reverse_number ( number ) ) ; NEW_LINE
Flip Binary Tree | A binary tree node ; method to flip the binary tree ; Recursively call the same method ; Rearranging main root Node after returning from recursive call ; Iterative method to do the level order traversal line by line ; Base Case ; Create an empty queue for level order traversal ; Enqueue root and initialize height ; nodeCount ( queue size ) indicates number of nodes at current level ; Dequeue all nodes of current level and Enqueue all nodes of next level ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . right = None NEW_LINE self . left = None NEW_LINE DEDENT DEDENT def flipBinaryTree ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return root NEW_LINE DEDENT if ( root . left is None and root . right is None ) : NEW_LINE INDENT return root NEW_LINE DEDENT flippedRoot = flipBinaryTree ( root . left ) NEW_LINE root . left . left = root . right NEW_LINE root . left . right = root NEW_LINE root . left = root . right = None NEW_LINE return flippedRoot NEW_LINE DEDENT def printLevelOrder ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT from Queue import Queue NEW_LINE q = Queue ( ) NEW_LINE q . put ( root ) NEW_LINE while ( True ) : NEW_LINE INDENT nodeCount = q . qsize ( ) NEW_LINE if nodeCount == 0 : NEW_LINE INDENT break NEW_LINE DEDENT while nodeCount > 0 : NEW_LINE INDENT node = q . get ( ) NEW_LINE print node . data , NEW_LINE if node . left is not None : NEW_LINE INDENT q . put ( node . left ) NEW_LINE DEDENT if node . right is not None : NEW_LINE INDENT q . put ( node . right ) NEW_LINE DEDENT nodeCount -= 1 NEW_LINE DEDENT print NEW_LINE DEDENT DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . right . left = Node ( 4 ) NEW_LINE root . right . right = Node ( 5 ) NEW_LINE print " Level ▁ order ▁ traversal ▁ of ▁ given ▁ tree " NEW_LINE printLevelOrder ( root ) NEW_LINE root = flipBinaryTree ( root ) NEW_LINE print " NEW_LINE Level order traversal of the flipped tree " NEW_LINE printLevelOrder ( root ) NEW_LINE
Check if stack elements are pairwise consecutive | Function to check if elements are pairwise consecutive in stack ; Transfer elements of s to aux . ; Traverse aux and see if elements are pairwise consecutive or not . We also need to make sure that original content is retained . ; Fetch current top two elements of aux and check if they are consecutive . ; append the elements to original stack . ; Driver Code
def pairWiseConsecutive ( s ) : NEW_LINE INDENT aux = [ ] NEW_LINE while ( len ( s ) != 0 ) : NEW_LINE INDENT aux . append ( s [ - 1 ] ) NEW_LINE s . pop ( ) NEW_LINE DEDENT result = True NEW_LINE while ( len ( aux ) > 1 ) : NEW_LINE INDENT x = aux [ - 1 ] NEW_LINE aux . pop ( ) NEW_LINE y = aux [ - 1 ] NEW_LINE aux . pop ( ) NEW_LINE if ( abs ( x - y ) != 1 ) : NEW_LINE INDENT result = False NEW_LINE DEDENT s . append ( x ) NEW_LINE s . append ( y ) NEW_LINE DEDENT if ( len ( aux ) == 1 ) : NEW_LINE INDENT s . append ( aux [ - 1 ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = [ ] NEW_LINE s . append ( 4 ) NEW_LINE s . append ( 5 ) NEW_LINE s . append ( - 2 ) NEW_LINE s . append ( - 3 ) NEW_LINE s . append ( 11 ) NEW_LINE s . append ( 10 ) NEW_LINE s . append ( 5 ) NEW_LINE s . append ( 6 ) NEW_LINE s . append ( 20 ) NEW_LINE if ( pairWiseConsecutive ( s ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT print ( " Stack ▁ content ▁ ( from ▁ top ) " , " after ▁ function ▁ call " ) NEW_LINE while ( len ( s ) != 0 ) : NEW_LINE INDENT print ( s [ - 1 ] , end = " ▁ " ) NEW_LINE s . pop ( ) NEW_LINE DEDENT DEDENT
Remove brackets from an algebraic string containing + and | Function to simplify the String ; resultant String of max Length equal to Length of input String ; create empty stack ; If top is 1 , flip the operator ; If top is 0 , append the same operator ; x is opposite to the top of stack ; append value equal to top of the stack ; If closing parentheses pop the stack once ; copy the character to the result ; Driver Code
def simplify ( Str ) : NEW_LINE INDENT Len = len ( Str ) NEW_LINE res = [ None ] * Len NEW_LINE index = 0 NEW_LINE i = 0 NEW_LINE s = [ ] NEW_LINE s . append ( 0 ) NEW_LINE while ( i < Len ) : NEW_LINE INDENT if ( Str [ i ] == ' + ' ) : NEW_LINE INDENT if ( s [ - 1 ] == 1 ) : NEW_LINE INDENT res [ index ] = ' - ' NEW_LINE index += 1 NEW_LINE DEDENT if ( s [ - 1 ] == 0 ) : NEW_LINE INDENT res [ index ] = ' + ' NEW_LINE index += 1 NEW_LINE DEDENT DEDENT elif ( Str [ i ] == ' - ' ) : NEW_LINE INDENT if ( s [ - 1 ] == 1 ) : NEW_LINE INDENT res [ index ] = ' + ' NEW_LINE index += 1 NEW_LINE DEDENT elif ( s [ - 1 ] == 0 ) : NEW_LINE INDENT res [ index ] = ' - ' NEW_LINE index += 1 NEW_LINE DEDENT DEDENT elif ( Str [ i ] == ' ( ' and i > 0 ) : NEW_LINE INDENT if ( Str [ i - 1 ] == ' - ' ) : NEW_LINE INDENT x = 0 if ( s [ - 1 ] == 1 ) else 1 NEW_LINE s . append ( x ) NEW_LINE DEDENT elif ( Str [ i - 1 ] == ' + ' ) : NEW_LINE INDENT s . append ( s [ - 1 ] ) NEW_LINE DEDENT DEDENT elif ( Str [ i ] == ' ) ' ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT res [ index ] = Str [ i ] NEW_LINE index += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " a - ( b + c ) " NEW_LINE s2 = " a - ( b - c - ( d + e ) ) - f " NEW_LINE r1 = simplify ( s1 ) NEW_LINE for i in r1 : NEW_LINE INDENT if i != None : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( ) NEW_LINE r2 = simplify ( s2 ) NEW_LINE for i in r2 : NEW_LINE INDENT if i != None : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT
Growable array based stack | constant amount at which stack is increased ; top of the stack ; length of stack ; function to create new stack ; allocate memory for new stack ; copying the content of old stack ; re - sizing the length ; function to push new element ; if stack is full , create new one ; insert element at top of the stack ; function to pop an element ; function to display ; if top is - 1 , that means stack is empty ; Driver Code ; creating initial stack ; pushing element to top of stack ; pushing more element when stack is full ; pushing more element so that stack can grow
BOUND = 4 NEW_LINE top = - 1 ; NEW_LINE a = [ ] NEW_LINE length = 0 ; NEW_LINE def create_new ( ) : NEW_LINE INDENT global length ; NEW_LINE new_a = [ 0 for i in range ( length + BOUND ) ] ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT new_a [ i ] = a [ i ] ; NEW_LINE DEDENT length += BOUND ; NEW_LINE return new_a NEW_LINE DEDENT def push ( element ) : NEW_LINE INDENT global top , a NEW_LINE if ( top == length - 1 ) : NEW_LINE INDENT a = create_new ( ) ; NEW_LINE DEDENT top += 1 NEW_LINE a [ top ] = element ; NEW_LINE return a ; NEW_LINE DEDENT def pop ( ) : NEW_LINE INDENT global top NEW_LINE top -= 1 ; NEW_LINE DEDENT def display ( ) : NEW_LINE INDENT global top NEW_LINE if ( top == - 1 ) : NEW_LINE INDENT print ( " Stack ▁ is ▁ Empty " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Stack : ▁ " , end = ' ' ) NEW_LINE for i in range ( top + 1 ) : NEW_LINE INDENT print ( a [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = create_new ( ) ; NEW_LINE push ( 1 ) ; NEW_LINE push ( 2 ) ; NEW_LINE push ( 3 ) ; NEW_LINE push ( 4 ) ; NEW_LINE display ( ) ; NEW_LINE push ( 5 ) ; NEW_LINE push ( 6 ) ; NEW_LINE display ( ) ; NEW_LINE push ( 7 ) ; NEW_LINE push ( 8 ) ; NEW_LINE display ( ) ; NEW_LINE push ( 9 ) ; NEW_LINE display ( ) ; NEW_LINE DEDENT
Range Queries for Longest Correct Bracket Subsequence Set | 2 | Function for precomputation ; Create a stack and push - 1 as initial index to it . ; Traverse all characters of given String ; If opening bracket , push index of it ; If closing bracket , i . e . , str [ i ] = ') ; If closing bracket , i . e . , str [ i ] = ' ) ' && stack is not empty then mark both " open ▁ & ▁ close " bracket indexs as 1 . Pop the previous opening bracket 's index ; If stack is empty . ; Function return output of each query in O ( 1 ) ; Driver code
def constructBlanceArray ( BOP , BCP , str , n ) : NEW_LINE INDENT stk = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == ' ( ' ) : NEW_LINE INDENT stk . append ( i ) ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( len ( stk ) != 0 ) : NEW_LINE INDENT BCP [ i ] = 1 ; NEW_LINE BOP [ stk [ - 1 ] ] = 1 ; NEW_LINE stk . pop ( ) ; NEW_LINE DEDENT else : NEW_LINE INDENT BCP [ i ] = 0 ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT BCP [ i ] += BCP [ i - 1 ] ; NEW_LINE BOP [ i ] += BOP [ i - 1 ] ; NEW_LINE DEDENT DEDENT def query ( BOP , BCP , s , e ) : NEW_LINE INDENT if ( BOP [ s - 1 ] == BOP [ s ] ) : NEW_LINE INDENT return ( BCP [ e ] - BOP [ s ] ) * 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT return ( BCP [ e ] - BOP [ s ] + 1 ) * 2 ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT string = " ( ) ) ( ( ) ) ( ( ) ) ( " ; NEW_LINE n = len ( string ) NEW_LINE BCP = [ 0 for i in range ( n + 1 ) ] ; NEW_LINE BOP = [ 0 for i in range ( n + 1 ) ] ; NEW_LINE constructBlanceArray ( BOP , BCP , string , n ) ; NEW_LINE startIndex = 5 NEW_LINE endIndex = 11 ; NEW_LINE print ( " Maximum ▁ Length ▁ Correct ▁ " + " Bracket ▁ Subsequence ▁ between ▁ " + str ( startIndex ) + " ▁ and ▁ " + str ( endIndex ) + " ▁ = ▁ " + str ( query ( BOP , BCP , startIndex , endIndex ) ) ) ; NEW_LINE startIndex = 4 ; NEW_LINE endIndex = 5 ; NEW_LINE print ( " Maximum ▁ Length ▁ Correct ▁ " + " Bracket ▁ Subsequence ▁ between ▁ " + str ( startIndex ) + " ▁ and ▁ " + str ( endIndex ) + " ▁ = ▁ " + str ( query ( BOP , BCP , startIndex , endIndex ) ) ) NEW_LINE startIndex = 1 ; NEW_LINE endIndex = 5 ; NEW_LINE print ( " Maximum ▁ Length ▁ Correct ▁ " + " Bracket ▁ Subsequence ▁ between ▁ " + str ( startIndex ) + " ▁ and ▁ " + str ( endIndex ) + " ▁ = ▁ " + str ( query ( BOP , BCP , startIndex , endIndex ) ) ) ; NEW_LINE DEDENT
HeapSort | To heapify subtree rooted at index i . n is size of heap ; Initialize largest as root ; left = 2 * i + 1 ; right = 2 * i + 2 ; See if left child of root exists and is greater than root ; See if right child of root exists and is greater than root ; Change root , if needed ; Heapify the root . ; The main function to sort an array of given size ; Build a maxheap . ; One by one extract elements ; swap ; call max heapify on the reduced heap ; Driver code
def heapify ( arr , n , i ) : NEW_LINE INDENT largest = i NEW_LINE l = 2 * i + 1 NEW_LINE r = 2 * i + 2 NEW_LINE if l < n and arr [ largest ] < arr [ l ] : NEW_LINE INDENT largest = l NEW_LINE DEDENT if r < n and arr [ largest ] < arr [ r ] : NEW_LINE INDENT largest = r NEW_LINE DEDENT if largest != i : NEW_LINE INDENT arr [ i ] , arr [ largest ] = arr [ largest ] , arr [ i ] NEW_LINE heapify ( arr , n , largest ) NEW_LINE DEDENT DEDENT def heapSort ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE for i in range ( n // 2 - 1 , - 1 , - 1 ) : NEW_LINE INDENT heapify ( arr , n , i ) NEW_LINE DEDENT for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT arr [ i ] , arr [ 0 ] = arr [ 0 ] , arr [ i ] NEW_LINE heapify ( arr , i , 0 ) NEW_LINE DEDENT DEDENT arr = [ 12 , 11 , 13 , 5 , 6 , 7 ] NEW_LINE heapSort ( arr ) NEW_LINE n = len ( arr ) NEW_LINE print ( " Sorted ▁ array ▁ is " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( " % d " % arr [ i ] ) , NEW_LINE DEDENT
Iterative HeapSort | function build Max Heap where value of each child is always smaller than value of their parent ; if child is bigger than parent ; swap child and parent until parent is smaller ; swap value of first indexed with last indexed ; maintaining heap property after each swapping ; if left child is smaller than right child point index variable to right child ; if parent is smaller than child then swapping parent with child having higher value ; Driver Code
def buildMaxHeap ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if arr [ i ] > arr [ int ( ( i - 1 ) / 2 ) ] : NEW_LINE INDENT j = i NEW_LINE while arr [ j ] > arr [ int ( ( j - 1 ) / 2 ) ] : NEW_LINE INDENT ( arr [ j ] , arr [ int ( ( j - 1 ) / 2 ) ] ) = ( arr [ int ( ( j - 1 ) / 2 ) ] , arr [ j ] ) NEW_LINE j = int ( ( j - 1 ) / 2 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def heapSort ( arr , n ) : NEW_LINE INDENT buildMaxHeap ( arr , n ) NEW_LINE for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT arr [ 0 ] , arr [ i ] = arr [ i ] , arr [ 0 ] NEW_LINE j , index = 0 , 0 NEW_LINE while True : NEW_LINE INDENT index = 2 * j + 1 NEW_LINE if ( index < ( i - 1 ) and arr [ index ] < arr [ index + 1 ] ) : NEW_LINE INDENT index += 1 NEW_LINE DEDENT if index < i and arr [ j ] < arr [ index ] : NEW_LINE INDENT arr [ j ] , arr [ index ] = arr [ index ] , arr [ j ] NEW_LINE DEDENT j = index NEW_LINE if index >= i : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 20 , 15 , 17 , 9 , 21 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Given ▁ array : ▁ " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE heapSort ( arr , n ) NEW_LINE print ( " Sorted ▁ array : ▁ " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT
Flip Binary Tree | Python3 program to flip a binary tree ; A binary tree node structure ; method to flip the binary tree ; Initialization of pointers ; Iterate through all left nodes ; Swapping nodes now , need temp to keep the previous right child Making prev ' s ▁ right ▁ as ▁ curr ' s left child ; Storing curr 's right child ; Making prev as curr 's right child ; Iterative method to do level order traversal line by line ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize height ; nodeCount ( queue size ) indicates number of nodes at current level . ; Dequeue all nodes of current level and Enqueue all nodes of next level ; Driver code
from collections import deque NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def flipBinaryTree ( root ) : NEW_LINE INDENT curr = root NEW_LINE next = None NEW_LINE temp = None NEW_LINE prev = None NEW_LINE while ( curr ) : NEW_LINE INDENT next = curr . left NEW_LINE curr . left = temp NEW_LINE temp = curr . right NEW_LINE curr . right = prev NEW_LINE prev = curr NEW_LINE curr = next NEW_LINE DEDENT return prev NEW_LINE DEDENT def printLevelOrder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = deque ( ) NEW_LINE q . append ( root ) NEW_LINE while ( 1 ) : NEW_LINE INDENT nodeCount = len ( q ) NEW_LINE if ( nodeCount == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT while ( nodeCount > 0 ) : NEW_LINE INDENT node = q . popleft ( ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE if ( node . left != None ) : NEW_LINE INDENT q . append ( node . left ) NEW_LINE DEDENT if ( node . right != None ) : NEW_LINE INDENT q . append ( node . right ) NEW_LINE DEDENT nodeCount -= 1 NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . right . left = Node ( 4 ) NEW_LINE root . right . right = Node ( 5 ) NEW_LINE print ( " Level ▁ order ▁ traversal ▁ of ▁ given ▁ tree " ) NEW_LINE printLevelOrder ( root ) NEW_LINE root = flipBinaryTree ( root ) NEW_LINE print ( " Level order traversal of the flipped " ▁ " tree " ) NEW_LINE printLevelOrder ( root ) NEW_LINE DEDENT
Foldable Binary Trees | Utility function to create a new tree node ; Returns true if the given tree can be folded ; A utility function that checks if trees with roots as n1 and n2 are mirror of each other ; If both left and right subtrees are NULL , then return true ; If one of the trees is NULL and other is not , then return false ; Otherwise check if left and right subtrees are mirrors of their counterparts ; Driver code ; The constructed binary tree is 1 / \ 2 3 \ / 4 5
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def IsFoldable ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return True NEW_LINE DEDENT return IsFoldableUtil ( root . left , root . right ) NEW_LINE DEDENT def IsFoldableUtil ( n1 , n2 ) : NEW_LINE INDENT if n1 == None and n2 == None : NEW_LINE INDENT return True NEW_LINE DEDENT if n1 == None or n2 == None : NEW_LINE INDENT return False NEW_LINE DEDENT d1 = IsFoldableUtil ( n1 . left , n2 . right ) NEW_LINE d2 = IsFoldableUtil ( n1 . right , n2 . left ) NEW_LINE return d1 and d2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . right = newNode ( 4 ) NEW_LINE root . right . left = newNode ( 5 ) NEW_LINE if IsFoldable ( root ) : NEW_LINE INDENT print ( " Tree ▁ is ▁ foldable " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Tree ▁ is ▁ not ▁ foldable " ) NEW_LINE DEDENT DEDENT
Check for Children Sum Property in a Binary Tree | returns 1 if children sum property holds for the given node and both of its children ; left_data is left child data and right_data is for right child data ; If node is None or it 's a leaf node then return true ; If left child is not present then 0 is used as data of left child ; If right child is not present then 0 is used as data of right child ; if the node and both of its children satisfy the property return 1 else 0 ; Helper class that allocates a new node with the given data and None left and right pointers . ; Driver Code
def isSumProperty ( node ) : NEW_LINE INDENT left_data = 0 NEW_LINE right_data = 0 NEW_LINE if ( node == None or ( node . left == None and node . right == None ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( node . left != None ) : NEW_LINE INDENT left_data = node . left . data NEW_LINE DEDENT if ( node . right != None ) : NEW_LINE INDENT right_data = node . right . data NEW_LINE DEDENT if ( ( node . data == left_data + right_data ) and isSumProperty ( node . left ) and isSumProperty ( node . right ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT DEDENT class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 8 ) NEW_LINE root . right = newNode ( 2 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . right = newNode ( 2 ) NEW_LINE if ( isSumProperty ( root ) ) : NEW_LINE INDENT print ( " The ▁ given ▁ tree ▁ satisfies ▁ the " , " children ▁ sum ▁ property ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ given ▁ tree ▁ does ▁ not ▁ satisfy " , " the ▁ children ▁ sum ▁ property ▁ " ) NEW_LINE DEDENT DEDENT
How to check if a given array represents a Binary Heap ? | Returns true if arr [ i . . n - 1 ] represents a max - heap ; If a leaf node ; If an internal node and is greater than its children , and same is recursively true for the children ; Driver Code
def isHeap ( arr , i , n ) : NEW_LINE INDENT if i >= int ( ( n - 2 ) / 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( arr [ i ] >= arr [ 2 * i + 1 ] and arr [ i ] >= arr [ 2 * i + 2 ] and isHeap ( arr , 2 * i + 1 , n ) and isHeap ( arr , 2 * i + 2 , n ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 90 , 15 , 10 , 7 , 12 , 2 , 7 , 3 ] NEW_LINE n = len ( arr ) - 1 NEW_LINE if isHeap ( arr , 0 , n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
How to check if a given array represents a Binary Heap ? | Returns true if arr [ i . . n - 1 ] represents a max - heap ; Start from root and go till the last internal node ; If left child is greater , return false ; If right child is greater , return false ; Driver Code
def isHeap ( arr , n ) : NEW_LINE INDENT for i in range ( int ( ( n - 2 ) / 2 ) + 1 ) : NEW_LINE INDENT if arr [ 2 * i + 1 ] > arr [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT if ( 2 * i + 2 < n and arr [ 2 * i + 2 ] > arr [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 90 , 15 , 10 , 7 , 12 , 2 , 7 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE if isHeap ( arr , n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Connect n ropes with minimum cost | Python3 program to connect n ropes with minimum cost ; Create a priority queue out of the given list ; Initializ result ; While size of priority queue is more than 1 ; Extract shortest two ropes from arr ; Connect the ropes : update result and insert the new rope to arr ; Driver code
import heapq NEW_LINE def minCost ( arr , n ) : NEW_LINE INDENT heapq . heapify ( arr ) NEW_LINE res = 0 NEW_LINE while ( len ( arr ) > 1 ) : NEW_LINE INDENT first = heapq . heappop ( arr ) NEW_LINE second = heapq . heappop ( arr ) NEW_LINE res += first + second NEW_LINE heapq . heappush ( arr , first + second ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT lengths = [ 4 , 3 , 2 , 6 ] NEW_LINE size = len ( lengths ) NEW_LINE print ( " Total ▁ cost ▁ for ▁ connecting ▁ ropes ▁ is ▁ " + str ( minCost ( lengths , size ) ) ) NEW_LINE DEDENT
Smallest Derangement of Sequence | Python3 program to generate smallest derangement using priority queue . ; Generate Sequence and insert into a priority queue . ; Generate Least Derangement ; Print Derangement ; Driver code
def generate_derangement ( N ) : NEW_LINE INDENT S = [ i for i in range ( N + 1 ) ] NEW_LINE PQ = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT PQ . append ( S [ i ] ) NEW_LINE DEDENT D = [ 0 ] * ( N + 1 ) NEW_LINE PQ . sort ( ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT PQ . sort ( ) NEW_LINE d = PQ [ 0 ] NEW_LINE del PQ [ 0 ] NEW_LINE if ( d != S [ i ] ) or ( i == N ) : NEW_LINE INDENT D [ i ] = d NEW_LINE DEDENT else : NEW_LINE INDENT PQ . sort ( ) NEW_LINE D [ i ] = PQ [ 0 ] NEW_LINE del PQ [ 0 ] NEW_LINE PQ . append ( d ) NEW_LINE DEDENT DEDENT if D [ N ] == S [ N ] : NEW_LINE INDENT t = D [ N - 1 ] NEW_LINE D [ N - 1 ] = D [ N ] NEW_LINE D [ N ] = t NEW_LINE DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( D [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT generate_derangement ( 10 ) NEW_LINE
Smallest Derangement of Sequence | Efficient Python3 program to find smallest derangement . ; Generate Sequence S ; Generate Derangement ; Only if i is odd Swap S [ N - 1 ] and S [ N ] ; Print Derangement ; Driver Code
def generate_derangement ( N ) : NEW_LINE INDENT S = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT S [ i ] = i NEW_LINE DEDENT D = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( 1 , N + 1 , 2 ) : NEW_LINE INDENT if i == N : NEW_LINE INDENT D [ N ] = S [ N - 1 ] NEW_LINE D [ N - 1 ] = S [ N ] NEW_LINE DEDENT else : NEW_LINE INDENT D [ i ] = i + 1 NEW_LINE D [ i + 1 ] = i NEW_LINE DEDENT DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( D [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT generate_derangement ( 10 ) NEW_LINE DEDENT
Largest Derangement of a Sequence | Python3 program to find the largest derangement ; Stores result ; Insert all elements into a priority queue ; Fill Up res [ ] from left to right ; New Element poped equals the element in original sequence . Get the next largest element ; If given sequence is in descending order then we need to swap last two elements again ; Driver code
def printLargest ( seq , N ) : NEW_LINE INDENT res = [ 0 ] * N NEW_LINE pq = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT pq . append ( seq [ i ] ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT pq . sort ( ) NEW_LINE pq . reverse ( ) NEW_LINE d = pq [ 0 ] NEW_LINE del pq [ 0 ] NEW_LINE if ( d != seq [ i ] or i == N - 1 ) : NEW_LINE INDENT res [ i ] = d NEW_LINE DEDENT else : NEW_LINE INDENT res [ i ] = pq [ 0 ] NEW_LINE del pq [ 0 ] NEW_LINE pq . append ( d ) NEW_LINE DEDENT DEDENT if ( res [ N - 1 ] == seq [ N - 1 ] ) : NEW_LINE INDENT res [ N - 1 ] = res [ N - 2 ] NEW_LINE res [ N - 2 ] = seq [ N - 1 ] NEW_LINE DEDENT print ( " Largest ▁ Derangement " ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( res [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT seq = [ 92 , 3 , 52 , 13 , 2 , 31 , 1 ] NEW_LINE n = len ( seq ) NEW_LINE printLargest ( seq , n ) NEW_LINE
Program to calculate Profit Or Loss | Function to calculate Profit . ; Function to calculate Loss . ; Driver code
def Profit ( costPrice , sellingPrice ) : NEW_LINE INDENT profit = ( sellingPrice - costPrice ) NEW_LINE return profit NEW_LINE DEDENT def Loss ( costPrice , sellingPrice ) : NEW_LINE INDENT Loss = ( costPrice - sellingPrice ) NEW_LINE return Loss NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT costPrice , sellingPrice = 1500 , 2000 NEW_LINE if sellingPrice == costPrice : NEW_LINE INDENT print ( " No ▁ profit ▁ nor ▁ Loss " ) NEW_LINE DEDENT elif sellingPrice > costPrice : NEW_LINE INDENT print ( Profit ( costPrice , sellingPrice ) , " Profit " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( Loss ( costPrice , sellingPrice ) , " Loss " ) NEW_LINE DEDENT DEDENT
Find the Next perfect square greater than a given number | Python3 implementation of above approach ; Function to find the next perfect square ; Driver Code
import math NEW_LINE def nextPerfectSquare ( N ) : NEW_LINE INDENT nextN = math . floor ( math . sqrt ( N ) ) + 1 NEW_LINE return nextN * nextN NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 35 NEW_LINE print ( nextPerfectSquare ( N ) ) NEW_LINE DEDENT
Print all substring of a number without any conversion | Python3 implementation of above approach ; Function to print the substrings of a number ; Calculate the total number of digits ; 0.5 has been added because of it will return double value like 99.556 ; Print all the numbers from starting position ; Update the no . ; Update the no . of digits ; Driver code
import math NEW_LINE def printSubstrings ( n ) : NEW_LINE INDENT s = int ( math . log10 ( n ) ) ; NEW_LINE d = ( math . pow ( 10 , s ) ) ; NEW_LINE k = d ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT while ( d > 0 ) : NEW_LINE INDENT print ( int ( n // d ) ) ; NEW_LINE d = int ( d / 10 ) ; NEW_LINE DEDENT n = int ( n % k ) ; NEW_LINE k = int ( k // 10 ) ; NEW_LINE d = k ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 123 ; NEW_LINE printSubstrings ( n ) ; NEW_LINE DEDENT
Modulo power for large numbers represented as strings | Python3 program to find ( a ^ b ) % MOD where a and b may be very large and represented as strings . ; Returns modulo exponentiation for two numbers represented as long long int . It is used by powerStrings ( ) . Its complexity is log ( n ) ; Returns modulo exponentiation for two numbers represented as strings . It is used by powerStrings ( ) ; We convert strings to number ; calculating a % MOD ; calculating b % ( MOD - 1 ) ; Now a and b are long long int . We calculate a ^ b using modulo exponentiation ; As numbers are very large that is it may contains upto 10 ^ 6 digits . So , we use string .
MOD = 1000000007 ; NEW_LINE def powerLL ( x , n ) : NEW_LINE INDENT result = 1 ; NEW_LINE while ( n ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT result = result * x % MOD ; NEW_LINE DEDENT n = int ( n / 2 ) ; NEW_LINE x = x * x % MOD ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT def powerStrings ( sa , sb ) : NEW_LINE INDENT a = 0 ; NEW_LINE b = 0 ; NEW_LINE for i in range ( len ( sa ) ) : NEW_LINE INDENT a = ( a * 10 + ( ord ( sa [ i ] ) - ord ( '0' ) ) ) % MOD ; NEW_LINE DEDENT for i in range ( len ( sb ) ) : NEW_LINE INDENT b = ( b * 10 + ( ord ( sb [ i ] ) - ord ( '0' ) ) ) % ( MOD - 1 ) ; NEW_LINE DEDENT return powerLL ( a , b ) ; NEW_LINE DEDENT sa = "2" ; NEW_LINE sb = "3" ; NEW_LINE print ( powerStrings ( sa , sb ) ) ; NEW_LINE
Check if a number can be expressed as 2 ^ x + 2 ^ y | Utility function to check if a number is power of 2 or not ; Utility function to determine the value of previous power of 2 ; function to check if n can be expressed as 2 ^ x + 2 ^ y or not ; if value of n is 0 or 1 it can not be expressed as 2 ^ x + 2 ^ y ; if n is power of two then it can be expressed as sum of 2 ^ x + 2 ^ y ; if the remainder after subtracting previous power of 2 is also a power of 2 then it can be expressed as 2 ^ x + 2 ^ y ; driver code
def isPowerOfTwo ( n ) : NEW_LINE INDENT return ( n and ( not ( n & ( n - 1 ) ) ) ) NEW_LINE DEDENT def previousPowerOfTwo ( n ) : NEW_LINE INDENT while ( n & n - 1 ) : NEW_LINE INDENT n = n & n - 1 NEW_LINE DEDENT return n NEW_LINE DEDENT def checkSum ( n ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT elif ( isPowerOfTwo ( n ) ) : NEW_LINE INDENT print ( n // 2 , n // 2 ) NEW_LINE return True NEW_LINE DEDENT else : NEW_LINE INDENT x = previousPowerOfTwo ( n ) NEW_LINE y = n - x ; NEW_LINE if ( isPowerOfTwo ( y ) ) : NEW_LINE INDENT print ( x , y ) NEW_LINE return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT n1 = 20 NEW_LINE if ( checkSum ( n1 ) ) : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT n2 = 11 NEW_LINE if ( checkSum ( n2 ) ) : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
10 's Complement of a decimal number | Python3 program to find 10 's complement ; Function to find 10 's complement ; Calculating total digits in num ; restore num ; calculate 10 's complement ; Driver code
import math NEW_LINE def complement ( num ) : NEW_LINE INDENT i = 0 ; NEW_LINE len = 0 ; NEW_LINE comp = 0 ; NEW_LINE temp = num ; NEW_LINE while ( 1 ) : NEW_LINE INDENT len += 1 ; NEW_LINE num = int ( num / 10 ) ; NEW_LINE if ( abs ( num ) == 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT num = temp ; NEW_LINE comp = math . pow ( 10 , len ) - num ; NEW_LINE return int ( comp ) ; NEW_LINE DEDENT print ( complement ( 25 ) ) ; NEW_LINE print ( complement ( 456 ) ) ; NEW_LINE
Program to find HCF ( Highest Common Factor ) of 2 Numbers | Recursive function to return gcd of a and b ; Everything divides 0 ; base case ; a is greater ; Driver program to test above function
def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 and b == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT if ( a == b ) : NEW_LINE INDENT return a NEW_LINE DEDENT if ( a > b ) : NEW_LINE INDENT return gcd ( a - b , b ) NEW_LINE DEDENT return gcd ( a , b - a ) NEW_LINE DEDENT a = 98 NEW_LINE b = 56 NEW_LINE if ( gcd ( a , b ) ) : NEW_LINE INDENT print ( ' GCD ▁ of ' , a , ' and ' , b , ' is ' , gcd ( a , b ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' not ▁ found ' ) NEW_LINE DEDENT
Number of sub arrays with odd sum | Function to find number of subarrays with odd sum ; ' odd ' stores number of odd numbers upto ith index ' c _ odd ' stores number of odd sum subarrays starting at ith index ' Result ' stores the number of odd sum subarrays ; First find number of odd sum subarrays starting at 0 th index ; Find number of odd sum subarrays starting at ith index add to result ; Driver code
def countOddSum ( a , n ) : NEW_LINE INDENT c_odd = 0 ; NEW_LINE result = 0 ; NEW_LINE odd = False ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % 2 == 1 ) : NEW_LINE INDENT if ( odd == True ) : NEW_LINE INDENT odd = False ; NEW_LINE DEDENT else : NEW_LINE INDENT odd = True ; NEW_LINE DEDENT DEDENT if ( odd ) : NEW_LINE INDENT c_odd += 1 ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT result += c_odd ; NEW_LINE if ( a [ i ] % 2 == 1 ) : NEW_LINE INDENT c_odd = ( n - i - c_odd ) ; NEW_LINE DEDENT DEDENT return result ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ar = [ 5 , 4 , 4 , 5 , 1 , 3 ] ; NEW_LINE n = len ( ar ) ; NEW_LINE print ( " The ▁ Number ▁ of ▁ Subarrays " + " with ▁ odd ▁ sum ▁ is ▁ " , countOddSum ( ar , n ) ) ; NEW_LINE DEDENT
Calculating n | Python Program to find n - th real root of x ; Initialize boundary values ; used for taking approximations of the answer ; Do binary search ; Driver code
def findNthRoot ( x , n ) : NEW_LINE INDENT x = float ( x ) NEW_LINE n = int ( n ) NEW_LINE if ( x >= 0 and x <= 1 ) : NEW_LINE INDENT low = x NEW_LINE high = 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = 1 NEW_LINE high = x NEW_LINE DEDENT epsilon = 0.00000001 NEW_LINE guess = ( low + high ) / 2 NEW_LINE while abs ( guess ** n - x ) >= epsilon : NEW_LINE INDENT if guess ** n > x : NEW_LINE INDENT high = guess NEW_LINE DEDENT else : NEW_LINE INDENT low = guess NEW_LINE DEDENT guess = ( low + high ) / 2 NEW_LINE DEDENT print ( guess ) NEW_LINE DEDENT x = 5 NEW_LINE n = 2 NEW_LINE findNthRoot ( x , n ) NEW_LINE
Sum of all elements up to Nth row in a Pascal triangle | Function to find sum of all elements upto nth row . ; Initialize sum with 0 ; Loop to calculate power of 2 upto n and add them ; Driver code
def calculateSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for row in range ( n ) : NEW_LINE INDENT sum = sum + ( 1 << row ) NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 10 NEW_LINE print ( " Sum ▁ of ▁ all ▁ elements : " , calculateSum ( n ) ) NEW_LINE
Number of sequences which has HEAD at alternate positions to the right of the first HEAD | function to calculate total sequences possible ; Value of N is even ; Value of N is odd ; Driver code
def findAllSequence ( N ) : NEW_LINE INDENT if ( N % 2 == 0 ) : NEW_LINE INDENT return ( pow ( 2 , N / 2 + 1 ) + pow ( 2 , N / 2 ) - 2 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return ( pow ( 2 , ( N + 1 ) / 2 ) + pow ( 2 , ( N + 1 ) / 2 ) - 2 ) ; NEW_LINE DEDENT DEDENT N = 2 ; NEW_LINE print ( int ( findAllSequence ( N ) ) ) ; NEW_LINE
Compute power of power k times % m | Python3 program to compute x ^ x ^ x ^ x . . % m ; Create an array to store phi or totient values ; Function to calculate Euler Totient values ; indicates not evaluated yet and initializes for product formula . ; Compute other Phi values ; If phi [ p ] is not computed already , then number p is prime ; Phi of a prime number p is always equal to p - 1. ; Update phi values of all multiples of p ; Add contribution of p to its multiple i by multiplying with ( 1 - 1 / p ) ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 y = y / 2 ; Function to calculate ( x ^ x ^ x ^ x ... k times ) % m ; to store different mod values ; run loop in reverse to calculate result ; compute euler totient function values ; Calling function to compute answer
N = 1000000 NEW_LINE phi = [ 0 for i in range ( N + 5 ) ] NEW_LINE def computeTotient ( ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT phi [ i ] = i NEW_LINE DEDENT for p in range ( 2 , N + 1 ) : NEW_LINE INDENT if ( phi [ p ] == p ) : NEW_LINE INDENT phi [ p ] = p - 1 NEW_LINE for i in range ( 2 * p , N + 1 , p ) : NEW_LINE INDENT phi [ i ] = ( phi [ i ] // p ) * ( p - 1 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def power ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def calculate ( x , k , mod ) : NEW_LINE INDENT arr = [ 0 for i in range ( N ) ] NEW_LINE count = 0 NEW_LINE while ( mod > 1 ) : NEW_LINE INDENT arr [ count ] = mod NEW_LINE count += 1 NEW_LINE mod = phi [ mod ] NEW_LINE DEDENT result = 1 NEW_LINE loop = count + 1 NEW_LINE arr [ count ] = 1 NEW_LINE for i in range ( min ( k , loop ) , - 1 , - 1 ) : NEW_LINE INDENT result = power ( x , result , arr [ i ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT computeTotient ( ) NEW_LINE x = 3 NEW_LINE k = 2 NEW_LINE m = 3 NEW_LINE print ( calculate ( x , k , m ) ) NEW_LINE
Number of ones in the smallest repunit | Function to find number of 1 s in smallest repunit multiple of the number ; to store number of 1 s in smallest repunit multiple of the number . ; initialize rem with 1 ; run loop until rem becomes zero ; rem * 10 + 1 here represents the repunit modulo n ; when remainder becomes 0 return count ; Driver Code ; Calling function
def countOnes ( n ) : NEW_LINE INDENT count = 1 ; NEW_LINE rem = 1 ; NEW_LINE while ( rem != 0 ) : NEW_LINE INDENT rem = ( rem * 10 + 1 ) % n ; NEW_LINE count = count + 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT n = 13 ; NEW_LINE print ( countOnes ( n ) ) ; NEW_LINE
Largest of two distinct numbers without using any conditional statements or operators | Function to find the largest number ; Driver Code
def largestNum ( a , b ) : NEW_LINE INDENT return a * ( bool ) ( a // b ) + b * ( bool ) ( b // a ) ; NEW_LINE DEDENT a = 22 ; NEW_LINE b = 1231 ; NEW_LINE print ( largestNum ( a , b ) ) ; NEW_LINE
Number of Distinct Meeting Points on a Circular Road | Python3 Program to find number of distinct point of meet on a circular road ; Returns the number of distinct meeting points . ; Find the relative speed . ; convert the negative value to positive . ; Driver Code
import math NEW_LINE def numberOfmeet ( a , b ) : NEW_LINE INDENT ans = 0 ; NEW_LINE if ( a > b ) : NEW_LINE INDENT ans = a - b ; NEW_LINE DEDENT else : NEW_LINE INDENT ans = b - a ; NEW_LINE DEDENT if ( a < 0 ) : NEW_LINE INDENT a = a * ( - 1 ) ; NEW_LINE DEDENT if ( b < 0 ) : NEW_LINE INDENT b = b * ( - 1 ) ; NEW_LINE DEDENT return int ( ans / math . gcd ( a , b ) ) ; NEW_LINE DEDENT a = 1 ; NEW_LINE b = - 1 ; NEW_LINE print ( numberOfmeet ( a , b ) ) ; NEW_LINE
Minimum number of Square Free Divisors | Python 3 Program to find the minimum number of square free divisors ; Initializing MAX with SQRT ( 10 ^ 6 ) ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Print all prime numbers ; This function returns the minimum number of Square Free divisors ; Precomputing Prime Factors ; holds max of max power of all prime factors ; holds the max power of current prime factor ; If number itself is prime , it will be included as answer and thus minimum required answer is 1 ; Driver Code
from math import sqrt NEW_LINE MAX = 1005 NEW_LINE def SieveOfEratosthenes ( primes ) : NEW_LINE INDENT prime = [ True for i in range ( MAX ) ] NEW_LINE for p in range ( 2 , int ( sqrt ( MAX ) ) + 1 , 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , MAX , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT for p in range ( 2 , MAX , 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT primes . append ( p ) NEW_LINE DEDENT DEDENT return primes NEW_LINE DEDENT def minimumSquareFreeDivisors ( N ) : NEW_LINE INDENT prime = [ ] NEW_LINE primes = [ ] NEW_LINE primes = SieveOfEratosthenes ( prime ) NEW_LINE max_count = 0 NEW_LINE i = 0 NEW_LINE while ( len ( primes ) and primes [ i ] * primes [ i ] <= N ) : NEW_LINE INDENT if ( N % primes [ i ] == 0 ) : NEW_LINE INDENT tmp = 0 NEW_LINE while ( N % primes [ i ] == 0 ) : NEW_LINE INDENT tmp += 1 NEW_LINE N /= primes [ i ] NEW_LINE DEDENT max_count = max ( max_count , tmp ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( max_count == 0 ) : NEW_LINE INDENT max_count = 1 NEW_LINE DEDENT return max_count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 24 NEW_LINE print ( " Minimum ▁ Number ▁ of ▁ Square ▁ Free ▁ Divisors ▁ is " , minimumSquareFreeDivisors ( N ) ) NEW_LINE N = 6 NEW_LINE print ( " Minimum ▁ Number ▁ of ▁ Square ▁ Free ▁ Divisors ▁ is " , minimumSquareFreeDivisors ( N ) ) NEW_LINE DEDENT
Subsequence of size k with maximum possible GCD | Python 3 program to find subsequence of size k with maximum possible GCD . ; function to find GCD of sub sequence of size k with max GCD in the array ; Computing highest element ; Array to store the count of divisors i . e . Potential GCDs ; Iterating over every element ; Calculating all the divisors ; Divisor found ; Incrementing count for divisor ; Element / divisor is also a divisor Checking if both divisors are not same ; Checking the highest potential GCD ; If this divisor can divide at least k numbers , it is a GCD of at least one sub sequence of size k ; Driver code ; Array in which sub sequence with size k with max GCD is to be found
import math NEW_LINE def findMaxGCD ( arr , n , k ) : NEW_LINE INDENT high = max ( arr ) NEW_LINE divisors = [ 0 ] * ( high + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 1 , int ( math . sqrt ( arr [ i ] ) ) + 1 ) : NEW_LINE INDENT if ( arr [ i ] % j == 0 ) : NEW_LINE INDENT divisors [ j ] += 1 NEW_LINE if ( j != arr [ i ] // j ) : NEW_LINE INDENT divisors [ arr [ i ] // j ] += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( high , 0 , - 1 ) : NEW_LINE INDENT if ( divisors [ i ] >= k ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 8 , 8 , 12 ] NEW_LINE k = 3 NEW_LINE n = len ( arr ) NEW_LINE print ( findMaxGCD ( arr , n , k ) ) NEW_LINE DEDENT
System of Linear Equations in three variables using Cramer 's Rule | This functions finds the determinant of Matrix ; This function finds the solution of system of linear equations using cramer 's rule ; Matrix d using coeff as given in cramer 's rule ; Matrix d1 using coeff as given in cramer 's rule ; Matrix d2 using coeff as given in cramer 's rule ; Matrix d3 using coeff as given in cramer 's rule ; Calculating Determinant of Matrices d , d1 , d2 , d3 ; Case 1 ; Coeff have a unique solution . Apply Cramer 's Rule ; calculating z using cramer 's rule ; Case 2 ; Driver Code ; storing coefficients of linear equations in coeff matrix
def determinantOfMatrix ( mat ) : NEW_LINE INDENT ans = ( mat [ 0 ] [ 0 ] * ( mat [ 1 ] [ 1 ] * mat [ 2 ] [ 2 ] - mat [ 2 ] [ 1 ] * mat [ 1 ] [ 2 ] ) - mat [ 0 ] [ 1 ] * ( mat [ 1 ] [ 0 ] * mat [ 2 ] [ 2 ] - mat [ 1 ] [ 2 ] * mat [ 2 ] [ 0 ] ) + mat [ 0 ] [ 2 ] * ( mat [ 1 ] [ 0 ] * mat [ 2 ] [ 1 ] - mat [ 1 ] [ 1 ] * mat [ 2 ] [ 0 ] ) ) NEW_LINE return ans NEW_LINE DEDENT def findSolution ( coeff ) : NEW_LINE INDENT d = [ [ coeff [ 0 ] [ 0 ] , coeff [ 0 ] [ 1 ] , coeff [ 0 ] [ 2 ] ] , [ coeff [ 1 ] [ 0 ] , coeff [ 1 ] [ 1 ] , coeff [ 1 ] [ 2 ] ] , [ coeff [ 2 ] [ 0 ] , coeff [ 2 ] [ 1 ] , coeff [ 2 ] [ 2 ] ] ] NEW_LINE d1 = [ [ coeff [ 0 ] [ 3 ] , coeff [ 0 ] [ 1 ] , coeff [ 0 ] [ 2 ] ] , [ coeff [ 1 ] [ 3 ] , coeff [ 1 ] [ 1 ] , coeff [ 1 ] [ 2 ] ] , [ coeff [ 2 ] [ 3 ] , coeff [ 2 ] [ 1 ] , coeff [ 2 ] [ 2 ] ] ] NEW_LINE d2 = [ [ coeff [ 0 ] [ 0 ] , coeff [ 0 ] [ 3 ] , coeff [ 0 ] [ 2 ] ] , [ coeff [ 1 ] [ 0 ] , coeff [ 1 ] [ 3 ] , coeff [ 1 ] [ 2 ] ] , [ coeff [ 2 ] [ 0 ] , coeff [ 2 ] [ 3 ] , coeff [ 2 ] [ 2 ] ] ] NEW_LINE d3 = [ [ coeff [ 0 ] [ 0 ] , coeff [ 0 ] [ 1 ] , coeff [ 0 ] [ 3 ] ] , [ coeff [ 1 ] [ 0 ] , coeff [ 1 ] [ 1 ] , coeff [ 1 ] [ 3 ] ] , [ coeff [ 2 ] [ 0 ] , coeff [ 2 ] [ 1 ] , coeff [ 2 ] [ 3 ] ] ] NEW_LINE D = determinantOfMatrix ( d ) NEW_LINE D1 = determinantOfMatrix ( d1 ) NEW_LINE D2 = determinantOfMatrix ( d2 ) NEW_LINE D3 = determinantOfMatrix ( d3 ) NEW_LINE print ( " D ▁ is ▁ : ▁ " , D ) NEW_LINE print ( " D1 ▁ is ▁ : ▁ " , D1 ) NEW_LINE print ( " D2 ▁ is ▁ : ▁ " , D2 ) NEW_LINE print ( " D3 ▁ is ▁ : ▁ " , D3 ) NEW_LINE if ( D != 0 ) : NEW_LINE INDENT x = D1 / D NEW_LINE y = D2 / D NEW_LINE z = D3 / D NEW_LINE print ( " Value ▁ of ▁ x ▁ is ▁ : ▁ " , x ) NEW_LINE print ( " Value ▁ of ▁ y ▁ is ▁ : ▁ " , y ) NEW_LINE print ( " Value ▁ of ▁ z ▁ is ▁ : ▁ " , z ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( D1 == 0 and D2 == 0 and D3 == 0 ) : NEW_LINE INDENT print ( " Infinite ▁ solutions " ) NEW_LINE DEDENT elif ( D1 != 0 or D2 != 0 or D3 != 0 ) : NEW_LINE INDENT print ( " No ▁ solutions " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT coeff = [ [ 2 , - 1 , 3 , 9 ] , [ 1 , 1 , 1 , 6 ] , [ 1 , - 1 , 1 , 2 ] ] NEW_LINE findSolution ( coeff ) NEW_LINE DEDENT
Find larger of x ^ y and y ^ x | Python3 program to print greater of x ^ y and y ^ x ; Driver Code
import math NEW_LINE def printGreater ( x , y ) : NEW_LINE INDENT X = y * math . log ( x ) ; NEW_LINE Y = x * math . log ( y ) ; NEW_LINE if ( abs ( X - Y ) < 1e-9 ) : NEW_LINE INDENT print ( " Equal " ) ; NEW_LINE DEDENT elif ( X > Y ) : NEW_LINE INDENT print ( x , " ^ " , y ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( y , " ^ " , x ) ; NEW_LINE DEDENT DEDENT x = 5 ; NEW_LINE y = 8 ; NEW_LINE printGreater ( x , y ) ; NEW_LINE
n | Function to print nth term of series ; Driver code
def sumOfSeries ( n ) : NEW_LINE INDENT return n * ( n + 1 ) * ( 6 * n * n * n + 9 * n * n + n - 1 ) / 30 NEW_LINE DEDENT n = 4 NEW_LINE print sumOfSeries ( n ) NEW_LINE
Product of first N factorials | To compute ( a * b ) % MOD ; res = 0 Initialize result ; If b is odd , add ' a ' to result ; Multiply ' a ' with 2 ; Divide b by 2 ; Return result ; This function computes factorials and product by using above function i . e . modular multiplication ; Initialize product and fact with 1 ; ith factorial ; product of first i factorials ; If at any iteration , product becomes divisible by MOD , simply return 0 ; Driver Code to Test above functions
def mulmod ( a , b , mod ) : NEW_LINE INDENT a = a % mod NEW_LINE while ( b > 0 ) : NEW_LINE INDENT if ( b % 2 == 1 ) : NEW_LINE INDENT res = ( res + a ) % mod NEW_LINE DEDENT a = ( a * 2 ) % mod NEW_LINE b //= 2 NEW_LINE DEDENT return res % mod NEW_LINE DEDENT def findProduct ( N ) : NEW_LINE INDENT product = 1 ; fact = 1 NEW_LINE MOD = 1e9 + 7 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT fact = mulmod ( fact , i , MOD ) NEW_LINE product = mulmod ( product , fact , MOD ) NEW_LINE if not product : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return int ( product ) NEW_LINE DEDENT N = 3 NEW_LINE print ( findProduct ( N ) ) NEW_LINE N = 5 NEW_LINE print ( findProduct ( N ) ) NEW_LINE
Check if sum of divisors of two numbers are same | Python3 program to find if two numbers are equivalent or not ; Function to calculate sum of all proper divisors num -- > given natural number ; To store sum of divisors ; Find all divisors and add them ; Function to check if both numbers are equivalent or not ; Driver code
import math NEW_LINE def divSum ( n ) : NEW_LINE INDENT sum = 1 ; NEW_LINE i = 2 ; NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT sum = ( sum + i + math . floor ( n / i ) ) ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def areEquivalent ( num1 , num2 ) : NEW_LINE INDENT return divSum ( num1 ) == divSum ( num2 ) ; NEW_LINE DEDENT num1 = 559 ; NEW_LINE num2 = 703 ; NEW_LINE if ( areEquivalent ( num1 , num2 ) == True ) : NEW_LINE INDENT print ( " Equivalent " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Equivalent " ) ; NEW_LINE DEDENT
Dodecahedral number | Function to calculate dodecahedral number ; Formula to calculate nth dodecahedral number ; Driver Code ; print result
def dodecahedral_num ( n ) : NEW_LINE INDENT return n * ( 3 * n - 1 ) * ( 3 * n - 2 ) // 2 NEW_LINE DEDENT n = 5 NEW_LINE print ( " % sth ▁ Dodecahedral ▁ number ▁ : " % n , dodecahedral_num ( n ) ) NEW_LINE
Count of divisors having more set bits than quotient on dividing N | Python3 Program to find number of Divisors which on integer division produce quotient having less set bit than divisor ; Return the count of set bit . ; check if q and d have same number of set bit . ; Binary Search to find the point at which number of set in q is less than or equal to d . ; while left index is less than right index ; finding the middle . ; check if q and d have same number of set it or not . ; Driver Code
import math NEW_LINE def bit ( x ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( x ) : NEW_LINE INDENT x /= 2 NEW_LINE ans = ans + 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def check ( d , x ) : NEW_LINE INDENT if ( bit ( x / d ) <= bit ( d ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False ; NEW_LINE DEDENT def bs ( n ) : NEW_LINE INDENT l = 1 NEW_LINE r = int ( math . sqrt ( n ) ) NEW_LINE while ( l < r ) : NEW_LINE INDENT m = int ( ( l + r ) / 2 ) NEW_LINE if ( check ( m , n ) ) : NEW_LINE INDENT r = m NEW_LINE DEDENT else : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT DEDENT if ( check ( l , n ) == False ) : NEW_LINE INDENT return math . floor ( l + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return math . floor ( l ) NEW_LINE DEDENT DEDENT def countDivisor ( n ) : NEW_LINE INDENT return n - bs ( n ) + 1 NEW_LINE DEDENT n = 5 NEW_LINE print ( countDivisor ( n ) ) NEW_LINE
Check if two people starting from different points ever meet | Python3 program to find if two people starting from different positions ever meet or not . ; If speed of a person at a position before other person is smaller , then return false . ; Making sure that x1 is greater ; Until one person crosses other ; first person taking one jump in each iteration ; second person taking one jump in each iteration ; Driver code
def everMeet ( x1 , x2 , v1 , v2 ) : NEW_LINE INDENT if ( x1 < x2 and v1 <= v2 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( x1 > x2 and v1 >= v2 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( x1 < x2 ) : NEW_LINE INDENT x1 , x2 = x2 , x1 ; NEW_LINE v1 , v2 = v2 , v1 ; NEW_LINE DEDENT while ( x1 >= x2 ) : NEW_LINE INDENT if ( x1 == x2 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT x1 = x1 + v1 ; NEW_LINE x2 = x2 + v2 ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT x1 = 5 ; NEW_LINE v1 = 8 ; NEW_LINE x2 = 4 ; NEW_LINE v2 = 7 ; NEW_LINE if ( everMeet ( x1 , x2 , v1 , v2 ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT
Divisibility by 3 where each digit is the sum of all prefix digits modulo 10 | Function to check the divisibility ; Cycle ; no of residual terms ; if no of residue term = 0 ; if no of residue term = 1 ; if no of residue term = 2 ; if no of residue term = 3 ; sum of all digits ; divisibility check ; Driver code
def check ( k , d0 , d1 ) : NEW_LINE INDENT s = ( ( 2 * ( d0 + d1 ) ) % 10 + ( 4 * ( d0 + d1 ) ) % 10 + ( 8 * ( d0 + d1 ) ) % 10 + ( 6 * ( d0 + d1 ) ) % 10 ) NEW_LINE a = ( k - 3 ) % 4 NEW_LINE if ( a == 0 ) : NEW_LINE INDENT x = 0 NEW_LINE DEDENT elif ( a == 1 ) : NEW_LINE INDENT x = ( 2 * ( d0 + d1 ) ) % 10 NEW_LINE DEDENT elif ( a == 2 ) : NEW_LINE INDENT x = ( ( 2 * ( d0 + d1 ) ) % 10 + ( 4 * ( d0 + d1 ) ) % 10 ) NEW_LINE DEDENT elif ( a == 3 ) : NEW_LINE INDENT x = ( ( 2 * ( d0 + d1 ) ) % 10 + ( 4 * ( d0 + d1 ) ) % 10 + ( 8 * ( d0 + d1 ) ) % 10 ) NEW_LINE DEDENT sum = d0 + d1 + ( ( k - 3 ) // 4 ) * s + x NEW_LINE if ( sum % 3 == 0 ) : NEW_LINE INDENT return " YES " NEW_LINE DEDENT else : NEW_LINE INDENT return " NO " NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 13 NEW_LINE d0 = 8 NEW_LINE d1 = 1 NEW_LINE print ( check ( k , d0 , d1 ) ) NEW_LINE k = 5 NEW_LINE d0 = 3 NEW_LINE d1 = 4 NEW_LINE print ( check ( k , d0 , d1 ) ) NEW_LINE DEDENT
Find ceil of a / b without using ceil ( ) function | Python3 program to find ceil ( a / b ) without using ceil ( ) function ; taking input 1 ; example of perfect division taking input 2
import math NEW_LINE a = 4 ; NEW_LINE b = 3 ; NEW_LINE val = ( a / b ) + ( ( a % b ) != 0 ) ; NEW_LINE print ( " The ▁ ceiling ▁ value ▁ of ▁ 4/3 ▁ is " , math . floor ( val ) ) ; NEW_LINE a = 6 ; NEW_LINE b = 3 ; NEW_LINE val = int ( ( a / b ) + ( ( a % b ) != 0 ) ) ; NEW_LINE print ( " The ▁ ceiling ▁ value ▁ of ▁ 6/3 ▁ is " , val ) ; NEW_LINE
Program to print Collatz Sequence | Python 3 program to print Collatz sequence ; We simply follow steps while we do not reach 1 ; If n is odd ; If even ; Print 1 at the end ; Driver code
def printCollatz ( n ) : NEW_LINE INDENT while n != 1 : NEW_LINE INDENT print ( n , end = ' ▁ ' ) NEW_LINE if n & 1 : NEW_LINE INDENT n = 3 * n + 1 NEW_LINE DEDENT else : NEW_LINE INDENT n = n // 2 NEW_LINE DEDENT DEDENT print ( n ) NEW_LINE DEDENT printCollatz ( 6 ) NEW_LINE
Powers of 2 to required sum | Python3 program to find the blocks for given number . ; Converting the decimal number into its binary equivalent . ; Displaying the output when the bit is '1' in binary equivalent of number . ; Driver Code
def block ( x ) : NEW_LINE INDENT v = [ ] NEW_LINE print ( " Blocks ▁ for ▁ % d ▁ : ▁ " % x , end = " " ) NEW_LINE while ( x > 0 ) : NEW_LINE INDENT v . append ( int ( x % 2 ) ) NEW_LINE x = int ( x / 2 ) NEW_LINE DEDENT for i in range ( 0 , len ( v ) ) : NEW_LINE INDENT if ( v [ i ] == 1 ) : NEW_LINE INDENT print ( i , end = " " ) NEW_LINE if ( i != len ( v ) - 1 ) : NEW_LINE INDENT print ( " , ▁ " , end = " " ) NEW_LINE DEDENT DEDENT DEDENT print ( " " ) NEW_LINE DEDENT block ( 71307 ) NEW_LINE block ( 1213 ) NEW_LINE block ( 29 ) NEW_LINE block ( 100 ) NEW_LINE
Given a number N in decimal base , find number of its digits in any base ( base b ) | Python3 program to Find Number of digits in base b . ; function to print number of digits ; Calculating log using base changing property and then taking it floor and then adding 1. ; printing output ; taking inputs ; calling the method
import math NEW_LINE def findNumberOfDigits ( n , base ) : NEW_LINE INDENT dig = ( math . floor ( math . log ( n ) / math . log ( base ) ) + 1 ) NEW_LINE print ( " The ▁ Number ▁ of ▁ digits ▁ of " . format ( n , base , dig ) ) DEDENT n = 1446 NEW_LINE base = 7 NEW_LINE findNumberOfDigits ( n , base ) NEW_LINE
Nesbitt 's Inequality | Python3 code to verify Nesbitt 's Inequality ; 3 parts of the inequality sum ; Driver Code
def isValidNesbitt ( a , b , c ) : NEW_LINE INDENT A = a / ( b + c ) ; NEW_LINE B = b / ( a + c ) ; NEW_LINE C = c / ( a + b ) ; NEW_LINE inequality = A + B + C ; NEW_LINE return ( inequality >= 1.5 ) ; NEW_LINE DEDENT a = 1.0 ; NEW_LINE b = 2.0 ; NEW_LINE c = 3.0 ; NEW_LINE if ( isValidNesbitt ( a , b , c ) ) : NEW_LINE INDENT print ( " Nesbitt ' s ▁ inequality ▁ satisfied . " , " ▁ for ▁ real ▁ numbers ▁ " , a , " , ▁ " , b , " , ▁ " , c ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ satisfied " ) ; NEW_LINE DEDENT
Cube Free Numbers smaller than n | Efficient Python3 Program to print all cube free numbers smaller than or equal to n . ; Initialize all numbers as not cube free ; Traverse through all possible cube roots ; If i itself is cube free ; Mark all multiples of i as not cube free ; Print all cube free numbers ; Driver Code
def printCubeFree ( n ) : NEW_LINE INDENT cubFree = [ 1 ] * ( n + 1 ) ; NEW_LINE i = 2 ; NEW_LINE while ( i * i * i <= n ) : NEW_LINE INDENT if ( cubFree [ i ] == 1 ) : NEW_LINE INDENT multiple = 1 ; NEW_LINE while ( i * i * i * multiple <= n ) : NEW_LINE INDENT cubFree [ i * i * i * multiple ] = 0 ; NEW_LINE multiple += 1 ; NEW_LINE DEDENT DEDENT i += 1 ; NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( cubFree [ i ] == 1 ) : NEW_LINE INDENT print ( i , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT printCubeFree ( 20 ) ; NEW_LINE DEDENT
Heap Sort for decreasing order using min heap | To heapify a subtree rooted with node i which is an index in arr [ ] . n is size of heap ; Initialize smalles as root ; left = 2 * i + 1 ; right = 2 * i + 2 ; If left child is smaller than root ; If right child is smaller than smallest so far ; If smallest is not root ; Recursively heapify the affected sub - tree ; main function to do heap sort ; Build heap ( rearrange array ) ; One by one extract an element from heap ; Move current root to end ; call max heapify on the reduced heap ; A utility function to print array of size n ; Driver Code
def heapify ( arr , n , i ) : NEW_LINE INDENT smallest = i NEW_LINE l = 2 * i + 1 NEW_LINE r = 2 * i + 2 NEW_LINE if l < n and arr [ l ] < arr [ smallest ] : NEW_LINE INDENT smallest = l NEW_LINE DEDENT if r < n and arr [ r ] < arr [ smallest ] : NEW_LINE INDENT smallest = r NEW_LINE DEDENT if smallest != i : NEW_LINE INDENT ( arr [ i ] , arr [ smallest ] ) = ( arr [ smallest ] , arr [ i ] ) NEW_LINE heapify ( arr , n , smallest ) NEW_LINE DEDENT DEDENT def heapSort ( arr , n ) : NEW_LINE INDENT for i in range ( int ( n / 2 ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT heapify ( arr , n , i ) NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT arr [ 0 ] , arr [ i ] = arr [ i ] , arr [ 0 ] NEW_LINE heapify ( arr , i , 0 ) NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 6 , 3 , 2 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE heapSort ( arr , n ) NEW_LINE print ( " Sorted ▁ array ▁ is ▁ " ) NEW_LINE printArray ( arr , n ) NEW_LINE DEDENT
Squared triangular number ( Sum of cubes ) | Python3 program to check if a given number is sum of cubes of natural numbers . ; Returns root of n ( n + 1 ) / 2 = num if num is triangular ( or integerroot exists ) . Else returns - 1. ; Considering the equation n * ( n + 1 ) / 2 = num . The equation is : a ( n ^ 2 ) + bn + c = 0 "; ; Find roots of equation ; checking if root1 is natural ; checking if root2 is natural ; Returns square root of x if it is perfect square . Else returns - 1. ; Find floating point value of square root of x . ; If square root is an integer ; Function to find if the given number is sum of the cubes of first n natural numbers ; Driver code
import math NEW_LINE def isTriangular ( num ) : NEW_LINE INDENT if ( num < 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT c = ( - 2 * num ) ; NEW_LINE b = 1 ; NEW_LINE a = 1 ; NEW_LINE d = ( b * b ) - ( 4 * a * c ) ; NEW_LINE if ( d < 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT root1 = ( - b + math . sqrt ( d ) ) // ( 2 * a ) ; NEW_LINE root2 = ( - b - math . sqrt ( d ) ) // ( 2 * a ) ; NEW_LINE if ( root1 > 0 and math . floor ( root1 ) == root1 ) : NEW_LINE INDENT return root1 ; NEW_LINE DEDENT if ( root2 > 0 and math . floor ( root2 ) == root2 ) : NEW_LINE INDENT return root2 ; NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT def isPerfectSquare ( x ) : NEW_LINE INDENT sr = math . sqrt ( x ) ; NEW_LINE if ( ( sr - math . floor ( sr ) ) == 0 ) : NEW_LINE INDENT return math . floor ( sr ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT DEDENT def findS ( s ) : NEW_LINE INDENT sr = isPerfectSquare ( s ) ; NEW_LINE if ( sr == - 1 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT return int ( isTriangular ( sr ) ) ; NEW_LINE DEDENT s = 9 ; NEW_LINE n = findS ( s ) ; NEW_LINE if ( n == - 1 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( n ) ; NEW_LINE DEDENT
Smallest even digits number not less than N | Function to return the answer when the first odd digit is 9 ; traverse towwars the left to find the non - 8 digit ; index digit ; if digit is not 8 , then break ; if on the left side of the '9' , no 8 is found then we return by adding a 2 and 0 's ; till non - 8 digit add all numbers ; if non - 8 is even or odd than add the next even . ; add 0 to right of 9 ; function to return the smallest number with all digits even ; convert the number to string to perform operations ; find out the first odd number ; if no odd numbers are there , than n is the answer ; if the odd number is 9 , than tricky case handles it ; add all digits till first odd ; increase the odd digit by 1 ; add 0 to the right of the odd number ; Driver Code
def trickyCase ( s , index ) : NEW_LINE INDENT index1 = - 1 ; NEW_LINE for i in range ( index - 1 , - 1 , - 1 ) : NEW_LINE INDENT digit = s [ i ] - '0' ; NEW_LINE if ( digit != 8 ) : NEW_LINE INDENT index1 = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( index1 == - 1 ) : NEW_LINE INDENT return 2 * pow ( 10 , len ( s ) ) ; NEW_LINE DEDENT num = 0 ; NEW_LINE for i in range ( index1 ) : NEW_LINE INDENT num = num * 10 + ( s [ i ] - '0' ) ; NEW_LINE DEDENT if ( s [ index1 ] % 2 == 0 ) : NEW_LINE INDENT num = num * 10 + ( s [ index1 ] - '0' + 2 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT num = num * 10 + ( s [ index1 ] - '0' + 1 ) ; NEW_LINE DEDENT for i in range ( index1 + 1 , len ( s ) ) : NEW_LINE INDENT num = num * 10 ; NEW_LINE DEDENT return num ; NEW_LINE DEDENT def smallestNumber ( n ) : NEW_LINE INDENT num = 0 ; NEW_LINE s = " " ; NEW_LINE duplicate = n ; NEW_LINE while ( n ) : NEW_LINE INDENT s = chr ( n % 10 + 48 ) + s ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE DEDENT index = - 1 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT digit = ord ( s [ i ] ) - ord ( '0' ) ; NEW_LINE if ( digit & 1 ) : NEW_LINE INDENT index = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( index == - 1 ) : NEW_LINE INDENT return duplicate ; NEW_LINE DEDENT if ( s [ index ] == '9' ) : NEW_LINE INDENT num = trickyCase ( s , index ) ; NEW_LINE return num ; NEW_LINE DEDENT for i in range ( index ) : NEW_LINE INDENT num = num * 10 + ord ( s [ i ] ) - ord ( '0' ) ; NEW_LINE DEDENT num = num * 10 + ( ord ( s [ index ] ) - ord ( '0' ) + 1 ) ; NEW_LINE for i in range ( index + 1 , len ( s ) ) : NEW_LINE INDENT num = num * 10 ; NEW_LINE DEDENT return num ; NEW_LINE DEDENT N = 2397 ; NEW_LINE print ( smallestNumber ( N ) ) ; NEW_LINE
n | Python3 program to find n - th number with sum of digits as 10. ; Find sum of digits in current no . ; If sum is 10 , we increment count ; If count becomes n , we return current number . ; Driver Code
def findNth ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE curr = 19 ; NEW_LINE while ( True ) : NEW_LINE INDENT sum = 0 ; NEW_LINE x = curr ; NEW_LINE while ( x > 0 ) : NEW_LINE INDENT sum = sum + x % 10 ; NEW_LINE x = int ( x / 10 ) ; NEW_LINE DEDENT if ( sum == 10 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT if ( count == n ) : NEW_LINE INDENT return curr ; NEW_LINE DEDENT curr += 9 ; NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT print ( findNth ( 5 ) ) ; NEW_LINE
Sum of pairwise products | Simple Python3 program to find sum of given series . ; Driver Code
def findSum ( n ) : NEW_LINE INDENT sm = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( i , n + 1 ) : NEW_LINE INDENT sm = sm + i * j NEW_LINE DEDENT DEDENT return sm NEW_LINE DEDENT n = 5 NEW_LINE print ( findSum ( n ) ) NEW_LINE
Sum of pairwise products | Efficient Python3 program to find sum of given series . ; Sum of multiples of 1 is 1 * ( 1 + 2 + . . ) ; Adding sum of multiples of numbers other than 1 , starting from 2. ; Subtract previous number from current multiple . ; For example , for 2 , we get sum as ( 2 + 3 + 4 + ... . ) * 2 ; Driver code
def findSum ( n ) : NEW_LINE INDENT multiTerms = n * ( n + 1 ) // 2 NEW_LINE sm = multiTerms NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT multiTerms = multiTerms - ( i - 1 ) NEW_LINE sm = sm + multiTerms * i NEW_LINE DEDENT return sm NEW_LINE DEDENT n = 5 NEW_LINE print ( findSum ( n ) ) NEW_LINE
Lemoine 's Conjecture | Python code to verify Lemoine 's Conjecture for any odd number >= 7 ; Function to check if a number is prime or not ; Representing n as p + ( 2 * q ) to satisfy lemoine 's conjecture ; Declaring a map to hold pairs ( p , q ) ; Finding various values of p for each q to satisfy n = p + ( 2 * q ) ; After finding a pair that satisfies the equation , check if both p and q are prime or not ; If both p and q are prime , store them in the map ; Displaying all pairs ( p , q ) that satisfy lemoine ' s ▁ conjecture ▁ for ▁ the ▁ number ▁ ' n ; Driver Code ; Function calling
from math import sqrt NEW_LINE def isPrime ( n : int ) -> bool : NEW_LINE INDENT if n < 2 : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def lemoine ( n : int ) -> None : NEW_LINE INDENT pr = dict ( ) NEW_LINE for q in range ( 1 , n // 2 + 1 ) : NEW_LINE INDENT p = n - 2 * q NEW_LINE if isPrime ( p ) and isPrime ( q ) : NEW_LINE INDENT if p not in pr : NEW_LINE INDENT pr [ p ] = q NEW_LINE DEDENT DEDENT DEDENT DEDENT ' NEW_LINE INDENT for it in pr : NEW_LINE INDENT print ( " % d ▁ = ▁ % d ▁ + ▁ ( 2 ▁ * ▁ % d ) " % ( n , it , pr [ it ] ) ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 39 NEW_LINE print ( n , " can ▁ be ▁ expressed ▁ as ▁ " ) NEW_LINE lemoine ( n ) NEW_LINE DEDENT
Sum of n digit numbers divisible by a given number | find the Sum of having n digit and divisible by the number ; compute the first and last term ; first number which is divisible by given number ; last number which is divisible by given number ; total divisible number ; return the total sum ; Driver code
def totalSumDivisibleByNum ( digit , number ) : NEW_LINE INDENT firstnum = pow ( 10 , digit - 1 ) NEW_LINE lastnum = pow ( 10 , digit ) NEW_LINE firstnum = ( firstnum - firstnum % number ) + number NEW_LINE lastnum = ( lastnum - lastnum % number ) NEW_LINE count = ( ( lastnum - firstnum ) / number + 1 ) NEW_LINE return int ( ( ( lastnum + firstnum ) * count ) / 2 ) NEW_LINE DEDENT digit = 3 ; num = 7 NEW_LINE print ( totalSumDivisibleByNum ( digit , num ) ) NEW_LINE
Program for N | Python 3 Program to find nth term of Arithmetic progression ; using formula to find the Nth term t ( n ) = a ( 1 ) + ( n - 1 ) * d ; starting number ; Common difference ; N th term to be find ; Display the output
def Nth_of_AP ( a , d , N ) : NEW_LINE INDENT return ( a + ( N - 1 ) * d ) NEW_LINE DEDENT a = 2 NEW_LINE d = 1 NEW_LINE N = 5 NEW_LINE print ( " The ▁ " , N , " th ▁ term ▁ of ▁ the ▁ series ▁ is ▁ : ▁ " , Nth_of_AP ( a , d , N ) ) NEW_LINE
Fibbinary Numbers ( No consecutive 1 s in binary ) | function to check if binary representation of an integer has consecutive 1 s ; stores the previous last bit initially as 0 ; if current last bit and previous last bit is 1 ; stores the last bit ; right shift the number ; Driver code
def checkFibinnary ( n ) : NEW_LINE INDENT prev_last = 0 NEW_LINE while ( n ) : NEW_LINE INDENT if ( ( n & 1 ) and prev_last ) : NEW_LINE INDENT return False NEW_LINE DEDENT prev_last = n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT n = 10 NEW_LINE if ( checkFibinnary ( n ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
Sum of the series 5 + 55 + 555 + . . up to n terms | function which return the the sum of series ; Driver Code
def sumOfSeries ( n ) : NEW_LINE INDENT return ( int ) ( 0.6172 * ( pow ( 10 , n ) - 1 ) - 0.55 * n ) NEW_LINE DEDENT n = 2 NEW_LINE print ( sumOfSeries ( n ) ) NEW_LINE
Nonagonal number | Function to find nth nonagonal number . ; Formula to find nth nonagonal number . ; Driver function .
def Nonagonal ( n ) : NEW_LINE INDENT return int ( n * ( 7 * n - 5 ) / 2 ) NEW_LINE DEDENT n = 10 NEW_LINE print ( Nonagonal ( n ) ) NEW_LINE
Check if a large number is divisible by 20 | Python3 program to check if a large number is divisible by 20. ; Get number with last two digits ; Check if the number formed by last two digits is divisible by 5 and 4. ; driver code
import math NEW_LINE def divisibleBy20 ( num ) : NEW_LINE INDENT lastTwoDigits = int ( num [ - 2 : ] ) NEW_LINE return ( ( lastTwoDigits % 5 == 0 and lastTwoDigits % 4 == 0 ) ) NEW_LINE DEDENT num = "63284689320" NEW_LINE if ( divisibleBy20 ( num ) == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Divisibility by 12 for a large number | Python Program to check if number is divisible by 12 ; if number greater then 3 ; find last digit ; no is odd ; find second last digit ; find sum of all digits ; f number is less then r equal to 100 ; driver function
import math NEW_LINE def isDvisibleBy12 ( num ) : NEW_LINE INDENT if ( len ( num ) >= 3 ) : NEW_LINE INDENT d1 = int ( num [ len ( num ) - 1 ] ) ; NEW_LINE if ( d1 % 2 != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT d2 = int ( num [ len ( num ) - 2 ] ) NEW_LINE sum = 0 NEW_LINE for i in range ( 0 , len ( num ) ) : NEW_LINE INDENT sum += int ( num [ i ] ) NEW_LINE DEDENT return ( sum % 3 == 0 and ( d2 * 10 + d1 ) % 4 == 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT number = int ( num ) NEW_LINE return ( number % 12 == 0 ) NEW_LINE DEDENT DEDENT num = "12244824607284961224" NEW_LINE if ( isDvisibleBy12 ( num ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Largest number that is not a perfect square | python program to find the largest non perfect square number among n numbers ; takes the sqrt of the number ; checks if it is a perfect square number ; function to find the largest non perfect square number ; stores the maximum of all non perfect square numbers ; traverse for all elements in the array ; store the maximum if not a perfect square ; driver code ; function call
import math NEW_LINE def check ( n ) : NEW_LINE INDENT d = int ( math . sqrt ( n ) ) NEW_LINE if ( d * d == n ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def largestNonPerfectSquareNumber ( a , n ) : NEW_LINE INDENT maxi = - 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( check ( a [ i ] ) == False ) : NEW_LINE INDENT maxi = max ( a [ i ] , maxi ) NEW_LINE DEDENT DEDENT return maxi NEW_LINE DEDENT a = [ 16 , 20 , 25 , 2 , 3 , 10 ] NEW_LINE n = len ( a ) NEW_LINE print ( largestNonPerfectSquareNumber ( a , n ) ) NEW_LINE
Program to print Arithmetic Progression series | Python 3 Program to print an arithmetic progression series ; Printing AP by simply adding d to previous term . ; starting number ; Common difference ; N th term to be find
def printAP ( a , d , n ) : NEW_LINE INDENT curr_term NEW_LINE DEDENT curr_term = a NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE DEDENT print ( curr_term , end = ' ▁ ' ) NEW_LINE INDENT curr_term = curr_term + d NEW_LINE DEDENT a = 2 NEW_LINE d = 1 NEW_LINE n = 5 NEW_LINE printAP ( a , d , n ) NEW_LINE
Count number of trailing zeros in product of array | Returns count of zeros in product of array ; count number of 2 s in each element ; count number of 5 s in each element ; return the minimum ; Driven Program
def countZeros ( a , n ) : NEW_LINE INDENT count2 = 0 NEW_LINE count5 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT while ( a [ i ] % 2 == 0 ) : NEW_LINE INDENT a [ i ] = a [ i ] // 2 NEW_LINE count2 = count2 + 1 NEW_LINE DEDENT while ( a [ i ] % 5 == 0 ) : NEW_LINE INDENT a [ i ] = a [ i ] // 5 NEW_LINE count5 = count5 + 1 NEW_LINE DEDENT DEDENT if ( count2 < count5 ) : NEW_LINE INDENT return count2 NEW_LINE DEDENT else : NEW_LINE INDENT return count5 NEW_LINE DEDENT DEDENT a = [ 10 , 100 , 20 , 30 , 50 , 90 , 12 , 80 ] NEW_LINE n = len ( a ) NEW_LINE print ( countZeros ( a , n ) ) NEW_LINE
Sum of square of first n even numbers | Efficient Python3 code to find sum of square of first n even numbers ; driver code
def squareSum ( n ) : NEW_LINE INDENT return int ( 2 * n * ( n + 1 ) * ( 2 * n + 1 ) / 3 ) NEW_LINE DEDENT ans = squareSum ( 8 ) NEW_LINE print ( ans ) NEW_LINE
MÃ ¼ nchhausen Number | Python 3 code for MA14nchhausen Number ; pwr [ i ] is going to store i raised to power i . ; Function to check out whether the number is MA14nchhausen Number or not ; Precompute i raised to power i for every i ; The input here is fixed i . e . it will check up to n ; check the integer for MA14nchhausen Number , if yes then print out the number ; Driver Code
import math NEW_LINE pwr = [ 0 ] * 10 NEW_LINE def isMunchhausen ( n ) : NEW_LINE INDENT sm = 0 NEW_LINE temp = n NEW_LINE while ( temp ) : NEW_LINE INDENT sm = sm + pwr [ ( temp % 10 ) ] NEW_LINE temp = temp // 10 NEW_LINE DEDENT return ( sm == n ) NEW_LINE DEDENT def printMunchhausenNumbers ( n ) : NEW_LINE INDENT for i in range ( 0 , 10 ) : NEW_LINE INDENT pwr [ i ] = math . pow ( ( float ) ( i ) , ( float ) ( i ) ) NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( isMunchhausen ( i ) ) : NEW_LINE INDENT print ( i ) NEW_LINE DEDENT DEDENT DEDENT n = 10000 NEW_LINE printMunchhausenNumbers ( n ) NEW_LINE
K | Python3 code to compute k - th digit in a ^ b ; computin a ^ b in python ; getting last digit ; increasing count by 1 ; if current number is required digit ; remove last digit ; driver code
def kthdigit ( a , b , k ) : NEW_LINE INDENT p = a ** b NEW_LINE count = 0 NEW_LINE while ( p > 0 and count < k ) : NEW_LINE INDENT rem = p % 10 NEW_LINE count = count + 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT return rem NEW_LINE DEDENT p = p / 10 ; NEW_LINE DEDENT DEDENT a = 5 NEW_LINE b = 2 NEW_LINE k = 1 NEW_LINE ans = kthdigit ( a , b , k ) NEW_LINE print ( ans ) NEW_LINE
Recursive sum of digit in n ^ x , where n and x are very large | Python3 Code for Sum of digit of n ^ x ; function to get sum of digits of a number ; function to return sum ; Find sum of digits in n ; Find remainder of exponent ; Driver method
import math NEW_LINE def digSum ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n % 9 == 0 : NEW_LINE INDENT return 9 NEW_LINE DEDENT else : NEW_LINE INDENT return ( n % 9 ) NEW_LINE DEDENT DEDENT def PowDigSum ( n , x ) : NEW_LINE INDENT sum = digSum ( n ) NEW_LINE rem = x % 6 NEW_LINE if ( ( sum == 3 or sum == 6 ) and x > 1 ) : NEW_LINE INDENT return 9 NEW_LINE DEDENT elif ( x == 1 ) : NEW_LINE INDENT return sum NEW_LINE DEDENT elif ( x == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( rem == 0 ) : NEW_LINE INDENT return digSum ( math . pow ( sum , 6 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT return digSum ( math . pow ( sum , rem ) ) NEW_LINE DEDENT DEDENT n = 33333 NEW_LINE x = 332654 NEW_LINE print ( PowDigSum ( n , x ) ) NEW_LINE
Container with Most Water | Python3 code for Max Water Container ; Calculating the max area ; Driver code
def maxArea ( A ) : NEW_LINE INDENT l = 0 NEW_LINE r = len ( A ) - 1 NEW_LINE area = 0 NEW_LINE while l < r : NEW_LINE INDENT area = max ( area , min ( A [ l ] , A [ r ] ) * ( r - l ) ) NEW_LINE if A [ l ] < A [ r ] : NEW_LINE INDENT l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT r -= 1 NEW_LINE DEDENT DEDENT return area NEW_LINE DEDENT a = [ 1 , 5 , 4 , 3 ] NEW_LINE b = [ 3 , 1 , 2 , 4 , 5 ] NEW_LINE print ( maxArea ( a ) ) NEW_LINE print ( maxArea ( b ) ) NEW_LINE
Program for Mobius Function | Python Program to evaluate Mobius def M ( N ) = 1 if N = 1 M ( N ) = 0 if any prime factor of N is contained twice M ( N ) = ( - 1 ) ^ ( no of distinctprime factors ) ; def to check if n is prime or not ; Handling 2 separately ; If 2 ^ 2 also divides N ; Check for all other prime factors ; If i divides n ; If i ^ 2 also divides N ; Driver Code
import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = i * i NEW_LINE DEDENT return True NEW_LINE DEDENT def mobius ( n ) : NEW_LINE INDENT p = 0 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT n = int ( n / 2 ) NEW_LINE p = p + 1 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT n = int ( n / i ) NEW_LINE p = p + 1 NEW_LINE if ( n % i == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT i = i + 2 NEW_LINE DEDENT if ( p % 2 == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT N = 17 NEW_LINE print ( " Mobius defs M ( N ) at N = { } is : { } " . format ( N , mobius ( N ) ) ) ; NEW_LINE print ( " Mobius defs M ( N ) at N = 25 is : { } " . format ( mobius ( 25 ) ) ) ; NEW_LINE print ( " Mobius defs M ( N ) at N = 6 is : { } " . format ( mobius ( 6 ) ) ) ; NEW_LINE
Sum of squares of binomial coefficients | function to return product of number from start to end . ; Return the sum of square of binomial coefficient ; Driven Program
def factorial ( start , end ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( start , end + 1 ) : NEW_LINE INDENT res *= i NEW_LINE DEDENT return res NEW_LINE DEDENT def sumofsquare ( n ) : NEW_LINE INDENT return int ( factorial ( n + 1 , 2 * n ) / factorial ( 1 , n ) ) NEW_LINE DEDENT n = 4 NEW_LINE print ( sumofsquare ( n ) ) NEW_LINE
Find nth Fibonacci number using Golden ratio | Approximate value of golden ratio ; Fibonacci numbers upto n = 5 ; Function to find nth Fibonacci number ; Fibonacci numbers for n < 6 ; Else start counting from 5 th term ; driver code
PHI = 1.6180339 NEW_LINE f = [ 0 , 1 , 1 , 2 , 3 , 5 ] NEW_LINE def fib ( n ) : NEW_LINE INDENT if n < 6 : NEW_LINE INDENT return f [ n ] NEW_LINE DEDENT t = 5 NEW_LINE fn = 5 NEW_LINE while t < n : NEW_LINE INDENT fn = round ( fn * PHI ) NEW_LINE t += 1 NEW_LINE DEDENT return fn NEW_LINE DEDENT n = 9 NEW_LINE print ( n , " th ▁ Fibonacci ▁ Number ▁ = " , fib ( n ) ) NEW_LINE
Euler Method for solving differential equation | Consider a differential equation dy / dx = ( x + y + xy ) ; Function for euler formula ; Iterating till the point at which we need approximation ; Printing approximation ; Initial Values ; Value of x at which we need approximation
def func ( x , y ) : NEW_LINE INDENT return ( x + y + x * y ) NEW_LINE DEDENT def euler ( x0 , y , h , x ) : NEW_LINE INDENT temp = - 0 NEW_LINE while x0 < x : NEW_LINE INDENT temp = y NEW_LINE y = y + h * func ( x0 , y ) NEW_LINE x0 = x0 + h NEW_LINE DEDENT print ( " Approximate ▁ solution ▁ at ▁ x ▁ = ▁ " , x , " ▁ is ▁ " , " % .6f " % y ) NEW_LINE DEDENT x0 = 0 NEW_LINE y0 = 1 NEW_LINE h = 0.025 NEW_LINE x = 0.1 NEW_LINE euler ( x0 , y0 , h , x ) NEW_LINE
Find x and y satisfying ax + by = n | function to find the solution ; traverse for all possible values ; check if it is satisfying the equation ; driver program to test the above function
def solution ( a , b , n ) : NEW_LINE INDENT i = 0 NEW_LINE while i * a <= n : NEW_LINE INDENT if ( n - ( i * a ) ) % b == 0 : NEW_LINE INDENT print ( " x ▁ = ▁ " , i , " , ▁ y ▁ = ▁ " , int ( ( n - ( i * a ) ) / b ) ) NEW_LINE return 0 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT print ( " No ▁ solution " ) NEW_LINE DEDENT a = 2 NEW_LINE b = 3 NEW_LINE n = 7 NEW_LINE solution ( a , b , n ) NEW_LINE
Sum of Binomial coefficients | Python Program to find the sum of Binomial Coefficient . ; Returns value of Binomial Coefficient Sum ; Driver program to test above function
import math NEW_LINE def binomialCoeffSum ( n ) : NEW_LINE INDENT return ( 1 << n ) ; NEW_LINE DEDENT n = 4 NEW_LINE print ( binomialCoeffSum ( n ) ) NEW_LINE