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 ; ...
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 ) : ...
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 . p...
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 pre...
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 ...
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 " , fr...
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...
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 ...
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 . ...
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...
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 ...
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 . p...
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 n...
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 ) :...
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 ] == ' ( ' ...
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 in...
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 ( maxlengt...
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 operator...
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_LIN...
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 Tru...
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 ) ; ...
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 elemen...
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 ] == ' ] ' : ...
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...
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 con...
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 clos...
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 element...
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 whil...
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 ( ...
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 expressio...
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 ( ...
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 ...
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...
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 p...
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_LI...
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 :...
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...
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' ) :...
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...
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 IN...
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 ag...
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 ) NE...
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 num...
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 ...
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 init...
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 . r...
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 ...
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 . ...
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 ...
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_L...
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 ...
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 ne...
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 ]...
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 ...
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 funct...
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...
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 ...
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 ...
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 ri...
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...
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...
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 . rig...
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 o...
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 DEDEN...
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 Fal...
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...
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_LI...
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_LIN...
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 ] NE...
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 ...
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...
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 costPr...
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 ....
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 % ...
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 expone...
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 ) :...
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...
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 r...
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 c...
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...
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 ind...
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 ...
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 ( ...
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 (...
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...
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 * ...
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 ...
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_LIN...
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 ...
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...
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...
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...
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...
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 ] * ...
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 ...
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 ;...
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...
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 ...
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 ) : NE...
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 o...
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 DEDEN...
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 pe...
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 >= x...
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 ...
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/...
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 ...
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 metho...
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_LI...
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 ...
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 ; R...
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 ...
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 ...
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 ...
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 a...
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...
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 ( ...
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 ; Driv...
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 ) ;...
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 )...
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...
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...
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 : NE...
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 ) ) ...
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 f...
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 ( che...
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 coun...
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 MA14nc...
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 fo...
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_...
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_L...
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 are...
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 ;...
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 ...
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 ( sumofs...
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 ( ...
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 , " ▁ i...
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 DEDE...
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