text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Rearrange characters to form palindrome if possible | Python3 program to rearrange a string to make palindrome . ; Store counts of characters ; Find the number of odd elements . Takes O ( n ) ; odd_cnt = 1 only if the length of str is odd ; Generate first halh of palindrome ; Build a string of floor ( count / 2 ) occurrences of current character ; Attach the built string to end of and begin of second half ; Insert odd character if there is any ; Driver code
from collections import defaultdict NEW_LINE def getPalindrome ( st ) : NEW_LINE INDENT hmap = defaultdict ( int ) NEW_LINE for i in range ( len ( st ) ) : NEW_LINE INDENT hmap [ st [ i ] ] += 1 NEW_LINE DEDENT oddCount = 0 NEW_LINE for x in hmap : NEW_LINE INDENT if ( hmap [ x ] % 2 != 0 ) : NEW_LINE INDENT oddCount += 1 NEW_LINE oddChar = x NEW_LINE DEDENT DEDENT if ( oddCount > 1 or oddCount == 1 and len ( st ) % 2 == 0 ) : NEW_LINE INDENT return " NO ▁ PALINDROME " NEW_LINE DEDENT firstHalf = " " NEW_LINE secondHalf = " " NEW_LINE for x in sorted ( hmap . keys ( ) ) : NEW_LINE INDENT s = ( hmap [ x ] // 2 ) * x NEW_LINE firstHalf = firstHalf + s NEW_LINE secondHalf = s + secondHalf NEW_LINE DEDENT if ( oddCount == 1 ) : NEW_LINE INDENT return ( firstHalf + oddChar + secondHalf ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( firstHalf + secondHalf ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " mdaam " NEW_LINE print ( getPalindrome ( s ) ) NEW_LINE DEDENT
Substrings starting with vowel and ending with consonants and vice versa | Returns true if ch is vowel ; Function to check consonant ; in case of empty string , we can 't fullfill the required condition, hence we return ans as 0. ; co [ i ] is going to store counts of consonants from str [ len - 1 ] to str [ i ] . vo [ i ] is going to store counts of vowels from str [ len - 1 ] to str [ i ] . ; Counting consonants and vowels from end of string . ; Now we traverse string from beginning ; If vowel , then count of substrings starting with str [ i ] is equal to count of consonants after it . ; If consonant , then count of substrings starting with str [ i ] is equal to count of vowels after it . ; Driver Code
def isVowel ( ch ) : NEW_LINE INDENT return ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) NEW_LINE DEDENT def isCons ( ch ) : NEW_LINE INDENT return ( ch != ' a ' and ch != ' e ' and ch != ' i ' and ch != ' o ' and ch != ' u ' ) NEW_LINE DEDENT def countSpecial ( str ) : NEW_LINE INDENT lent = len ( str ) NEW_LINE if lent == 0 : NEW_LINE return 0 ; NEW_LINE co = [ ] NEW_LINE vo = [ ] NEW_LINE for i in range ( 0 , lent + 1 ) : NEW_LINE INDENT co . append ( 0 ) NEW_LINE DEDENT for i in range ( 0 , lent + 1 ) : NEW_LINE INDENT vo . append ( 0 ) NEW_LINE DEDENT if isCons ( str [ lent - 1 ] ) == 1 : NEW_LINE INDENT co [ lent - 1 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT vo [ lent - 1 ] = 1 NEW_LINE DEDENT for i in range ( lent - 2 , - 1 , - 1 ) : NEW_LINE INDENT if isCons ( str [ i ] ) == 1 : NEW_LINE INDENT co [ i ] = co [ i + 1 ] + 1 NEW_LINE vo [ i ] = vo [ i + 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT co [ i ] = co [ i + 1 ] NEW_LINE vo [ i ] = vo [ i + 1 ] + 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( lent ) : NEW_LINE INDENT if isVowel ( str [ i ] ) : NEW_LINE INDENT ans = ans + co [ i + 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT ans = ans + vo [ i + 1 ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT str = " adceba " NEW_LINE print ( countSpecial ( str ) ) NEW_LINE
Convert the string into palindrome string by changing only one character | Function to check if it is possible to convert the string into palindrome ; Counting number of characters that should be changed . ; If count of changes is less than or equal to 1 ; Driver Code
def checkPalindrome ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE count = 0 NEW_LINE for i in range ( 0 , int ( n / 2 ) ) : NEW_LINE INDENT if ( str [ i ] != str [ n - i - 1 ] ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT if ( count <= 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT str = " abccaa " NEW_LINE if ( checkPalindrome ( str ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Number of substrings with odd decimal value in a binary string | python program to count substrings with odd decimal value ; function to count number of substrings with odd decimal representation ; auxiliary array to store count of 1 's before ith index ; store count of 1 's before i-th index ; variable to store answer ; traverse the string reversely to calculate number of odd substrings before i - th index ; Driver method
import math NEW_LINE def countSubstr ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE auxArr = [ 0 for i in range ( n ) ] NEW_LINE if ( s [ 0 ] == '1' ) : NEW_LINE INDENT auxArr [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE if ( s [ i ] == '1' ) : NEW_LINE INDENT auxArr [ i ] = auxArr [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT auxArr [ i ] = auxArr [ i - 1 ] NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT count += auxArr [ i ] NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT s = "1101" NEW_LINE print ( countSubstr ( s ) ) NEW_LINE
Find the starting indices of the substrings in string ( S ) which is made by concatenating all words from a list ( L ) | Returns an integer vector consisting of starting indices of substrings present inside the string S ; Number of a characters of a word in list L . ; Number of words present inside list L . ; Total characters present in list L . ; Resultant vector which stores indices . ; If the total number of characters in list L is more than length of string S itself . ; Map stores the words present in list L against it 's occurrences inside list L ; Traverse the substring ; Extract the word ; If word not found or if frequency of current word is more than required simply break . ; Else decrement the count of word from hash_map ; Store the starting index of that substring when all the words in the list are in substring ; Driver Code
def findSubStringIndices ( s , L ) : NEW_LINE INDENT size_word = len ( L [ 0 ] ) NEW_LINE word_count = len ( L ) NEW_LINE size_L = size_word * word_count NEW_LINE res = [ ] NEW_LINE if size_L > len ( s ) : NEW_LINE INDENT return res NEW_LINE DEDENT hash_map = dict ( ) NEW_LINE for i in range ( word_count ) : NEW_LINE INDENT if L [ i ] in hash_map : NEW_LINE INDENT hash_map [ L [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT hash_map [ L [ i ] ] = 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , len ( s ) - size_L + 1 , 1 ) : NEW_LINE INDENT temp_hash_map = hash_map . copy ( ) NEW_LINE j = i NEW_LINE count = word_count NEW_LINE while j < i + size_L : NEW_LINE INDENT word = s [ j : j + size_word ] NEW_LINE if ( word not in hash_map or temp_hash_map [ word ] == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT temp_hash_map [ word ] -= 1 NEW_LINE count -= 1 NEW_LINE DEDENT j += size_word NEW_LINE DEDENT if count == 0 : NEW_LINE INDENT res . append ( i ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " barfoothefoobarman " NEW_LINE L = [ " foo " , " bar " ] NEW_LINE indices = findSubStringIndices ( s , L ) NEW_LINE print ( * indices ) NEW_LINE DEDENT
Check whether second string can be formed from characters of first string | Python program to check whether second string can be formed from first string ; Create a count array and count frequencies characters in s1 ; Now traverse through str2 to check if every character has enough counts ; Driver Code
def canMakeStr2 ( s1 , s2 ) : NEW_LINE INDENT count = { s1 [ i ] : 0 for i in range ( len ( s1 ) ) } NEW_LINE for i in range ( len ( s1 ) ) : NEW_LINE INDENT count [ s1 [ i ] ] += 1 NEW_LINE DEDENT for i in range ( len ( s2 ) ) : NEW_LINE INDENT if ( count . get ( s2 [ i ] ) == None or count [ s2 [ i ] ] == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT count [ s2 [ i ] ] -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT s1 = " geekforgeeks " NEW_LINE s2 = " for " NEW_LINE if canMakeStr2 ( s1 , s2 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Position of robot after given movements | function to find final position of robot after the complete movement ; traverse the instruction string 'move ; for each movement increment its respective counter ; required final position of robot ; Driver code
def finalPosition ( move ) : NEW_LINE INDENT l = len ( move ) NEW_LINE countUp , countDown = 0 , 0 NEW_LINE countLeft , countRight = 0 , 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( l ) : NEW_LINE INDENT if ( move [ i ] == ' U ' ) : NEW_LINE INDENT countUp += 1 NEW_LINE DEDENT elif ( move [ i ] == ' D ' ) : NEW_LINE INDENT countDown += 1 NEW_LINE DEDENT elif ( move [ i ] == ' L ' ) : NEW_LINE INDENT countLeft += 1 NEW_LINE DEDENT elif ( move [ i ] == ' R ' ) : NEW_LINE INDENT countRight += 1 NEW_LINE DEDENT DEDENT print ( " Final ▁ Position : ▁ ( " , ( countRight - countLeft ) , " , ▁ " , ( countUp - countDown ) , " ) " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT move = " UDDLLRUUUDUURUDDUULLDRRRR " NEW_LINE finalPosition ( move ) NEW_LINE DEDENT
Length of longest balanced parentheses prefix | Function to return the length of longest balanced parentheses prefix . ; Traversing the string . ; If open bracket add 1 to sum . ; If closed bracket subtract 1 from sum ; if first bracket is closing bracket then this condition would help ; If sum is 0 , store the index value . ; Driver Code
def maxbalancedprefix ( str , n ) : NEW_LINE INDENT _sum = 0 NEW_LINE maxi = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if str [ i ] == ' ( ' : NEW_LINE INDENT _sum += 1 NEW_LINE DEDENT else : NEW_LINE INDENT _sum -= 1 NEW_LINE DEDENT if _sum < 0 : NEW_LINE INDENT break NEW_LINE DEDENT if _sum == 0 : NEW_LINE INDENT maxi = i + 1 NEW_LINE DEDENT DEDENT return maxi NEW_LINE DEDENT str = ' ( ( ( ) ( ) ) ( ) ) ( ( ' NEW_LINE n = len ( str ) NEW_LINE print ( maxbalancedprefix ( str , n ) ) NEW_LINE
Minimum cost to convert string into palindrome | Function to return cost ; length of string ; Iterate from both sides of string . If not equal , a cost will be there ; Driver code
def cost ( st ) : NEW_LINE INDENT l = len ( st ) NEW_LINE res = 0 NEW_LINE j = l - 1 NEW_LINE i = 0 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( st [ i ] != st [ j ] ) : NEW_LINE INDENT res += ( min ( ord ( st [ i ] ) , ord ( st [ j ] ) ) - ord ( ' a ' ) + 1 ) NEW_LINE DEDENT i = i + 1 NEW_LINE j = j - 1 NEW_LINE DEDENT return res NEW_LINE DEDENT st = " abcdef " ; NEW_LINE print ( cost ( st ) ) NEW_LINE
Encoding a word into Pig Latin | Python program to encode a word to a Pig Latin . ; the index of the first vowel is stored . ; Pig Latin is possible only if vowels is present ; Take all characters after index ( including index ) . Append all characters which are before index . Finally append " ay " ; Driver code
def isVowel ( c ) : NEW_LINE INDENT return ( c == ' A ' or c == ' E ' or c == ' I ' or c == ' O ' or c == ' U ' or c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) ; NEW_LINE DEDENT def pigLatin ( s ) : NEW_LINE INDENT length = len ( s ) ; NEW_LINE index = - 1 ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( isVowel ( s [ i ] ) ) : NEW_LINE INDENT index = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( index == - 1 ) : NEW_LINE INDENT return " - 1" ; NEW_LINE DEDENT return s [ index : ] + s [ 0 : index ] + " ay " ; NEW_LINE DEDENT str = pigLatin ( " graphic " ) ; NEW_LINE if ( str == " - 1" ) : NEW_LINE INDENT print ( " No ▁ vowels ▁ found . ▁ Pig ▁ Latin ▁ not ▁ possible " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( str ) ; NEW_LINE DEDENT
Possibility of a word from a given set of characters | Python 3 program to check if a query string is present is given set . ; Count occurrences of all characters in s . ; Check if number of occurrences of every character in q is less than or equal to that in s . ; driver program
MAX_CHAR = 256 NEW_LINE def isPresent ( s , q ) : NEW_LINE INDENT freq = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) ] += 1 NEW_LINE DEDENT for i in range ( 0 , len ( q ) ) : NEW_LINE INDENT freq [ ord ( q [ i ] ) ] -= 1 NEW_LINE if ( freq [ ord ( q [ i ] ) ] < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT s = " abctd " NEW_LINE q = " cat " NEW_LINE if ( isPresent ( s , q ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Minimum reduce operations to convert a given string into a palindrome | Returns count of minimum character reduce operations to make palindrome . ; Compare every character of first half with the corresponding character of second half and add difference to result . ; Driver code
def countReduce ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE res = 0 NEW_LINE for i in range ( 0 , int ( n / 2 ) ) : NEW_LINE INDENT res += abs ( int ( ord ( str [ i ] ) ) - int ( ord ( str [ n - i - 1 ] ) ) ) NEW_LINE DEDENT return res NEW_LINE DEDENT str = " abcd " NEW_LINE print ( countReduce ( str ) ) NEW_LINE
Minimal operations to make a number magical | function to calculate the minimal changes ; maximum digits that can be changed ; nested loops to generate all 6 digit numbers ; counter to count the number of change required ; if first digit is equal ; if 2 nd digit is equal ; if 3 rd digit is equal ; if 4 th digit is equal ; if 5 th digit is equal ; if 6 th digit is equal ; checks if less then the previous calculate changes ; returns the answer ; driver program to test the above function ; number stored in string ; prints the minimum operations
def calculate ( s ) : NEW_LINE INDENT ans = 6 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT for k in range ( 10 ) : NEW_LINE INDENT for l in range ( 10 ) : NEW_LINE INDENT for m in range ( 10 ) : NEW_LINE INDENT for n in range ( 10 ) : NEW_LINE INDENT if ( i + j + k == l + m + n ) : NEW_LINE INDENT c = 0 NEW_LINE if ( i != ord ( s [ 0 ] ) - ord ( '0' ) ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( j != ord ( s [ 1 ] ) - ord ( '0' ) ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( k != ord ( s [ 2 ] ) - ord ( '0' ) ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( l != ord ( s [ 3 ] ) - ord ( '0' ) ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( m != ord ( s [ 4 ] ) - ord ( '0' ) ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( n != ord ( s [ 5 ] ) - ord ( '0' ) ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( c < ans ) : NEW_LINE INDENT ans = c NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "123456" NEW_LINE print ( calculate ( s ) ) NEW_LINE DEDENT
Check if a two character string can be made using given words | Function to check if str can be made using given words ; If str itself is present ; Match first character of str with second of word and vice versa ; If both characters found . ; Driver Code
def makeAndCheckString ( words , str ) : NEW_LINE INDENT n = len ( words ) NEW_LINE first = second = False NEW_LINE for i in range ( n ) : NEW_LINE INDENT if words [ i ] == str : NEW_LINE INDENT return True NEW_LINE DEDENT if str [ 0 ] == words [ i ] [ 1 ] : NEW_LINE INDENT first = True NEW_LINE DEDENT if str [ 1 ] == words [ i ] [ 0 ] : NEW_LINE INDENT second = True NEW_LINE DEDENT if first and second : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT str = ' ya ' NEW_LINE words = [ ' ah ' , ' oy ' , ' to ' , ' ha ' ] NEW_LINE if makeAndCheckString ( words , str ) : NEW_LINE INDENT print ( ' YES ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' NO ' ) NEW_LINE DEDENT
Print N | Function to get the binary representation of the number N ; loop for each bit ; generate numbers in the range of ( 2 ^ N ) - 1 to 2 ^ ( N - 1 ) inclusive ; longest prefix check ; if counts of 1 is greater than counts of zero ; do sub - prefixes check ; Driver code ; Function call
def getBinaryRep ( N , num_of_bits ) : NEW_LINE INDENT r = " " ; NEW_LINE num_of_bits -= 1 NEW_LINE while ( num_of_bits >= 0 ) : NEW_LINE INDENT if ( N & ( 1 << num_of_bits ) ) : NEW_LINE INDENT r += ( "1" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT r += ( "0" ) ; NEW_LINE DEDENT num_of_bits -= 1 NEW_LINE DEDENT return r ; NEW_LINE DEDENT def NBitBinary ( N ) : NEW_LINE INDENT r = [ ] NEW_LINE first = 1 << ( N - 1 ) ; NEW_LINE last = first * 2 ; NEW_LINE for i in range ( last - 1 , first - 1 , - 1 ) : NEW_LINE INDENT zero_cnt = 0 ; NEW_LINE one_cnt = 0 ; NEW_LINE t = i ; NEW_LINE num_of_bits = 0 ; NEW_LINE while ( t ) : NEW_LINE INDENT if ( t & 1 ) : NEW_LINE INDENT one_cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT zero_cnt += 1 NEW_LINE DEDENT num_of_bits += 1 NEW_LINE t = t >> 1 ; NEW_LINE DEDENT if ( one_cnt >= zero_cnt ) : NEW_LINE INDENT all_prefix_match = True ; NEW_LINE msk = ( 1 << num_of_bits ) - 2 ; NEW_LINE prefix_shift = 1 ; NEW_LINE while ( msk ) : NEW_LINE INDENT prefix = ( ( msk & i ) >> prefix_shift ) ; NEW_LINE prefix_one_cnt = 0 ; NEW_LINE prefix_zero_cnt = 0 ; NEW_LINE while ( prefix ) : NEW_LINE INDENT if ( prefix & 1 ) : NEW_LINE INDENT prefix_one_cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT prefix_zero_cnt += 1 NEW_LINE DEDENT prefix = prefix >> 1 ; NEW_LINE DEDENT if ( prefix_zero_cnt > prefix_one_cnt ) : NEW_LINE INDENT all_prefix_match = False ; NEW_LINE break ; NEW_LINE DEDENT prefix_shift += 1 NEW_LINE msk = msk & ( msk << 1 ) ; NEW_LINE DEDENT if ( all_prefix_match ) : NEW_LINE INDENT r . append ( getBinaryRep ( i , num_of_bits ) ) ; NEW_LINE DEDENT DEDENT DEDENT return r NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 ; NEW_LINE results = NBitBinary ( n ) ; NEW_LINE for i in range ( len ( results ) ) : NEW_LINE INDENT print ( results [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT
Find winner of an election where votes are represented as candidate names | Python3 program to find winner in an election . ; We have four Candidates with name as ' John ' , ' Johnny ' , ' jamie ' , ' jackie ' . The votes in String array are as per the votes casted . Print the name of candidates received Max vote . ; Insert all votes in a hashmap ; Traverse through map to find the candidate with maximum votes . ; If there is a tie , pick lexicographically smaller . ; Driver code
from collections import defaultdict NEW_LINE def findWinner ( votes ) : NEW_LINE INDENT mapObj = defaultdict ( int ) NEW_LINE for st in votes : NEW_LINE INDENT mapObj [ st ] += 1 NEW_LINE DEDENT maxValueInMap = 0 NEW_LINE winner = " " NEW_LINE for entry in mapObj : NEW_LINE INDENT key = entry NEW_LINE val = mapObj [ entry ] NEW_LINE if ( val > maxValueInMap ) : NEW_LINE INDENT maxValueInMap = val NEW_LINE winner = key NEW_LINE DEDENT elif ( val == maxValueInMap and winner > key ) : NEW_LINE INDENT winner = key NEW_LINE DEDENT DEDENT print ( winner ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT votes = [ " john " , " johnny " , " jackie " , " johnny " , " john " , " jackie " , " jamie " , " jamie " , " john " , " johnny " , " jamie " , " johnny " , " john " ] NEW_LINE findWinner ( votes ) NEW_LINE DEDENT
Luhn algorithm | Returns true if given card number is valid ; We add two digits to handle cases that make two digits after doubling ; Driver code
def checkLuhn ( cardNo ) : NEW_LINE INDENT nDigits = len ( cardNo ) NEW_LINE nSum = 0 NEW_LINE isSecond = False NEW_LINE for i in range ( nDigits - 1 , - 1 , - 1 ) : NEW_LINE INDENT d = ord ( cardNo [ i ] ) - ord ( '0' ) NEW_LINE if ( isSecond == True ) : NEW_LINE INDENT d = d * 2 NEW_LINE DEDENT nSum += d // 10 NEW_LINE nSum += d % 10 NEW_LINE isSecond = not isSecond NEW_LINE DEDENT if ( nSum % 10 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT cardNo = "79927398713" NEW_LINE if ( checkLuhn ( cardNo ) ) : NEW_LINE INDENT print ( " This ▁ is ▁ a ▁ valid ▁ card " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " This ▁ is ▁ not ▁ a ▁ valid ▁ card " ) NEW_LINE DEDENT DEDENT
Distributing all balls without repetition | Python3 program to find if its possible to distribute balls without repitiion ; function to find if its possible to distribute balls or not ; count array to count how many times each color has occurred ; increasing count of each color every time it appears ; to check if any color appears more than K times if it does we will print NO ; Driver code
MAX_CHAR = 26 NEW_LINE def distributingBalls ( k , n , string ) : NEW_LINE INDENT a = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( MAX_CHAR ) : NEW_LINE INDENT if ( a [ i ] > k ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , k = 6 , 3 NEW_LINE string = " aacaab " NEW_LINE if ( distributingBalls ( k , n , string ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
Find substrings that contain all vowels | Returns true if x is vowel . ; Function to check whether a character is vowel or not ; Outer loop picks starting character and inner loop picks ending character . ; If current character is not vowel , then no more result substr1ings possible starting from str1 [ i ] . ; If vowel , then we insert it in hash ; If all vowels are present in current substr1ing ; Driver code
def isVowel ( x ) : NEW_LINE INDENT if ( x == ' a ' or x == ' e ' or x == ' i ' or x == ' o ' or x == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def FindSubstr1ing ( str1 ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT hash = dict ( ) NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT if ( isVowel ( str1 [ j ] ) == False ) : NEW_LINE INDENT break NEW_LINE DEDENT hash [ str1 [ j ] ] = 1 NEW_LINE if ( len ( hash ) == 5 ) : NEW_LINE INDENT print ( str1 [ i : j + 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT str1 = " aeoibsddaeiouudb " NEW_LINE FindSubstr1ing ( str1 ) NEW_LINE
Find if an array contains a string with one mismatch | Python 3 program to find if given string is present with one mismatch . ; If the array is empty ; If sizes are same ; If first mismatch ; Second mismatch ; Driver code
def check ( list , s ) : NEW_LINE INDENT n = len ( list ) NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( len ( list [ i ] ) != len ( s ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT diff = False NEW_LINE for j in range ( 0 , len ( list [ i ] ) , 1 ) : NEW_LINE INDENT if ( list [ i ] [ j ] != s [ j ] ) : NEW_LINE INDENT if ( diff == False ) : NEW_LINE INDENT diff = True NEW_LINE DEDENT else : NEW_LINE INDENT diff = False NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if ( diff ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = [ ] NEW_LINE s . append ( " bana " ) NEW_LINE s . append ( " apple " ) NEW_LINE s . append ( " banacb " ) NEW_LINE s . append ( " bonanza " ) NEW_LINE s . append ( " banamf " ) NEW_LINE print ( int ( check ( s , " banana " ) ) ) NEW_LINE DEDENT
Sentence Palindrome ( Palindrome after removing spaces , dots , . . etc ) | To check sentence is palindrome or not ; Lowercase string ; Compares character until they are equal ; If there is another symbol in left of sentence ; If there is another symbol in right of sentence ; If characters are equal ; If characters are not equal then sentence is not palindrome ; Returns true if sentence is palindrome ; Driver program to test sentencePalindrome ( )
def sentencePalindrome ( s ) : NEW_LINE INDENT l , h = 0 , len ( s ) - 1 NEW_LINE s = s . lower ( ) NEW_LINE while ( l <= h ) : NEW_LINE INDENT if ( not ( s [ l ] >= ' a ' and s [ l ] <= ' z ' ) ) : NEW_LINE INDENT l += 1 NEW_LINE DEDENT elif ( not ( s [ h ] >= ' a ' and s [ h ] <= ' z ' ) ) : NEW_LINE INDENT h -= 1 NEW_LINE DEDENT elif ( s [ l ] == s [ h ] ) : NEW_LINE INDENT l += 1 NEW_LINE h -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT s = " Too ▁ hot ▁ to ▁ hoot . " NEW_LINE if ( sentencePalindrome ( s ) ) : NEW_LINE INDENT print " Sentence ▁ is ▁ palindrome . " NEW_LINE DEDENT else : NEW_LINE INDENT print " Sentence ▁ is ▁ not ▁ palindrome . " NEW_LINE DEDENT
Ways to remove one element from a binary string so that XOR becomes zero | Return number of ways in which XOR become ZERO by remove 1 element ; Counting number of 0 and 1 ; If count of ones is even then return count of zero else count of one ; Driver Code
def xorZero ( str ) : NEW_LINE INDENT one_count = 0 NEW_LINE zero_count = 0 NEW_LINE n = len ( str ) NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( str [ i ] == '1' ) : NEW_LINE INDENT one_count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT zero_count += 1 NEW_LINE DEDENT DEDENT if ( one_count % 2 == 0 ) : NEW_LINE INDENT return zero_count NEW_LINE DEDENT return one_count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "11111" NEW_LINE print ( xorZero ( str ) ) NEW_LINE DEDENT
Check if both halves of the string have same set of characters | Python3 program to check if it is possible to split string or not ; Function to check if we can split string or not ; Counter array initialized with 0 ; Length of the string ; Traverse till the middle element is reached ; First half ; Second half ; Checking if values are different , set flag to 1 ; String to be checked
MAX_CHAR = 26 NEW_LINE def checkCorrectOrNot ( s ) : NEW_LINE INDENT global MAX_CHAR NEW_LINE count = [ 0 ] * MAX_CHAR NEW_LINE n = len ( s ) NEW_LINE if n == 1 : NEW_LINE INDENT return true NEW_LINE DEDENT i = 0 ; j = n - 1 NEW_LINE while i < j : NEW_LINE INDENT count [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE count [ ord ( s [ j ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE i += 1 ; j -= 1 NEW_LINE DEDENT for i in range ( MAX_CHAR ) : NEW_LINE INDENT if count [ i ] != 0 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT s = " abab " NEW_LINE print ( " Yes " if checkCorrectOrNot ( s ) else " No " ) NEW_LINE
Check if a string is Isogram or not | function to check isogram ; loop to store count of chars and check if it is greater than 1 ; if count > 1 , return false ; Driver code ; checking str as isogram ; checking str2 as isogram
def check_isogram ( string ) : NEW_LINE INDENT length = len ( string ) ; NEW_LINE mapHash = [ 0 ] * 26 ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT mapHash [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE if ( mapHash [ ord ( string [ i ] ) - ord ( ' a ' ) ] > 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeks " ; NEW_LINE string2 = " computer " ; NEW_LINE if ( check_isogram ( string ) ) : NEW_LINE INDENT print ( " True " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) ; NEW_LINE DEDENT if ( check_isogram ( string2 ) ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) ; NEW_LINE DEDENT DEDENT
Check if a binary string has a 0 between 1 s or not | Set 1 ( General approach ) | Function returns 1 when string is valid else returns 0 ; Find first occurrence of 1 in s [ ] ; Find last occurrence of 1 in s [ ] ; Check if there is any 0 in range ; Driver code
def checkString ( s ) : NEW_LINE INDENT Len = len ( s ) NEW_LINE first = len ( s ) + 1 NEW_LINE for i in range ( Len ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT first = i NEW_LINE break NEW_LINE DEDENT DEDENT last = 0 NEW_LINE for i in range ( Len - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT last = i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( first , last + 1 ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT s = "00011111111100000" NEW_LINE if ( checkString ( s ) ) : NEW_LINE INDENT print ( " VALID " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NOT ▁ VALID " ) NEW_LINE DEDENT
Program to print all substrings of a given string | * Function to print all ( n * ( n + 1 ) ) / 2 * substrings of a given string s of length n . ; Fix start index in outer loop . Reveal new character in inner loop till end of string . Prtill - now - formed string . ; Driver program to test above function
def printAllSubstrings ( s , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT temp = " " NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT temp += s [ j ] NEW_LINE print ( temp ) NEW_LINE DEDENT DEDENT DEDENT s = " Geeky " NEW_LINE printAllSubstrings ( s , len ( s ) ) NEW_LINE
Reverse a string preserving space positions | Python3 program to implement the above approach ; Initialize two pointers as two corners ; Move both pointers toward each other ; If character at start or end is space , ignore it ; If both are not spaces , do swap ; Driver code
def preserveSpace ( Str ) : NEW_LINE INDENT n = len ( Str ) NEW_LINE Str = list ( Str ) NEW_LINE start = 0 NEW_LINE end = n - 1 NEW_LINE while ( start < end ) : NEW_LINE INDENT if ( Str [ start ] == ' ▁ ' ) : NEW_LINE INDENT start += 1 NEW_LINE continue NEW_LINE DEDENT elif ( Str [ end ] == ' ▁ ' ) : NEW_LINE INDENT end -= 1 NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT Str [ start ] , Str [ end ] = ( Str [ end ] , Str [ start ] ) NEW_LINE start += 1 NEW_LINE end -= 1 NEW_LINE DEDENT DEDENT print ( ' ' . join ( Str ) ) NEW_LINE DEDENT Str = " internship ▁ at ▁ geeks ▁ for ▁ geeks " NEW_LINE preserveSpace ( Str ) ; NEW_LINE
Put spaces between words starting with capital letters | Function to amend the sentence ; Traverse the string ; Convert to lowercase if its an uppercase character ; Print space before it if its an uppercase character ; Print the character ; if lowercase character then just print ; Driver Code
def amendSentence ( string ) : NEW_LINE INDENT string = list ( string ) NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if string [ i ] >= ' A ' and string [ i ] <= ' Z ' : NEW_LINE INDENT string [ i ] = chr ( ord ( string [ i ] ) + 32 ) NEW_LINE if i != 0 : NEW_LINE INDENT print ( " ▁ " , end = " " ) NEW_LINE DEDENT print ( string [ i ] , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( string [ i ] , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " BruceWayneIsBatman " NEW_LINE amendSentence ( string ) NEW_LINE DEDENT
C ++ program to concatenate a string given number of times | Function which return string by concatenating it . ; Copying given string to temporary string . ; Concatenating strings ; Driver code
def repeat ( s , n ) : NEW_LINE INDENT s1 = s NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT s += s1 NEW_LINE DEDENT return s NEW_LINE DEDENT s = " geeks " NEW_LINE n = 3 NEW_LINE print ( repeat ( s , n ) ) NEW_LINE
Number of distinct permutation a String can have | Python program to find number of distinct permutations of a string . ; Utility function to find factorial of n . ; Returns count of distinct permutations of str . ; finding frequency of all the lower case alphabet and storing them in array of integer ; finding factorial of number of appearances and multiplying them since they are repeating alphabets ; finding factorial of size of string and dividing it by factorial found after multiplying ; Driver code
MAX_CHAR = 26 NEW_LINE def factorial ( n ) : NEW_LINE INDENT fact = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT fact = fact * i ; NEW_LINE DEDENT return fact NEW_LINE DEDENT def countDistinctPermutations ( st ) : NEW_LINE INDENT length = len ( st ) NEW_LINE freq = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( 0 , length ) : NEW_LINE INDENT if ( st [ i ] >= ' a ' ) : NEW_LINE INDENT freq [ ( ord ) ( st [ i ] ) - 97 ] = freq [ ( ord ) ( st [ i ] ) - 97 ] + 1 ; NEW_LINE DEDENT DEDENT fact = 1 NEW_LINE for i in range ( 0 , MAX_CHAR ) : NEW_LINE INDENT fact = fact * factorial ( freq [ i ] ) NEW_LINE DEDENT return factorial ( length ) / fact NEW_LINE DEDENT st = " fvvfhvgv " NEW_LINE print ( countDistinctPermutations ( st ) ) NEW_LINE
Determine if a string has all Unique Characters | Python3 program to illustrate String with unique characters without using any data structure ; Assuming string can have characters a - z this has 32 bits set to 0 ; If that bit is already set in checker , return False ; Otherwise update and continue by setting that bit in the checker ; No duplicates encountered , return True ; Driver Code
import math NEW_LINE def uniqueCharacters ( str ) : NEW_LINE INDENT checker = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT bitAtIndex = ord ( str [ i ] ) - ord ( ' a ' ) NEW_LINE if ( ( bitAtIndex ) > 0 ) : NEW_LINE INDENT if ( ( checker & ( ( 1 << bitAtIndex ) ) ) > 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT checker = checker | ( 1 << bitAtIndex ) NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT input = " geekforgeeks " NEW_LINE if ( uniqueCharacters ( input ) ) : NEW_LINE INDENT print ( " The ▁ String ▁ " + input + " ▁ has ▁ all ▁ unique ▁ characters " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ String ▁ " + input + " ▁ has ▁ duplicate ▁ characters " ) NEW_LINE DEDENT DEDENT
Alternate vowel and consonant string | ' ch ' is vowel or not ; create alternate vowel and consonant string str1 [ 0. . . l1 - 1 ] and str2 [ start ... l2 - 1 ] ; first adding character of vowel / consonant then adding character of consonant / vowel ; function to find the required alternate vowel and consonant string ; count vowels and update vowel string ; count consonants and update consonant string ; no such string can be formed ; remove first character of vowel string then create alternate string with cstr [ 0. . . nc - 1 ] and vstr [ 1. . . nv - 1 ] ; remove first character of consonant string then create alternate string with vstr [ 0. . . nv - 1 ] and cstr [ 1. . . nc - 1 ] ; if both vowel and consonant strings are of equal length start creating string with consonant ; start creating string with vowel ; Driver Code
def isVowel ( ch ) : NEW_LINE INDENT if ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def createAltStr ( str1 , str2 , start , l ) : NEW_LINE INDENT finalStr = " " NEW_LINE i = 0 NEW_LINE for j in range ( start , l ) : NEW_LINE INDENT finalStr = ( finalStr + str1 [ i ] ) + str2 [ j ] NEW_LINE i + 1 NEW_LINE DEDENT return finalStr NEW_LINE DEDENT def findAltStr ( str1 ) : NEW_LINE INDENT nv = 0 NEW_LINE nc = 0 NEW_LINE vstr = " " NEW_LINE cstr = " " NEW_LINE l = len ( str1 ) NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT if ( isVowel ( str1 [ i ] ) ) : NEW_LINE INDENT nv += 1 NEW_LINE vstr = vstr + str1 [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT nc += 1 NEW_LINE cstr = cstr + str1 [ i ] NEW_LINE DEDENT DEDENT if ( abs ( nv - nc ) >= 2 ) : NEW_LINE INDENT return " no ▁ such ▁ string " NEW_LINE DEDENT if ( nv > nc ) : NEW_LINE INDENT return ( vstr [ 0 ] + createAltStr ( cstr , vstr , 1 , nv ) ) NEW_LINE DEDENT if ( nc > nv ) : NEW_LINE INDENT return ( cstr [ 0 ] + createAltStr ( vstr , cstr , 1 , nc ) ) NEW_LINE DEDENT if ( cstr [ 0 ] < vstr [ 0 ] ) : NEW_LINE INDENT return createAltStr ( cstr , vstr , 0 , nv ) NEW_LINE DEDENT return createAltStr ( vstr , cstr , 0 , nc ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " geeks " NEW_LINE print ( findAltStr ( str1 ) ) NEW_LINE DEDENT
Check whether K | Python3 code to check if k - th bit of a given number is set or not ; Driver code
def isKthBitSet ( n , k ) : NEW_LINE INDENT if n & ( 1 << ( k - 1 ) ) : NEW_LINE INDENT print ( " SET " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NOT ▁ SET " ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE k = 1 NEW_LINE isKthBitSet ( n , k ) NEW_LINE
Reverse string without using any temporary variable | Reversing a string using reverse ( ) ; Reverse str [ beign . . end ]
str = " geeksforgeeks " ; NEW_LINE str = " " . join ( reversed ( str ) ) NEW_LINE print ( str ) ; NEW_LINE
Recursive function to check if a string is palindrome | A recursive function that check a str [ s . . e ] is palindrome or not . ; If there is only one character ; If first and last characters do not match ; If there are more than two characters , check if middle substring is also palindrome or not . ; An empty string is considered as palindrome ; Driver Code
def isPalRec ( st , s , e ) : NEW_LINE INDENT if ( s == e ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( st [ s ] != st [ e ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( s < e + 1 ) : NEW_LINE INDENT return isPalRec ( st , s + 1 , e - 1 ) ; NEW_LINE DEDENT return True NEW_LINE DEDENT def isPalindrome ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return isPalRec ( st , 0 , n - 1 ) ; NEW_LINE DEDENT st = " geeg " NEW_LINE if ( isPalindrome ( st ) ) : NEW_LINE INDENT print " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT print " No " NEW_LINE DEDENT
Count substrings with same first and last characters | assuming lower case only ; Calculating frequency of each character in the string . ; Computing result using counts ; Driver code
MAX_CHAR = 26 ; NEW_LINE def countSubstringWithEqualEnds ( s ) : NEW_LINE INDENT result = 0 ; NEW_LINE n = len ( s ) ; NEW_LINE count = [ 0 ] * MAX_CHAR ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT for i in range ( MAX_CHAR ) : NEW_LINE INDENT result += ( count [ i ] * ( count [ i ] + 1 ) / 2 ) ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT s = " abcab " ; NEW_LINE print ( countSubstringWithEqualEnds ( s ) ) ; NEW_LINE
Maximum consecutive repeating character in string | Returns the maximum repeating character in a given string ; Traverse string except last character ; If current character matches with next ; If doesn 't match, update result (if required) and reset count ; Driver code
def maxRepeating ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE count = 0 NEW_LINE res = str [ 0 ] NEW_LINE cur_count = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i < n - 1 and str [ i ] == str [ i + 1 ] ) : NEW_LINE INDENT cur_count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if cur_count > count : NEW_LINE INDENT count = cur_count NEW_LINE res = str [ i ] NEW_LINE DEDENT cur_count = 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " aaaabbaaccde " NEW_LINE print ( maxRepeating ( str ) ) NEW_LINE DEDENT
Queries on subsequence of string | Python3 program to answer subsequence queries for a given string . ; Precompute the position of each character from each position of String S ; Computing position of each character from each position of String S ; Print " Yes " if T is subsequence of S , else " No " ; Traversing the string T ; If next position is greater than length of S set flag to false . ; Setting position of next character ; Driven code
MAX = 10000 NEW_LINE CHAR_SIZE = 26 NEW_LINE def precompute ( mat , str , Len ) : NEW_LINE INDENT for i in range ( CHAR_SIZE ) : NEW_LINE INDENT mat [ Len ] [ i ] = Len NEW_LINE DEDENT for i in range ( Len - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( CHAR_SIZE ) : NEW_LINE INDENT mat [ i ] [ j ] = mat [ i + 1 ] [ j ] NEW_LINE DEDENT mat [ i ] [ ord ( str [ i ] ) - ord ( ' a ' ) ] = i NEW_LINE DEDENT DEDENT def query ( mat , str , Len ) : NEW_LINE INDENT pos = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( mat [ pos ] [ ord ( str [ i ] ) - ord ( ' a ' ) ] >= Len ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT pos = mat [ pos ] [ ord ( str [ i ] ) - ord ( ' a ' ) ] + 1 NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT S = " geeksforgeeks " NEW_LINE Len = len ( S ) NEW_LINE mat = [ [ 0 for i in range ( CHAR_SIZE ) ] for j in range ( MAX ) ] NEW_LINE precompute ( mat , S , Len ) NEW_LINE get = " No " NEW_LINE if ( query ( mat , " gg " , Len ) ) : NEW_LINE INDENT get = " Yes " NEW_LINE DEDENT print ( get ) NEW_LINE get = " No " NEW_LINE if ( query ( mat , " gro " , Len ) ) : NEW_LINE INDENT get = " Yes " NEW_LINE DEDENT print ( get ) NEW_LINE get = " No " NEW_LINE if ( query ( mat , " gfg " , Len ) ) : NEW_LINE INDENT get = " Yes " NEW_LINE DEDENT print ( get ) NEW_LINE get = " No " NEW_LINE if ( query ( mat , " orf " , Len ) ) : NEW_LINE INDENT get = " Yes " NEW_LINE DEDENT print ( get ) NEW_LINE
Queries for characters in a repeated string | Print whether index i and j have same element or not . ; Finding relative position of index i , j . ; Checking is element are same at index i , j . ; Driver code
def query ( s , i , j ) : NEW_LINE INDENT n = len ( s ) NEW_LINE i %= n NEW_LINE j %= n NEW_LINE print ( " Yes " ) if s [ i ] == s [ j ] else print ( " No " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = " geeksforgeeks " NEW_LINE query ( X , 0 , 8 ) NEW_LINE query ( X , 8 , 13 ) NEW_LINE query ( X , 6 , 15 ) NEW_LINE DEDENT
Count of character pairs at same distance as in English alphabets | Function to count pairs ; Increment count if characters are at same distance ; Driver code
def countPairs ( str1 ) : NEW_LINE INDENT result = 0 ; NEW_LINE n = len ( str1 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( abs ( ord ( str1 [ i ] ) - ord ( str1 [ j ] ) ) == abs ( i - j ) ) : NEW_LINE INDENT result += 1 ; NEW_LINE DEDENT DEDENT DEDENT return result ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " geeksforgeeks " ; NEW_LINE print ( countPairs ( str1 ) ) ; NEW_LINE DEDENT
Longest common subsequence with permutations allowed | Function to calculate longest string str1 -- > first string str2 -- > second string count1 [ ] -- > hash array to calculate frequency of characters in str1 count [ 2 ] -- > hash array to calculate frequency of characters in str2 result -- > resultant longest string whose permutations are sub - sequence of given two strings ; calculate frequency of characters ; Now traverse hash array ; append character ( ' a ' + i ) in resultant string ' result ' by min ( count1 [ i ] , count2i ] ) times ; Driver Code
def longestString ( str1 , str2 ) : NEW_LINE INDENT count1 = [ 0 ] * 26 NEW_LINE count2 = [ 0 ] * 26 NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT count1 [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( len ( str2 ) ) : NEW_LINE INDENT count2 [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT result = " " NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT for j in range ( 1 , min ( count1 [ i ] , count2 [ i ] ) + 1 ) : NEW_LINE INDENT result = result + chr ( ord ( ' a ' ) + i ) NEW_LINE DEDENT DEDENT print ( result ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " geeks " NEW_LINE str2 = " cake " NEW_LINE longestString ( str1 , str2 ) NEW_LINE DEDENT
Check if string follows order of characters defined by a pattern or not | Set 1 | Function to check if characters in the input string follows the same order as determined by characters present in the given pattern ; len stores length of the given pattern ; if length of pattern is more than length of input string , return false ; ; x , y are two adjacent characters in pattern ; find index of last occurrence of character x in the input string ; find index of first occurrence of character y in the input string ; return false if x or y are not present in the input string OR last occurrence of x is after the first occurrence of y in the input string ; return true if string matches the pattern ; Driver Code
def checkPattern ( string , pattern ) : NEW_LINE INDENT l = len ( pattern ) NEW_LINE if len ( string ) < l : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( l - 1 ) : NEW_LINE INDENT x = pattern [ i ] NEW_LINE y = pattern [ i + 1 ] NEW_LINE last = string . rindex ( x ) NEW_LINE first = string . index ( y ) NEW_LINE if last == - 1 or first == - 1 or last > first : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " engineers ▁ rock " NEW_LINE pattern = " gsr " NEW_LINE print ( checkPattern ( string , pattern ) ) NEW_LINE DEDENT
Calculate sum of all numbers present in a string | Function to calculate sum of all numbers present in a str1ing containing alphanumeric characters ; A temporary str1ing ; holds sum of all numbers present in the str1ing ; read each character in input string ; if current character is a digit ; if current character is an alphabet ; increment Sum by number found earlier ( if any ) ; reset temporary str1ing to empty ; atoi ( temp . c_str1 ( ) ) takes care of trailing numbers ; input alphanumeric str1ing ; Function call
def findSum ( str1 ) : NEW_LINE INDENT temp = "0" NEW_LINE Sum = 0 NEW_LINE for ch in str1 : NEW_LINE INDENT if ( ch . isdigit ( ) ) : NEW_LINE INDENT temp += ch NEW_LINE DEDENT else : NEW_LINE INDENT Sum += int ( temp ) NEW_LINE temp = "0" NEW_LINE DEDENT DEDENT return Sum + int ( temp ) NEW_LINE DEDENT str1 = "12abc20yz68" NEW_LINE print ( findSum ( str1 ) ) NEW_LINE
Count number of substrings with exactly k distinct characters | Function to count number of substrings with exactly k unique characters ; Initialize result ; To store count of characters from ' a ' to ' z ' ; Consider all substrings beginning with str [ i ] ; Initializing array with 0 ; Consider all substrings between str [ i . . j ] ; If this is a new character for this substring , increment dist_count . ; Increment count of current character ; If distinct character count becomes k , then increment result . ; Driver Code
def countkDist ( str1 , k ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE res = 0 NEW_LINE cnt = [ 0 ] * 27 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT dist_count = 0 NEW_LINE cnt = [ 0 ] * 27 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT if ( cnt [ ord ( str1 [ j ] ) - 97 ] == 0 ) : NEW_LINE INDENT dist_count += 1 NEW_LINE DEDENT cnt [ ord ( str1 [ j ] ) - 97 ] += 1 NEW_LINE if ( dist_count == k ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT if ( dist_count > k ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " abcbaa " NEW_LINE k = 3 NEW_LINE print ( " Total ▁ substrings ▁ with ▁ exactly " , k , " distinct ▁ characters ▁ : ▁ " , end = " " ) NEW_LINE print ( countkDist ( str1 , k ) ) NEW_LINE DEDENT
Lower case to upper case | Converts a string to uppercase ; Driver code
def to_upper ( string ) : NEW_LINE INDENT for i in range ( len ( string ) ) : NEW_LINE INDENT if ( ' a ' <= string [ i ] <= ' z ' ) : NEW_LINE INDENT string = ( string [ 0 : i ] + chr ( ord ( string [ i ] ) - ord ( ' a ' ) + ord ( ' A ' ) ) + string [ i + 1 : ] ) NEW_LINE DEDENT DEDENT return string ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " geeksforgeeks " ; NEW_LINE print ( to_upper ( str ) ) ; NEW_LINE DEDENT
Longest Common Prefix using Character by Character Matching | A Function to find the string having the minimum length and returns that length ; A Function that returns the longest common prefix from the array of strings ; Our resultant string char current ; The current character ; Current character ( must be same in all strings to be a part of result ) ; Append to result ; Driver program to test above function
def findMinLength ( arr , n ) : NEW_LINE INDENT min = len ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( len ( arr [ i ] ) < min ) : NEW_LINE INDENT min = len ( arr [ i ] ) NEW_LINE DEDENT DEDENT return ( min ) NEW_LINE DEDENT def commonPrefix ( arr , n ) : NEW_LINE INDENT minlen = findMinLength ( arr , n ) NEW_LINE result = " " NEW_LINE for i in range ( minlen ) : NEW_LINE INDENT current = arr [ 0 ] [ i ] NEW_LINE for j in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ j ] [ i ] != current ) : NEW_LINE INDENT return result NEW_LINE DEDENT DEDENT result = result + current NEW_LINE DEDENT return ( result ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " geeksforgeeks " , " geeks " , " geek " , " geezer " ] NEW_LINE n = len ( arr ) NEW_LINE ans = commonPrefix ( arr , n ) NEW_LINE if ( len ( ans ) ) : NEW_LINE INDENT print ( " The ▁ longest ▁ common ▁ prefix ▁ is ▁ " , ans ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " There ▁ is ▁ no ▁ common ▁ prefix " ) NEW_LINE DEDENT DEDENT
Check if two given strings are isomorphic to each other | Python program to check if two strings are isomorphic ; This function returns true if str1 and str2 are isomorphic ; Length of both strings must be same for one to one corresponance ; To mark visited characters in str2 ; To store mapping of every character from str1 to that of str2 . Initialize all entries of map as - 1 ; Process all characters one by one ; if current character of str1 is seen first time in it . ; if current character of st2 is already seen , one to one mapping not possible ; Mark current character of str2 as visited ; Store mapping of current characters ; If this is not first appearance of current character in str1 , then check if previous appearance mapped to same character of str2 ; Driver program
MAX_CHARS = 256 NEW_LINE def areIsomorphic ( string1 , string2 ) : NEW_LINE INDENT m = len ( string1 ) NEW_LINE n = len ( string2 ) NEW_LINE if m != n : NEW_LINE INDENT return False NEW_LINE DEDENT marked = [ False ] * MAX_CHARS NEW_LINE map = [ - 1 ] * MAX_CHARS NEW_LINE for i in xrange ( n ) : NEW_LINE INDENT if map [ ord ( string1 [ i ] ) ] == - 1 : NEW_LINE INDENT if marked [ ord ( string2 [ i ] ) ] == True : NEW_LINE INDENT return False NEW_LINE DEDENT marked [ ord ( string2 [ i ] ) ] = True NEW_LINE map [ ord ( string1 [ i ] ) ] = string2 [ i ] NEW_LINE DEDENT elif map [ ord ( string1 [ i ] ) ] != string2 [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT print areIsomorphic ( " aab " , " xxy " ) NEW_LINE print areIsomorphic ( " aab " , " xyz " ) NEW_LINE
Minimum insertions to form shortest palindrome | Returns true if a string str [ st . . end ] is palindrome ; Returns count of insertions on left side to make str [ ] a palindrome ; Find the largest prefix of given string that is palindrome . ; Characters after the palindromic prefix must be added at the beginning also to make the complete string palindrome ; Driver Code
def isPalin ( str , st , end ) : NEW_LINE INDENT while ( st < end ) : NEW_LINE INDENT if ( str [ st ] != str [ end ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT st += 1 NEW_LINE end - - 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def findMinInsert ( str , n ) : NEW_LINE INDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( isPalin ( str , 0 , i ) ) : NEW_LINE INDENT return ( n - i - 1 ) NEW_LINE DEDENT DEDENT DEDENT Input = " JAVA " NEW_LINE print ( findMinInsert ( Input , len ( Input ) ) ) NEW_LINE
Remove repeated digits in a given number | Python 3 program to remove repeated digits ; Store first digits as previous digit ; Initialize power ; Iterate through all digits of n , note that the digits are processed from least significant digit to most significant digit . ; Store current digit ; Add the current digit to the beginning of result ; Update previous result and power ; Remove last digit from n ; Driver Code
def removeRecur ( n ) : NEW_LINE INDENT prev_digit = n % 10 NEW_LINE pow = 10 NEW_LINE res = prev_digit NEW_LINE while ( n ) : NEW_LINE INDENT curr_digit = n % 10 NEW_LINE if ( curr_digit != prev_digit ) : NEW_LINE INDENT res += curr_digit * pow NEW_LINE prev_digit = curr_digit NEW_LINE pow *= 10 NEW_LINE DEDENT n = int ( n / 10 ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12224 NEW_LINE print ( removeRecur ( n ) ) NEW_LINE DEDENT
Remove " b " and " ac " from a given string | Utility function to convert string to list ; Utility function to convert list to string ; length of string ; Check if current and next character forms ac ; If current character is b ; if current char is ' c ▁ & & ▁ last ▁ char ▁ in ▁ output ▁ ▁ is ▁ ' a ' so delete both ; Else copy curr char to output string ; Driver program
def toList ( string ) : NEW_LINE INDENT l = [ ] NEW_LINE for x in string : NEW_LINE INDENT l . append ( x ) NEW_LINE DEDENT return l NEW_LINE DEDENT def toString ( l ) : NEW_LINE INDENT return ' ' . join ( l ) NEW_LINE DEDENT def stringFilter ( string ) : NEW_LINE INDENT n = len ( string ) NEW_LINE i = - 1 NEW_LINE j = 0 NEW_LINE while j < n : NEW_LINE INDENT if j < n - 1 and string [ j ] == ' a ' and string [ j + 1 ] == ' c ' : NEW_LINE INDENT j += 2 NEW_LINE DEDENT elif string [ j ] == ' b ' : NEW_LINE INDENT j += 1 NEW_LINE DEDENT elif i >= 0 and string [ j ] == ' c ' and string [ i ] == ' a ' : NEW_LINE INDENT i -= 1 NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE string [ i ] = string [ j ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE return toString ( string [ : i ] ) NEW_LINE DEDENT string1 = " ad " NEW_LINE print " Input ▁ = > ▁ " + string1 + " NEW_LINE Output = > " , NEW_LINE print stringFilter ( toList ( string1 ) ) + " NEW_LINE " NEW_LINE string2 = " acbac " NEW_LINE print " Input ▁ = > ▁ " + string2 + " NEW_LINE Output = > " , NEW_LINE print stringFilter ( toList ( string2 ) ) + " NEW_LINE " NEW_LINE string3 = " aaac " NEW_LINE print " Input ▁ = > ▁ " + string3 + " NEW_LINE Output = > " , NEW_LINE print stringFilter ( toList ( string3 ) ) + " NEW_LINE " NEW_LINE string4 = " react " NEW_LINE print " Input ▁ = > ▁ " + string4 + " NEW_LINE Output = > " , NEW_LINE print stringFilter ( toList ( string4 ) ) + " NEW_LINE " NEW_LINE string5 = " aa " NEW_LINE print " Input ▁ = > ▁ " + string5 + " NEW_LINE Output = > " , NEW_LINE print stringFilter ( toList ( string5 ) ) + " NEW_LINE " NEW_LINE string6 = " ababaac " NEW_LINE print " Input ▁ = > ▁ " + string6 + " NEW_LINE Output = > " , NEW_LINE print stringFilter ( toList ( string6 ) ) + " NEW_LINE " NEW_LINE string7 = " abc " NEW_LINE print " Input ▁ = > ▁ " + string7 + " NEW_LINE Output = > " , NEW_LINE print stringFilter ( toList ( string7 ) ) + " NEW_LINE " NEW_LINE
Write your own atoi ( ) | A simple Python3 program for implementation of atoi ; If whitespaces then ignore . ; Sign of number ; Checking for valid input ; Handling overflow test case ; Driver Code ; Functional Code
import sys NEW_LINE def myAtoi ( Str ) : NEW_LINE INDENT sign , base , i = 1 , 0 , 0 NEW_LINE while ( Str [ i ] == ' ▁ ' ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if ( Str [ i ] == ' - ' or Str [ i ] == ' + ' ) : NEW_LINE INDENT sign = 1 - 2 * ( Str [ i ] == ' - ' ) NEW_LINE i += 1 NEW_LINE DEDENT while ( i < len ( Str ) and Str [ i ] >= '0' and Str [ i ] <= '9' ) : NEW_LINE INDENT if ( base > ( sys . maxsize // 10 ) or ( base == ( sys . maxsize // 10 ) and ( Str [ i ] - '0' ) > 7 ) ) : NEW_LINE INDENT if ( sign == 1 ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT else : NEW_LINE INDENT return - ( sys . maxsize ) NEW_LINE DEDENT DEDENT base = 10 * base + ( ord ( Str [ i ] ) - ord ( '0' ) ) NEW_LINE i += 1 NEW_LINE DEDENT return base * sign NEW_LINE DEDENT Str = list ( " ▁ - 123" ) NEW_LINE val = myAtoi ( Str ) NEW_LINE print ( val ) NEW_LINE
Check whether two strings are anagram of each other | Python program to check if two strings are anagrams of each other ; function to check if two strings are anagrams of each other ; Create a count array and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; If both strings are of different length . Removing this condition will make the program fail for strings like " aaca " and " aca " ; See if there is any non - zero value in count array ; Driver code ; Function call
NO_OF_CHARS = 256 NEW_LINE def areAnagram ( str1 , str2 ) : NEW_LINE INDENT count = [ 0 for i in range ( NO_OF_CHARS ) ] NEW_LINE i = 0 NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT count [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE count [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] -= 1 ; NEW_LINE DEDENT if ( len ( str1 ) != len ( str2 ) ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( NO_OF_CHARS ) : NEW_LINE INDENT if ( count [ i ] != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT str1 = " geeksforgeeks " NEW_LINE str2 = " forgeeksgeeks " NEW_LINE if ( areAnagram ( str1 , str2 ) ) : NEW_LINE INDENT print ( " The ▁ two ▁ strings ▁ are ▁ anagram ▁ of ▁ each ▁ other " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ two ▁ strings ▁ are ▁ not ▁ anagram ▁ of ▁ each ▁ other " ) NEW_LINE DEDENT
Length of the longest substring without repeating characters | This functionr eturns true if all characters in strr [ i . . j ] are distinct , otherwise returns false ; Note : Default values in visited are false ; Returns length of the longest substring with all distinct characters . ; Result ; Driver code
def areDistinct ( strr , i , j ) : NEW_LINE INDENT visited = [ 0 ] * ( 26 ) NEW_LINE for k in range ( i , j + 1 ) : NEW_LINE INDENT if ( visited [ ord ( strr [ k ] ) - ord ( ' a ' ) ] == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT visited [ ord ( strr [ k ] ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT return True NEW_LINE DEDENT def longestUniqueSubsttr ( strr ) : NEW_LINE INDENT n = len ( strr ) NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT if ( areDistinct ( strr , i , j ) ) : NEW_LINE INDENT res = max ( res , j - i + 1 ) NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = " geeksforgeeks " NEW_LINE print ( " The ▁ input ▁ is ▁ " , strr ) NEW_LINE len = longestUniqueSubsttr ( strr ) NEW_LINE print ( " The ▁ length ▁ of ▁ the ▁ longest ▁ " " non - repeating ▁ character ▁ substring ▁ is ▁ " , len ) NEW_LINE DEDENT
Remove duplicates from a given string | Function to make the string unique ; loop to traverse the string and check for repeating chars using IndexOf ( ) method in Java ; character at i 'th index of s ; if c is present in str , it returns the index of c , else it returns - 1 print ( st . index ( c ) ) ; adding c to str if - 1 is returned ; Driver code ; Input string with repeating chars
def unique ( s ) : NEW_LINE INDENT st = " " NEW_LINE length = len ( s ) NEW_LINE for i in range ( length ) : NEW_LINE INDENT c = s [ i ] NEW_LINE if c not in st : NEW_LINE INDENT st += c NEW_LINE DEDENT DEDENT return st NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE print ( unique ( s ) ) NEW_LINE DEDENT
Sum of all subsets whose sum is a Perfect Number from a given array | Python3 program for the above approach ; Function to check is a given number is a perfect number or not ; Stores the sum of its divisors ; Add all divisors of x to sum_div ; If the sum of divisors is equal to the given number , return true ; Otherwise , return false ; Function to find sum of all subsets from an array whose sum is a perfect number ; Prthe current subset sum if it is a perfect number ; Check if sum is a perfect number or not ; Calculate sum of the subset including arr [ l ] ; Calculate sum of the subset excluding arr [ l ] ; Driver Code
import math NEW_LINE def isPerfect ( x ) : NEW_LINE INDENT sum_div = 1 NEW_LINE for i in range ( 2 , ( x // 2 ) + 1 ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT sum_div += i NEW_LINE DEDENT DEDENT if ( sum_div == x ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def subsetSum ( arr , l , r , sum ) : NEW_LINE INDENT if ( l > r ) : NEW_LINE INDENT if ( isPerfect ( sum ) != 0 ) : NEW_LINE INDENT print ( sum , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT subsetSum ( arr , l + 1 , r , sum + arr [ l ] ) NEW_LINE subsetSum ( arr , l + 1 , r , sum ) NEW_LINE DEDENT arr = [ 5 , 4 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE subsetSum ( arr , 0 , N - 1 , 0 ) NEW_LINE
Print all possible ways to split an array into K subsets | Utility function to find all possible ways to split array into K subsets ; If count of elements in K subsets are greater than or equal to N ; If count of subsets formed is equal to K ; Print K subsets by splitting array into K subsets ; Print current subset ; If current element is the last element of the subset ; Otherwise ; If any subset is occupied , then push the element in that first ; Recursively do the same for remaining elements ; Backtrack ; Otherwise , push it in an empty subset and increase the subset count by 1 ; Break to avoid the case of going in other empty subsets , if available , and forming the same combination ; Function to to find all possible ways to split array into K subsets ; Stores K subset by splitting array into K subsets ; Size of each subset must be less than the number of elements ; Driver Code ; Given array ; Given K ; Size of the array ; Prints all possible splits into subsets
def PartitionSub ( arr , i , N , K , nos , v ) : NEW_LINE INDENT if ( i >= N ) : NEW_LINE INDENT if ( nos == K ) : NEW_LINE INDENT for x in range ( len ( v ) ) : NEW_LINE INDENT print ( " { ▁ " , end = " " ) NEW_LINE for y in range ( len ( v [ x ] ) ) : NEW_LINE INDENT print ( v [ x ] [ y ] , end = " " ) NEW_LINE if ( y == len ( v [ x ] ) - 1 ) : NEW_LINE INDENT print ( " ▁ " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " , ▁ " , end = " " ) NEW_LINE DEDENT DEDENT if ( x == len ( v ) - 1 ) : NEW_LINE INDENT print ( " } " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " } , ▁ " , end = " " ) NEW_LINE DEDENT DEDENT print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE DEDENT return NEW_LINE DEDENT for j in range ( K ) : NEW_LINE INDENT if ( len ( v [ j ] ) > 0 ) : NEW_LINE INDENT v [ j ] . append ( arr [ i ] ) NEW_LINE PartitionSub ( arr , i + 1 , N , K , nos , v ) NEW_LINE v [ j ] . remove ( v [ j ] [ len ( v [ j ] ) - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT v [ j ] . append ( arr [ i ] ) NEW_LINE PartitionSub ( arr , i + 1 , N , K , nos + 1 , v ) NEW_LINE v [ j ] . remove ( v [ j ] [ len ( v [ j ] ) - 1 ] ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT def partKSubsets ( arr , N , K ) : NEW_LINE INDENT v = [ [ ] for i in range ( K ) ] NEW_LINE if ( K == 0 or K > N ) : NEW_LINE INDENT print ( " Not ▁ Possible " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ Subset ▁ Combinations ▁ are : ▁ " ) NEW_LINE PartitionSub ( arr , 0 , N , K , 0 , v ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE partKSubsets ( arr , N , K ) NEW_LINE DEDENT
Count the number of Prime Cliques in an undirected graph | Python3 implementation to Count the number of Prime Cliques in an undirected graph ; Stores the vertices ; Graph ; Degree of the vertices ; To store the count of prime cliques ; Function to create Sieve to check primes ; false here indicates that it is not prime ; Condition if prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to check if the given set of vertices in store array is a clique or not ; Run a loop for all set of edges ; If any edge is missing ; Function to find the count of all the cliques having prime size ; Check if any vertices from i + 1 can be inserted ; Add the vertex to store ; If the graph is not a clique of size k then it cannot be a clique by adding another edge ; Increase the count of prime cliques if the size of current clique is prime ; Check if another edge can be added ; Driver code
MAX = 100 NEW_LINE store = [ 0 for i in range ( MAX ) ] NEW_LINE n = 0 NEW_LINE graph = [ [ 0 for j in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE d = [ 0 for i in range ( MAX ) ] NEW_LINE ans = 0 NEW_LINE def SieveOfEratosthenes ( prime , p_size ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while ( p * p <= p_size ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , p_size + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def is_clique ( b ) : NEW_LINE INDENT for i in range ( 1 , b ) : NEW_LINE INDENT for j in range ( i + 1 , b ) : NEW_LINE INDENT if ( graph [ store [ i ] ] [ store [ j ] ] == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def primeCliques ( i , l , prime ) : NEW_LINE INDENT global ans NEW_LINE for j in range ( i + 1 , n + 1 ) : NEW_LINE INDENT store [ l ] = j NEW_LINE if ( is_clique ( l + 1 ) ) : NEW_LINE INDENT if ( prime [ l ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT primeCliques ( j , l + 1 , prime ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT edges = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 3 , 1 ] , [ 4 , 3 ] , [ 4 , 5 ] , [ 5 , 3 ] ] NEW_LINE size = len ( edges ) NEW_LINE n = 5 NEW_LINE prime = [ True for i in range ( n + 2 ) ] NEW_LINE SieveOfEratosthenes ( prime , n + 1 ) NEW_LINE for i in range ( size ) : NEW_LINE INDENT graph [ edges [ i ] [ 0 ] ] [ edges [ i ] [ 1 ] ] = 1 NEW_LINE graph [ edges [ i ] [ 1 ] ] [ edges [ i ] [ 0 ] ] = 1 NEW_LINE d [ edges [ i ] [ 0 ] ] += 1 NEW_LINE d [ edges [ i ] [ 1 ] ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE primeCliques ( 0 , 1 , prime ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Construct a Doubly linked linked list from 2D Matrix | define dimension of matrix ; struct node of doubly linked list with four pointer next , prev , up , down ; function to create a new node ; function to construct the doubly linked list ; Create Node with value contain in matrix at index ( i , j ) ; Assign address of curr into the prev pointer of temp ; Assign address of curr into the up pointer of temp ; Recursive call for next pointer ; Recursive call for down pointer ; Return newly constructed node whose all four node connected at it 's appropriate position ; Function to construct the doubly linked list ; function call for construct the doubly linked list ; function for displaying doubly linked list data ; pointer to move right ; pointer to move down ; loop till node -> down is not NULL ; loop till node -> right is not NULL ; Driver code ; initialise matrix
dim = 3 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . prev = None NEW_LINE self . up = None NEW_LINE self . down = None NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def createNode ( data ) : NEW_LINE INDENT temp = Node ( data ) ; NEW_LINE return temp ; NEW_LINE DEDENT def constructDoublyListUtil ( mtrx , i , j , curr ) : NEW_LINE INDENT if ( i >= dim or j >= dim ) : NEW_LINE INDENT return None ; NEW_LINE DEDENT temp = createNode ( mtrx [ i ] [ j ] ) ; NEW_LINE temp . prev = curr ; NEW_LINE temp . up = curr ; NEW_LINE temp . next = constructDoublyListUtil ( mtrx , i , j + 1 , temp ) ; NEW_LINE temp . down = constructDoublyListUtil ( mtrx , i + 1 , j , temp ) ; NEW_LINE return temp ; NEW_LINE DEDENT def constructDoublyList ( mtrx ) : NEW_LINE INDENT return constructDoublyListUtil ( mtrx , 0 , 0 , None ) ; NEW_LINE DEDENT def display ( head ) : NEW_LINE INDENT rPtr = None NEW_LINE dPtr = head ; NEW_LINE while ( dPtr != None ) : NEW_LINE INDENT rPtr = dPtr ; NEW_LINE while ( rPtr != None ) : NEW_LINE INDENT print ( rPtr . data , end = ' ▁ ' ) NEW_LINE rPtr = rPtr . next ; NEW_LINE DEDENT print ( ) NEW_LINE dPtr = dPtr . down ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mtrx = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE list = constructDoublyList ( mtrx ) ; NEW_LINE display ( list ) ; NEW_LINE DEDENT
Count of exponential paths in a Binary Tree | Python3 program to find the count exponential paths in Binary Tree ; Structure of a Tree node ; Function to create a new node ; Function to find x ; Take log10 of n ; Log ( n ) with base i ; Raising i to the power p ; Function to check whether the given node equals to x ^ y for some y > 0 ; Take logx ( n ) with base x ; Utility function to count the exponent path in a given Binary tree ; Base Condition , when node pointer becomes null or node value is not a number of pow ( x , y ) ; Increment count when encounter leaf node ; Left recursive call save the value of count ; Right recursive call and return value of count ; Function to count exponential paths ; Create Tree ; Retrieve the value of x ; Function call
import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( key ) : NEW_LINE INDENT temp = Node ( key ) NEW_LINE return temp NEW_LINE DEDENT def find_x ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT num = math . log10 ( n ) NEW_LINE x , no = 0 , 0 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT den = math . log10 ( i ) NEW_LINE p = num / den NEW_LINE no = int ( pow ( i , int ( p ) ) ) NEW_LINE if abs ( no - n ) < 1e-6 : NEW_LINE INDENT x = i NEW_LINE break NEW_LINE DEDENT DEDENT return x NEW_LINE DEDENT def is_key ( n , x ) : NEW_LINE INDENT p = math . log10 ( n ) / math . log10 ( x ) NEW_LINE no = int ( pow ( x , int ( p ) ) ) NEW_LINE if n == no : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def evenPaths ( node , count , x ) : NEW_LINE INDENT if node == None or not is_key ( node . key , x ) : NEW_LINE INDENT return count NEW_LINE DEDENT if node . left == None and node . right == None : NEW_LINE INDENT count += 1 NEW_LINE DEDENT count = evenPaths ( node . left , count , x ) NEW_LINE return evenPaths ( node . right , count , x ) NEW_LINE DEDENT def countExpPaths ( node , x ) : NEW_LINE INDENT return evenPaths ( node , 0 , x ) NEW_LINE DEDENT root = newNode ( 27 ) NEW_LINE root . left = newNode ( 9 ) NEW_LINE root . right = newNode ( 81 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE root . left . right = newNode ( 10 ) NEW_LINE root . right . left = newNode ( 70 ) NEW_LINE root . right . right = newNode ( 243 ) NEW_LINE root . right . right . left = newNode ( 81 ) NEW_LINE root . right . right . right = newNode ( 909 ) NEW_LINE x = find_x ( root . key ) NEW_LINE print ( countExpPaths ( root , x ) ) NEW_LINE
Number of pairs such that path between pairs has the two vertices A and B | Python 3 program to find the number of pairs such that the path between every pair contains two given vertices ; Function to perform DFS on the given graph by fixing the a vertex ; To mark a particular vertex as visited ; Variable to store the count of the vertices which can be reached from a ; Performing the DFS by iterating over the visited array ; If the vertex is not visited and removing the vertex b ; Function to return the number of pairs such that path between any two pairs consists of the given two vertices A and B ; Initializing the visited array and assigning it with 0 's ; Initially , the count of vertices is 0 ; Performing DFS by removing the vertex B ; Count the vertices which cannot be reached after removing the vertex B ; Again reinitializing the visited array ; Setting the count of vertices to 0 to perform the DFS again ; Performing the DFS by removing the vertex A ; Count the vertices which cannot be reached after removing the vertex A ; Multiplying both the vertices set ; Driver code ; Loop to store the graph
N = 1000001 NEW_LINE c = 0 NEW_LINE n = 0 NEW_LINE m = 0 NEW_LINE a = 0 NEW_LINE b = 0 NEW_LINE def dfs ( a , b , v , vis ) : NEW_LINE INDENT global c NEW_LINE vis [ a ] = 1 NEW_LINE c += 1 NEW_LINE for i in v [ a ] : NEW_LINE INDENT if ( vis [ i ] == 0 and i != b ) : NEW_LINE INDENT dfs ( i , b , v , vis ) NEW_LINE DEDENT DEDENT DEDENT def Calculate ( v ) : NEW_LINE INDENT global c NEW_LINE vis = [ 0 for i in range ( n + 1 ) ] NEW_LINE c = 0 NEW_LINE dfs ( a , b , v , vis ) NEW_LINE ans1 = n - c - 1 NEW_LINE vis = [ 0 for i in range ( len ( vis ) ) ] NEW_LINE c = 0 NEW_LINE dfs ( b , a , v , vis ) NEW_LINE ans2 = n - c - 1 NEW_LINE print ( ans1 * ans2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 NEW_LINE m = 7 NEW_LINE a = 3 NEW_LINE b = 5 NEW_LINE edges = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 3 , 4 ] , [ 4 , 5 ] , [ 5 , 6 ] , [ 6 , 7 ] , [ 7 , 5 ] ] NEW_LINE v = [ [ ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT v [ edges [ i ] [ 0 ] ] . append ( edges [ i ] [ 1 ] ) NEW_LINE v [ edges [ i ] [ 1 ] ] . append ( edges [ i ] [ 0 ] ) NEW_LINE DEDENT Calculate ( v ) NEW_LINE DEDENT
Travelling Salesman Problem implementation using BackTracking | Python3 implementation of the approach ; Function to find the minimum weight Hamiltonian Cycle ; If last node is reached and it has a link to the starting node i . e the source then keep the minimum value out of the total cost of traversal and " ans " Finally return to check for more possible values ; BACKTRACKING STEP Loop to traverse the adjacency list of currPos node and increasing the count by 1 and cost by graph [ currPos ] [ i ] value ; Mark as visited ; Mark ith node as unvisited ; n is the number of nodes i . e . V ; Boolean array to check if a node has been visited or not ; Mark 0 th node as visited ; Find the minimum weight Hamiltonian Cycle ; ans is the minimum weight Hamiltonian Cycle
V = 4 NEW_LINE answer = [ ] NEW_LINE def tsp ( graph , v , currPos , n , count , cost ) : NEW_LINE INDENT if ( count == n and graph [ currPos ] [ 0 ] ) : NEW_LINE INDENT answer . append ( cost + graph [ currPos ] [ 0 ] ) NEW_LINE return NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( v [ i ] == False and graph [ currPos ] [ i ] ) : NEW_LINE INDENT v [ i ] = True NEW_LINE tsp ( graph , v , i , n , count + 1 , cost + graph [ currPos ] [ i ] ) NEW_LINE v [ i ] = False NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE graph = [ [ 0 , 10 , 15 , 20 ] , [ 10 , 0 , 35 , 25 ] , [ 15 , 35 , 0 , 30 ] , [ 20 , 25 , 30 , 0 ] ] NEW_LINE v = [ False for i in range ( n ) ] NEW_LINE v [ 0 ] = True NEW_LINE tsp ( graph , v , 0 , n , 1 , 0 ) NEW_LINE print ( min ( answer ) ) NEW_LINE DEDENT
Generate all the binary strings of N bits | Function to print the output ; Function to generate all binary strings ; First assign "0" at ith position and try for all other permutations for remaining positions ; And then assign "1" at ith position and try for all other permutations for remaining positions ; Driver Code ; Print all binary strings
def printTheArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def generateAllBinaryStrings ( n , arr , i ) : NEW_LINE INDENT if i == n : NEW_LINE INDENT printTheArray ( arr , n ) NEW_LINE return NEW_LINE DEDENT arr [ i ] = 0 NEW_LINE generateAllBinaryStrings ( n , arr , i + 1 ) NEW_LINE arr [ i ] = 1 NEW_LINE generateAllBinaryStrings ( n , arr , i + 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE arr = [ None ] * n NEW_LINE generateAllBinaryStrings ( n , arr , 0 ) NEW_LINE DEDENT
Combinations where every element appears twice and distance between appearances is equal to the value | Find all combinations that satisfies given constraints ; if all elements are filled , print the solution ; Try all possible combinations for element elem ; if position i and ( i + elem + 1 ) are not occupied in the vector ; place elem at position i and ( i + elem + 1 ) ; recurse for next element ; backtrack ( remove elem from position i and ( i + elem + 1 ) ) ; create a vector of double the size of given number with ; all its elements initialized by 1 ; start from element 1 ; given number
def allCombinationsRec ( arr , elem , n ) : NEW_LINE INDENT if ( elem > n ) : NEW_LINE INDENT for i in ( arr ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT print ( " " ) NEW_LINE return NEW_LINE DEDENT for i in range ( 0 , 2 * n ) : NEW_LINE INDENT if ( arr [ i ] == - 1 and ( i + elem + 1 ) < 2 * n and arr [ i + elem + 1 ] == - 1 ) : NEW_LINE INDENT arr [ i ] = elem NEW_LINE arr [ i + elem + 1 ] = elem NEW_LINE allCombinationsRec ( arr , elem + 1 , n ) NEW_LINE arr [ i ] = - 1 NEW_LINE arr [ i + elem + 1 ] = - 1 NEW_LINE DEDENT DEDENT DEDENT def allCombinations ( n ) : NEW_LINE INDENT arr = [ - 1 ] * ( 2 * n ) NEW_LINE elem = 1 NEW_LINE allCombinationsRec ( arr , elem , n ) NEW_LINE DEDENT n = 3 NEW_LINE allCombinations ( n ) NEW_LINE
Printing all solutions in N | Python program for above approach ; Program to solve N - Queens Problem ; All_rows_filled is a bit mask having all N bits set ; If rowmask will have all bits set , means queen has been placed successfully in all rows and board is displayed ; We extract a bit mask ( safe ) by rowmask , ldmask and rdmask . all set bits of ' safe ' indicates the safe column index for queen placement of this iteration for row index ( row ) . ; Extracts the right - most set bit ( safe column index ) where queen can be placed for this row ; these bit masks will keep updated in each iteration for next row ; Reset right - most set bit to 0 so , next iteration will continue by placing the queen at another safe column index of this row ; Backtracking , replace ' Q ' by ' ; Program to print board ; Driver Code ; n = 4 board size ; Function Call
import math NEW_LINE result = [ ] NEW_LINE def solveBoard ( board , row , rowmask , ldmask , rdmask ) : NEW_LINE INDENT n = len ( board ) NEW_LINE all_rows_filled = ( 1 << n ) - 1 NEW_LINE if ( rowmask == all_rows_filled ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in board : NEW_LINE INDENT for j in range ( len ( i ) ) : NEW_LINE INDENT if i [ j ] == ' Q ' : NEW_LINE INDENT v . append ( j + 1 ) NEW_LINE DEDENT DEDENT DEDENT result . append ( v ) NEW_LINE DEDENT safe = all_rows_filled & ( ~ ( rowmask ldmask rdmask ) ) NEW_LINE while ( safe > 0 ) : NEW_LINE INDENT p = safe & ( - safe ) NEW_LINE col = ( int ) ( math . log ( p ) / math . log ( 2 ) ) NEW_LINE board [ row ] [ col ] = ' Q ' NEW_LINE solveBoard ( board , row + 1 , rowmask | p , ( ldmask p ) << 1 , ( rdmask p ) >> 1 ) NEW_LINE safe = safe & ( safe - 1 ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT board [ row ] [ col ] = ' ▁ ' NEW_LINE DEDENT def printBoard ( board ) : NEW_LINE INDENT for row in board : NEW_LINE INDENT print ( " | " + " | " . join ( row ) + " ▁ " ) NEW_LINE DEDENT DEDENT def main ( ) : NEW_LINE INDENT board = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT row = [ ] NEW_LINE for j in range ( n ) : NEW_LINE INDENT row . append ( ' ▁ ' ) NEW_LINE DEDENT board . append ( row ) NEW_LINE DEDENT rowmask = 0 NEW_LINE ldmask = 0 NEW_LINE rdmask = 0 NEW_LINE row = 0 NEW_LINE result . clear ( ) NEW_LINE solveBoard ( board , row , rowmask , ldmask , rdmask ) NEW_LINE result . sort ( ) NEW_LINE print ( result ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Find all distinct subsets of a given set using BitMasking Approach | Function to find all subsets of given set . Any repeated subset is considered only once in the output ; Run counter i from 000. . 0 to 111. . 1 ; consider each element in the set ; Check if jth bit in the i is set . If the bit is set , we consider jth element from set ; if subset is encountered for the first time If we use set < string > , we can directly insert ; consider every subset ; split the subset and print its elements ; Driver Code
def printPowerSet ( arr , n ) : NEW_LINE INDENT _list = [ ] NEW_LINE for i in range ( 2 ** n ) : NEW_LINE INDENT subset = " " NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( i & ( 1 << j ) ) != 0 : NEW_LINE INDENT subset += str ( arr [ j ] ) + " | " NEW_LINE DEDENT DEDENT if subset not in _list and len ( subset ) > 0 : NEW_LINE INDENT _list . append ( subset ) NEW_LINE DEDENT DEDENT for subset in _list : NEW_LINE INDENT arr = subset . split ( ' ▁ ' ) NEW_LINE for string in arr : NEW_LINE INDENT print ( string , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 12 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE printPowerSet ( arr , n ) NEW_LINE DEDENT
m Coloring Problem | Backtracking | Python3 program for the above approach ; A node class which stores the color and the edges connected to the node ; Create a visited array of n nodes , initialized to zero ; maxColors used till now are 1 as all nodes are painted color 1 ; Do a full BFS traversal from all unvisited starting points ; If the starting point is unvisited , mark it visited and push it in queue ; BFS Travel starts here ; Checking all adjacent nodes to " top " edge in our queue ; IMPORTANT : If the color of the adjacent node is same , increase it by 1 ; If number of colors used shoots m , return 0 ; If the adjacent node is not visited , mark it visited and push it in queue ; Driver code ; Number of colors ; Create a vector of n + 1 nodes of type " node " The zeroth position is just dummy ( 1 to n to be used ) ; Add edges to each node as per given input ; Connect the undirected graph ; Display final answer
from queue import Queue NEW_LINE class node : NEW_LINE INDENT color = 1 NEW_LINE edges = set ( ) NEW_LINE DEDENT def canPaint ( nodes , n , m ) : NEW_LINE INDENT visited = [ 0 for _ in range ( n + 1 ) ] NEW_LINE maxColors = 1 NEW_LINE for _ in range ( 1 , n + 1 ) : NEW_LINE INDENT if visited [ _ ] : NEW_LINE INDENT continue NEW_LINE DEDENT visited [ _ ] = 1 NEW_LINE q = Queue ( ) NEW_LINE q . put ( _ ) NEW_LINE while not q . empty ( ) : NEW_LINE INDENT top = q . get ( ) NEW_LINE for _ in nodes [ top ] . edges : NEW_LINE INDENT if nodes [ top ] . color == nodes [ _ ] . color : NEW_LINE INDENT nodes [ _ ] . color += 1 NEW_LINE DEDENT maxColors = max ( maxColors , max ( nodes [ top ] . color , nodes [ _ ] . color ) ) NEW_LINE if maxColors > m : NEW_LINE INDENT print ( maxColors ) NEW_LINE return 0 NEW_LINE DEDENT if not visited [ _ ] : NEW_LINE INDENT visited [ _ ] = 1 NEW_LINE q . put ( _ ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE graph = [ [ 0 , 1 , 1 , 1 ] , [ 1 , 0 , 1 , 0 ] , [ 1 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 0 ] ] NEW_LINE m = 3 NEW_LINE nodes = [ ] NEW_LINE for _ in range ( n + 1 ) : NEW_LINE INDENT nodes . append ( node ( ) ) NEW_LINE DEDENT for _ in range ( n ) : NEW_LINE INDENT for __ in range ( n ) : NEW_LINE INDENT if graph [ _ ] [ __ ] : NEW_LINE INDENT nodes [ _ ] . edges . add ( _ ) NEW_LINE nodes [ __ ] . edges . add ( __ ) NEW_LINE DEDENT DEDENT DEDENT print ( canPaint ( nodes , n , m ) ) NEW_LINE DEDENT
Fast Doubling method to find the Nth Fibonacci number | Python3 program to find the Nth Fibonacci number using Fast Doubling Method ; Function calculate the N - th fibanacci number using fast doubling method ; Base Condition ; Here a = F ( n ) ; Here b = F ( n + 1 ) ; As F ( 2 n ) = F ( n ) [ 2F ( n + 1 ) F ( n ) ] Here c = F ( 2 n ) ; As F ( 2 n + 1 ) = F ( n ) ^ 2 + F ( n + 1 ) ^ 2 Here d = F ( 2 n + 1 ) ; Check if N is odd or even ; Driver code
MOD = 1000000007 NEW_LINE def FastDoubling ( n , res ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT res [ 0 ] = 0 NEW_LINE res [ 1 ] = 1 NEW_LINE return NEW_LINE DEDENT FastDoubling ( ( n // 2 ) , res ) NEW_LINE a = res [ 0 ] NEW_LINE b = res [ 1 ] NEW_LINE c = 2 * b - a NEW_LINE if ( c < 0 ) : NEW_LINE INDENT c += MOD NEW_LINE DEDENT c = ( a * c ) % MOD NEW_LINE d = ( a * a + b * b ) % MOD NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT res [ 0 ] = c NEW_LINE res [ 1 ] = d NEW_LINE DEDENT else : NEW_LINE INDENT res [ 0 ] = d NEW_LINE res [ 1 ] = c + d NEW_LINE DEDENT DEDENT N = 6 NEW_LINE res = [ 0 ] * 2 NEW_LINE FastDoubling ( N , res ) NEW_LINE print ( res [ 0 ] ) NEW_LINE
Frequency of an integer in the given array using Divide and Conquer | Function to return the frequency of x in the subarray arr [ low ... high ] ; If the subarray is invalid or the element is not found ; If there 's only a single element which is equal to x ; Divide the array into two parts and then find the count of occurrences of x in both the parts ; Driver code
def count ( arr , low , high , x ) : NEW_LINE INDENT if ( ( low > high ) or ( low == high and arr [ low ] != x ) ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( low == high and arr [ low ] == x ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return count ( arr , low , ( low + high ) // 2 , x ) + count ( arr , 1 + ( low + high ) // 2 , high , x ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 30 , 1 , 42 , 5 , 56 , 3 , 56 , 9 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE x = 56 ; NEW_LINE print ( count ( arr , 0 , n - 1 , x ) ) ; NEW_LINE DEDENT
Median of an unsorted array using Quick Select Algorithm | Python3 program to find median of an array ; Returns the correct position of pivot element ; Picks a random pivot element between l and r and partitions arr [ l . . r ] around the randomly picked element using partition ( ) ; Utility function to find median ; if l < r ; Find the partition index ; If partition index = k , then we found the median of odd number element in arr [ ] ; If index = k - 1 , then we get a & b as middle element of arr [ ] ; If partitionIndex >= k then find the index in first half of the arr [ ] ; If partitionIndex <= k then find the index in second half of the arr [ ] ; Function to find Median ; If n is odd ; If n is even ; Print the Median of arr [ ] ; Driver code
import random NEW_LINE a , b = None , None ; NEW_LINE def Partition ( arr , l , r ) : NEW_LINE INDENT lst = arr [ r ] ; i = l ; j = l ; NEW_LINE while ( j < r ) : NEW_LINE INDENT if ( arr [ j ] < lst ) : NEW_LINE INDENT arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] ; NEW_LINE i += 1 ; NEW_LINE DEDENT j += 1 ; NEW_LINE DEDENT arr [ i ] , arr [ r ] = arr [ r ] , arr [ i ] ; NEW_LINE return i ; NEW_LINE DEDENT def randomPartition ( arr , l , r ) : NEW_LINE INDENT n = r - l + 1 ; NEW_LINE pivot = random . randrange ( 1 , 100 ) % n ; NEW_LINE arr [ l + pivot ] , arr [ r ] = arr [ r ] , arr [ l + pivot ] ; NEW_LINE return Partition ( arr , l , r ) ; NEW_LINE DEDENT def MedianUtil ( arr , l , r , k , a1 , b1 ) : NEW_LINE INDENT global a , b ; NEW_LINE if ( l <= r ) : NEW_LINE INDENT partitionIndex = randomPartition ( arr , l , r ) ; NEW_LINE if ( partitionIndex == k ) : NEW_LINE INDENT b = arr [ partitionIndex ] ; NEW_LINE if ( a1 != - 1 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT DEDENT elif ( partitionIndex == k - 1 ) : NEW_LINE INDENT a = arr [ partitionIndex ] ; NEW_LINE if ( b1 != - 1 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT DEDENT if ( partitionIndex >= k ) : NEW_LINE INDENT return MedianUtil ( arr , l , partitionIndex - 1 , k , a , b ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return MedianUtil ( arr , partitionIndex + 1 , r , k , a , b ) ; NEW_LINE DEDENT DEDENT return ; NEW_LINE DEDENT def findMedian ( arr , n ) : NEW_LINE INDENT global a ; NEW_LINE global b ; NEW_LINE a = - 1 ; NEW_LINE b = - 1 ; NEW_LINE if ( n % 2 == 1 ) : NEW_LINE INDENT MedianUtil ( arr , 0 , n - 1 , n // 2 , a , b ) ; NEW_LINE ans = b ; NEW_LINE DEDENT else : NEW_LINE INDENT MedianUtil ( arr , 0 , n - 1 , n // 2 , a , b ) ; NEW_LINE ans = ( a + b ) // 2 ; NEW_LINE DEDENT print ( " Median ▁ = ▁ " , ans ) ; NEW_LINE DEDENT arr = [ 12 , 3 , 5 , 7 , 4 , 19 , 26 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE findMedian ( arr , n ) ; NEW_LINE
Largest number N which can be reduced to 0 in K steps | Utility function to return the first digit of a number . ; Remove last digit from number till only one digit is left ; return the first digit ; Utility function that returns the count of numbers written down when starting from n ; Function to find the largest number N which can be reduced to 0 in K steps ; Get the sequence length of the mid point ; Until k sequence length is reached ; Update mid point ; Get count of the new mid point ; Update right to mid ; Update left to mid ; Increment mid point by one while count is equal to k to get the maximum value of mid point ; Driver Code
def firstDigit ( n ) : NEW_LINE INDENT while ( n >= 10 ) : NEW_LINE INDENT n //= 10 ; NEW_LINE DEDENT return n ; NEW_LINE DEDENT def getCount ( n ) : NEW_LINE INDENT count = 1 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT leadDigit = firstDigit ( n ) ; NEW_LINE n -= leadDigit ; NEW_LINE count += 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def getLargestNumber ( k ) : NEW_LINE INDENT left = k ; NEW_LINE right = k * 10 ; NEW_LINE mid = ( left + right ) // 2 ; NEW_LINE length = getCount ( mid ) ; NEW_LINE while ( length != k ) : NEW_LINE INDENT mid = ( left + right ) // 2 ; NEW_LINE length = getCount ( mid ) ; NEW_LINE if ( length > k ) : NEW_LINE INDENT right = mid ; NEW_LINE DEDENT else : NEW_LINE INDENT left = mid ; NEW_LINE DEDENT DEDENT while ( length == k ) : NEW_LINE INDENT if ( length != getCount ( mid + 1 ) ) : NEW_LINE INDENT break ; NEW_LINE DEDENT mid += 1 ; NEW_LINE DEDENT return mid ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT k = 3 ; NEW_LINE print ( getLargestNumber ( k ) ) ; NEW_LINE DEDENT
Check if point ( X , Y ) can be reached from origin ( 0 , 0 ) with jump of 1 and N perpendicularly simultaneously | Function to check if ( X , Y ) is reachable from ( 0 , 0 ) using the jumps of given type ; Case where source & destination are the same ; Check for even N ( X , Y ) is reachable or not ; If N is odd and parity of X and Y is different return , no valid sequence of jumps exist ; Driver Code
def checkReachability ( N , X , Y ) : NEW_LINE INDENT if ( X == 0 and Y == 0 ) : NEW_LINE INDENT return " YES " NEW_LINE DEDENT if ( N % 2 == 0 ) : NEW_LINE INDENT return " YES " NEW_LINE DEDENT else : NEW_LINE INDENT if ( X % 2 != Y % 2 ) : NEW_LINE INDENT return " NO " NEW_LINE DEDENT else : NEW_LINE INDENT return " YES " NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE X = 5 NEW_LINE Y = 4 NEW_LINE print ( checkReachability ( N , X , Y ) ) NEW_LINE DEDENT
Find three vertices in an N | Function to find three vertices that subtends an angle closest to A ; Stores the closest angle to A ; Stores the count of edge which subtend an angle of A ; Iterate in the range [ 1 , N - 2 ] ; Stores the angle subtended ; If absolute ( angle - A ) is less than absolute ( mi - A ) ; Update angle to mi , and also update i to ans ; Pr the vertices ; Driver Code
import math NEW_LINE import sys NEW_LINE def closestsAngle ( N , A ) : NEW_LINE INDENT mi = sys . maxsize NEW_LINE ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT angle = 180.0 * i / N NEW_LINE if ( math . fabs ( angle - A ) < math . fabs ( mi - A ) ) : NEW_LINE INDENT mi = angle NEW_LINE i += 1 NEW_LINE ans = i NEW_LINE DEDENT DEDENT print ( 2 , 1 , 2 + ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE A = 15 NEW_LINE closestsAngle ( N , A ) NEW_LINE DEDENT
Area of a triangle with two vertices at midpoints of opposite sides of a square and the other vertex lying on vertex of a square | Python3 program for the above approach ; Function to find the area of the triangle that inscribed in square ; Stores the length of the first side of triangle ; Stores the length of the second side of triangle ; Stores the length of the third side of triangle ; Stores the area of the triangle ; Return the resultant area ; Driver Code
from math import sqrt NEW_LINE def areaOftriangle ( side ) : NEW_LINE INDENT a = sqrt ( pow ( side / 2 , 2 ) + pow ( side / 2 , 2 ) ) NEW_LINE b = sqrt ( pow ( side , 2 ) + pow ( side / 2 , 2 ) ) NEW_LINE c = sqrt ( pow ( side , 2 ) + pow ( side / 2 , 2 ) ) NEW_LINE s = ( a + b + c ) / 2 NEW_LINE area = sqrt ( s * ( s - a ) * ( s - b ) * ( s - c ) ) NEW_LINE return round ( area , 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE print ( areaOftriangle ( N ) ) NEW_LINE DEDENT
Equation of a straight line with perpendicular distance D from origin and an angle A between the perpendicular from origin and x | Python3 program for the approach ; Function to find equation of a line whose distance from origin and angle made by the perpendicular from origin with x - axis is given ; Convert angle from degree to radian ; Handle the special case ; Calculate the sin and cos of angle ; Print the equation of the line ; Given Input ; Function Call
import math NEW_LINE def findLine ( distance , degree ) : NEW_LINE INDENT x = degree * 3.14159 / 180 NEW_LINE if ( degree > 90 ) : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE return NEW_LINE DEDENT result_1 = math . sin ( x ) NEW_LINE result_2 = math . cos ( x ) NEW_LINE print ( ' % .2f ' % result_2 , " x ▁ + " , ' % .2f ' % result_1 , " y ▁ = ▁ " , distance , sep = " " ) NEW_LINE DEDENT D = 10 NEW_LINE A = 30 NEW_LINE findLine ( D , A ) NEW_LINE
Count number of coordinates from an array satisfying the given conditions | Function to count the number of coordinates from a given set that satisfies the given conditions ; Stores the count of central points ; Find all possible pairs ; Initialize variables c1 , c2 , c3 , c4 to define the status of conditions ; Stores value of each point ; Check the conditions for each point by generating all possible pairs ; If arr [ j ] [ 0 ] > x and arr [ j ] [ 1 ] == y ; If arr [ j ] [ 0 ] < x and arr [ j ] [ 1 ] = = y ; If arr [ j ] [ 1 ] > y and arr [ j ] [ 0 ] == x ; If arr [ j ] [ 1 ] < y and arr [ j ] [ 0 ] = = x ; If all conditions satisfy then point is central point ; Increment the count by 1 ; Return the count ; Driver Code
def centralPoints ( arr , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT c1 = 0 NEW_LINE c2 = 0 NEW_LINE c3 = 0 NEW_LINE c4 = 0 NEW_LINE x = arr [ i ] [ 0 ] NEW_LINE y = arr [ i ] [ 1 ] NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( arr [ j ] [ 0 ] > x and arr [ j ] [ 1 ] == y ) : NEW_LINE INDENT c1 = 1 NEW_LINE DEDENT if ( arr [ j ] [ 1 ] > y and arr [ j ] [ 0 ] == x ) : NEW_LINE INDENT c2 = 1 NEW_LINE DEDENT if ( arr [ j ] [ 0 ] < x and arr [ j ] [ 1 ] == y ) : NEW_LINE INDENT c3 = 1 NEW_LINE DEDENT if ( arr [ j ] [ 1 ] < y and arr [ j ] [ 0 ] == x ) : NEW_LINE INDENT c4 = 1 NEW_LINE DEDENT DEDENT if ( c1 + c2 + c3 + c4 == 4 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 0 ] , [ 2 , 0 ] , [ 1 , 1 ] , [ 1 , - 1 ] ] NEW_LINE N = len ( arr ) NEW_LINE print ( centralPoints ( arr , N ) ) ; NEW_LINE DEDENT
Displacement from origin after N moves of given distances in specified directions | Python3 program for the above approach ; Function to find the displacement from the origin and direction after performing the given set of moves ; Stores the distances travelled in the directions North , South , East , and West respectively ; Store the initial position of robot ; Traverse the array B [ ] ; If the current direction is North ; If the current direction is South ; If the current direction is East ; If the current direction is West ; Stores the total vertical displacement ; Stores the total horizontal displacement ; Find the displacement ; Print the displacement and direction after N moves ; Driver Code
from math import sqrt , floor NEW_LINE def finalPosition ( a , b , M ) : NEW_LINE INDENT n = 0 NEW_LINE s = 0 NEW_LINE e = 0 NEW_LINE w = 0 NEW_LINE p = ' N ' NEW_LINE for i in range ( M ) : NEW_LINE INDENT if ( p == ' N ' ) : NEW_LINE INDENT if ( a [ i ] == ' U ' ) : NEW_LINE INDENT p = ' N ' NEW_LINE n = n + b [ i ] NEW_LINE DEDENT elif ( a [ i ] == ' D ' ) : NEW_LINE INDENT p = ' S ' NEW_LINE s = s + b [ i ] NEW_LINE DEDENT elif ( a [ i ] == ' R ' ) : NEW_LINE INDENT p = ' E ' NEW_LINE e = e + b [ i ] NEW_LINE DEDENT elif ( a [ i ] == ' L ' ) : NEW_LINE INDENT p = ' W ' NEW_LINE w = w + b [ i ] NEW_LINE DEDENT DEDENT elif ( p == ' S ' ) : NEW_LINE INDENT if ( a [ i ] == ' U ' ) : NEW_LINE INDENT p = ' S ' NEW_LINE s = s + b [ i ] NEW_LINE DEDENT elif ( a [ i ] == ' D ' ) : NEW_LINE INDENT p = ' N ' NEW_LINE n = n + b [ i ] NEW_LINE DEDENT elif ( a [ i ] == ' R ' ) : NEW_LINE INDENT p = ' W ' NEW_LINE w = w + b [ i ] NEW_LINE DEDENT elif ( a [ i ] == ' L ' ) : NEW_LINE INDENT p = ' E ' NEW_LINE e = e + b [ i ] NEW_LINE DEDENT DEDENT elif ( p == ' E ' ) : NEW_LINE INDENT if ( a [ i ] == ' U ' ) : NEW_LINE INDENT p = ' E ' NEW_LINE e = e + b [ i ] NEW_LINE DEDENT elif ( a [ i ] == ' D ' ) : NEW_LINE INDENT p = ' W ' NEW_LINE w = w + b [ i ] NEW_LINE DEDENT elif ( a [ i ] == ' R ' ) : NEW_LINE INDENT p = ' S ' NEW_LINE s = s + b [ i ] NEW_LINE DEDENT elif ( a [ i ] == ' L ' ) : NEW_LINE INDENT p = ' N ' NEW_LINE n = n + b [ i ] NEW_LINE DEDENT DEDENT elif ( p == ' W ' ) : NEW_LINE INDENT if ( a [ i ] == ' U ' ) : NEW_LINE INDENT p = ' W ' NEW_LINE w = w + b [ i ] NEW_LINE DEDENT elif ( a [ i ] == ' D ' ) : NEW_LINE INDENT p = ' E ' NEW_LINE e = e + b [ i ] NEW_LINE DEDENT elif ( a [ i ] == ' R ' ) : NEW_LINE INDENT p = ' N ' NEW_LINE n = n + b [ i ] NEW_LINE DEDENT elif ( a [ i ] == ' L ' ) : NEW_LINE INDENT p = ' S ' NEW_LINE s = s + b [ i ] NEW_LINE DEDENT DEDENT DEDENT ver_disp = n - s NEW_LINE hor_disp = e - w NEW_LINE displacement = floor ( sqrt ( ( ver_disp * ver_disp ) + ( hor_disp * hor_disp ) ) + 1 ) NEW_LINE print ( displacement , p ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ ' U ' , ' R ' , ' R ' , ' R ' , ' R ' ] NEW_LINE B = [ 1 , 1 , 1 , 1 , 0 ] NEW_LINE N = len ( A ) NEW_LINE finalPosition ( A , B , N ) NEW_LINE DEDENT
Program to find Length of Latus Rectum of an Ellipse | Function to calculate the length of the latus rectum of an ellipse ; Length of major axis ; Length of minor axis ; Length of the latus rectum ; Driver Code ; Given lengths of semi - major and semi - minor axis ; Function call to calculate length of the latus rectum of a ellipse
def lengthOfLatusRectum ( A , B ) : NEW_LINE INDENT major = 2.0 * A NEW_LINE minor = 2.0 * B NEW_LINE latus_rectum = ( minor * minor ) / major NEW_LINE return latus_rectum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = 3.0 NEW_LINE B = 2.0 NEW_LINE print ( ' % .5f ' % lengthOfLatusRectum ( A , B ) ) NEW_LINE DEDENT
Program to find slant height of cone and pyramid | Python 3 program for the above approach ; Function to calculate slant height of a cone ; Store the slant height of cone ; Print the result ; Function to find the slant height of a pyramid ; Store the slant height of pyramid ; Print the result ; Driver Code ; Dimensions of Cone ; Function Call for slant height of Cone ; Dimensions of Pyramid ; Function to calculate slant height of a pyramid
from math import sqrt , pow NEW_LINE def coneSlantHeight ( cone_h , cone_r ) : NEW_LINE INDENT slant_height_cone = sqrt ( pow ( cone_h , 2 ) + pow ( cone_r , 2 ) ) NEW_LINE print ( " Slant ▁ height ▁ of ▁ cone ▁ is : " , slant_height_cone ) NEW_LINE DEDENT def pyramidSlantHeight ( pyramid_h , pyramid_s ) : NEW_LINE INDENT slant_height_pyramid = sqrt ( pow ( pyramid_s / 2 , 2 ) + pow ( pyramid_h , 2 ) ) NEW_LINE print ( " Slant ▁ height ▁ of ▁ pyramid ▁ is : " , " { : . 5f } " . format ( slant_height_pyramid ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT H1 = 4.5 NEW_LINE R = 6 NEW_LINE coneSlantHeight ( H1 , R ) ; NEW_LINE H2 = 4 NEW_LINE S = 4.8 NEW_LINE pyramidSlantHeight ( H2 , S ) NEW_LINE DEDENT
Program to find the length of Latus Rectum of a Parabola | Python 3 program for the above approach ; Function to calculate distance between two points ; Calculating distance ; Function to calculate length of the latus rectum of a parabola ; Stores the co - ordinates of the vertex of the parabola ; Stores the co - ordinates of the focus of parabola ; Print the distance between focus and vertex ; Driver Code ; Given a , b & c ; Function call
from math import sqrt NEW_LINE def distance ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT return sqrt ( ( x2 - x1 ) * ( x2 - x1 ) + ( y2 - y1 ) * ( y2 - y1 ) ) NEW_LINE DEDENT def lengthOfLatusRectum ( a , b , c ) : NEW_LINE INDENT vertex = [ ( - b / ( 2 * a ) ) , ( ( ( 4 * a * c ) - ( b * b ) ) / ( 4 * a ) ) ] NEW_LINE focus = [ ( - b / ( 2 * a ) ) , ( ( ( 4 * a * c ) - ( b * b ) + 1 ) / ( 4 * a ) ) ] NEW_LINE print ( " { : . 6f } " . format ( 4 * distance ( focus [ 0 ] , focus [ 1 ] , vertex [ 0 ] , vertex [ 1 ] ) ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 3 NEW_LINE b = 5 NEW_LINE c = 1 NEW_LINE lengthOfLatusRectum ( a , b , c ) NEW_LINE DEDENT
Program to convert polar co | Python 3 program for the above approach ; Function to convert degree to radian ; Function to convert the polar coordinate to cartesian ; Convert degerees to radian ; Applying the formula : x = rcos ( theata ) , y = rsin ( theta ) ; Print cartesian coordinates ; Driver Code ; Given polar coordinates ; Function to convert polar coordinates to equivalent cartesian coordinates
import math NEW_LINE def ConvertDegToRad ( degree ) : NEW_LINE INDENT pi = 3.14159 NEW_LINE return ( degree * ( pi / 180.0 ) ) NEW_LINE DEDENT def ConvertToCartesian ( polar ) : NEW_LINE INDENT polar [ 1 ] = ConvertDegToRad ( polar [ 1 ] ) NEW_LINE cartesian = [ polar [ 0 ] * math . cos ( polar [ 1 ] ) , polar [ 0 ] * math . sin ( polar [ 1 ] ) ] NEW_LINE print ( ' % .3f ' % cartesian [ 0 ] , ' % .3f ' % cartesian [ 1 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT polar = [ 1.4142 , 45 ] NEW_LINE ConvertToCartesian ( polar ) NEW_LINE DEDENT
Distance between orthocenter and circumcenter of a right | Python3 program for the above approach ; Function to calculate Euclidean distance between the points p1 and p2 ; Stores x coordinates of both points ; Stores y coordinates of both points ; Return the Euclid distance using distance formula ; Function to find orthocenter of the right angled triangle ; Find the length of the three sides ; Orthocenter will be the vertex opposite to the largest side ; Function to find the circumcenter of right angle triangle ; Circumcenter will be located at center of hypotenuse ; If AB is the hypotenuse ; If BC is the hypotenuse ; If AC is the hypotenuse ; Function to find distance between orthocenter and circumcenter ; Find circumcenter ; Find orthocenter ; Find the distance between the orthocenter and circumcenter ; Print distance between orthocenter and circumcenter ; Given coordinates A , B , and C ; Function Call
import math NEW_LINE def distance ( p1 , p2 ) : NEW_LINE INDENT x1 , x2 = p1 [ 0 ] , p2 [ 0 ] NEW_LINE y1 , y2 = p1 [ 1 ] , p2 [ 1 ] NEW_LINE return int ( math . sqrt ( pow ( x2 - x1 , 2 ) + pow ( y2 - y1 , 2 ) ) ) NEW_LINE DEDENT def find_orthocenter ( A , B , C ) : NEW_LINE INDENT AB = distance ( A , B ) NEW_LINE BC = distance ( B , C ) NEW_LINE CA = distance ( C , A ) NEW_LINE if ( AB > BC and AB > CA ) : NEW_LINE INDENT return C NEW_LINE DEDENT if ( BC > AB and BC > CA ) : NEW_LINE INDENT return A NEW_LINE DEDENT return B NEW_LINE DEDENT def find_circumcenter ( A , B , C ) : NEW_LINE INDENT AB = distance ( A , B ) NEW_LINE BC = distance ( B , C ) NEW_LINE CA = distance ( C , A ) NEW_LINE if ( AB > BC and AB > CA ) : NEW_LINE INDENT return ( ( A [ 0 ] + B [ 0 ] ) // 2 , ( A [ 1 ] + B [ 1 ] ) // 2 ) NEW_LINE DEDENT if ( BC > AB and BC > CA ) : NEW_LINE INDENT return ( ( B [ 0 ] + C [ 0 ] ) // 2 , ( B [ 1 ] + C [ 1 ] ) // 2 ) NEW_LINE DEDENT return ( ( C [ 0 ] + A [ 0 ] ) // 2 , ( C [ 1 ] + A [ 1 ] ) // 2 ) NEW_LINE DEDENT def findDistance ( A , B , C ) : NEW_LINE INDENT circumcenter = find_circumcenter ( A , B , C ) NEW_LINE orthocenter = find_orthocenter ( A , B , C ) NEW_LINE distance_between = distance ( circumcenter , orthocenter ) NEW_LINE print ( distance_between ) NEW_LINE DEDENT A = [ 0 , 0 ] NEW_LINE B = [ 6 , 0 ] NEW_LINE C = [ 0 , 8 ] NEW_LINE findDistance ( A , B , C ) NEW_LINE
Generate all integral points lying inside a rectangle | Python3 program to implement the above approach ; Function to generate coordinates lying within the rectangle ; Store all possible coordinates that lie within the rectangle ; Stores the number of possible coordinates that lie within the rectangle ; Generate all possible coordinates ; Generate all possible X - coordinates ; Generate all possible Y - coordinates ; If coordinates ( X , Y ) has not been generated already ; Insert the coordinates ( X , Y ) ; Print the coordinates ; Driver code ; Rectangle dimensions
import time NEW_LINE import random NEW_LINE random . seed ( time . time ( ) ) NEW_LINE def generatePoints ( L , W ) : NEW_LINE INDENT hash = { } NEW_LINE total = ( L * W ) NEW_LINE for i in range ( total ) : NEW_LINE INDENT X = random . randint ( 0 , L ) % L NEW_LINE Y = random . randint ( 0 , W ) % W NEW_LINE while ( ( X , Y ) in hash ) : NEW_LINE INDENT X = random . randint ( 0 , L ) % L NEW_LINE Y = random . randint ( 0 , W ) % W NEW_LINE DEDENT hash [ ( X , Y ) ] = 1 NEW_LINE DEDENT for points in sorted ( hash ) : NEW_LINE INDENT print ( " ( " , points [ 0 ] , " , ▁ " , points [ 1 ] , " ) ▁ " , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , W = 3 , 2 NEW_LINE generatePoints ( L , W ) NEW_LINE DEDENT
Count triangles required to form a House of Cards of height N | Function to find required number of triangles ; Driver Code ; Function call
def noOfTriangles ( n ) : NEW_LINE INDENT return n * ( n + 2 ) * ( 2 * n + 1 ) // 8 NEW_LINE DEDENT n = 3 NEW_LINE print ( noOfTriangles ( n ) ) NEW_LINE
Check if N contains all digits as K in base B | Python3 program for the above approach ; Function to print the number of digits ; Calculate log using base change property and then take its floor and then add 1 ; Return the output ; Function that returns true if n contains all one 's in base b ; Calculate the sum ; Given number N ; Given base B ; Given digit K ; Function call
import math NEW_LINE def findNumberOfDigits ( n , base ) : NEW_LINE INDENT dig = ( math . floor ( math . log ( n ) / math . log ( base ) ) + 1 ) NEW_LINE return dig NEW_LINE DEDENT def isAllKs ( n , b , k ) : NEW_LINE INDENT len = findNumberOfDigits ( n , b ) NEW_LINE sum = k * ( 1 - pow ( b , len ) ) / ( 1 - b ) NEW_LINE return sum == N NEW_LINE DEDENT N = 13 NEW_LINE B = 3 NEW_LINE K = 1 NEW_LINE if ( isAllKs ( N , B , K ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Check if a right | Function to check if right - angled triangle can be formed by the given coordinates ; Calculate the sides ; Check Pythagoras Formula ; Driver code
def checkRightAngled ( X1 , Y1 , X2 , Y2 , X3 , Y3 ) : NEW_LINE INDENT A = ( int ( pow ( ( X2 - X1 ) , 2 ) ) + int ( pow ( ( Y2 - Y1 ) , 2 ) ) ) NEW_LINE B = ( int ( pow ( ( X3 - X2 ) , 2 ) ) + int ( pow ( ( Y3 - Y2 ) , 2 ) ) ) NEW_LINE C = ( int ( pow ( ( X3 - X1 ) , 2 ) ) + int ( pow ( ( Y3 - Y1 ) , 2 ) ) ) NEW_LINE if ( ( A > 0 and B > 0 and C > 0 ) and ( A == ( B + C ) or B == ( A + C ) or C == ( A + B ) ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X1 = 0 ; X2 = 0 ; X3 = 9 ; NEW_LINE Y1 = 2 ; Y2 = 14 ; Y3 = 2 ; NEW_LINE checkRightAngled ( X1 , Y1 , X2 , Y2 , X3 , Y3 ) NEW_LINE DEDENT
Count of intersections of M line segments with N vertical lines in XY plane | Function to create prefix sum array ; Initialize the prefix array to remove garbage values ; Marking the occurances of vertical lines ; Creating the prefix array ; Function that returns the count of total intersection ; ans is the number of points of intersection of the line segments with the vertical lines ; Index mapping ; we don 't consider a vertical line segment because even if it falls on a vertical line then it just touches it and not intersects. ; We have assumed that x1 will be left and x2 right but if not then just swap ; Number of vertical lines ; Number of line segments ; Format : x1 , y1 , x2 , y2 ; First create the prefix array ; Print the total number of intersections
def createPrefixArray ( n , arr , prefSize , pref ) : NEW_LINE INDENT for i in range ( prefSize ) : NEW_LINE INDENT pref [ i ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT x = arr [ i ] + 1000000 NEW_LINE pref [ x ] += 1 NEW_LINE DEDENT for i in range ( 1 , prefSize ) : NEW_LINE INDENT pref [ i ] += pref [ i - 1 ] NEW_LINE DEDENT DEDENT def pointOfIntersection ( m , segments , size , pref ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT x1 = segments [ i ] [ 0 ] NEW_LINE x2 = segments [ i ] [ 2 ] NEW_LINE x1 = x1 + 1000000 NEW_LINE x2 = x2 + 1000000 NEW_LINE if ( x1 != x2 ) : NEW_LINE INDENT if ( x1 > x2 ) : NEW_LINE INDENT x1 , x2 = x2 , x1 NEW_LINE DEDENT Occ_Till_Right = pref [ x2 - 1 ] NEW_LINE Occ_Till_Left = pref [ x1 ] NEW_LINE ans += ( Occ_Till_Right - Occ_Till_Left ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT N = 4 NEW_LINE M = 8 NEW_LINE size = 2000000 + 2 NEW_LINE pref = [ 0 ] * size NEW_LINE lines = [ - 5 , - 3 , 2 , 3 ] NEW_LINE segments = [ [ - 2 , 5 , 5 , - 6 ] , [ - 5 , - 2 , - 3 , - 5 ] , [ - 2 , 3 , - 6 , 1 ] , [ - 1 , - 3 , 4 , 2 ] , [ 2 , 5 , 2 , 1 ] , [ 4 , 5 , 4 , - 5 ] , [ - 2 , - 4 , 5 , 3 ] , [ 1 , 2 , - 2 , 1 ] ] NEW_LINE createPrefixArray ( N , lines , size , pref ) NEW_LINE print ( pointOfIntersection ( M , segments , size , pref ) ) NEW_LINE
Count of rectangles possible from N and M straight lines parallel to X and Y axis respectively | Function to calculate number of rectangles ; Total number of ways to select two lines parallel to X axis ; Total number of ways to select two lines parallel to Y axis ; Total number of rectangles ; Driver code
def count_rectangles ( N , M ) : NEW_LINE INDENT p_x = ( N * ( N - 1 ) ) // 2 NEW_LINE p_y = ( M * ( M - 1 ) ) // 2 NEW_LINE return p_x * p_y NEW_LINE DEDENT N = 3 NEW_LINE M = 6 NEW_LINE print ( count_rectangles ( N , M ) ) NEW_LINE
Angle between a Pair of Lines in 3D | Python3 program for the above approach ; Function to find the angle between the two lines ; Find direction ratio of line AB ; Find direction ratio of line BC ; Find the dotProduct of lines AB & BC ; Find magnitude of line AB and BC ; Find the cosine of the angle formed by line AB and BC ; Find angle in radian ; Print angle ; Driver Code ; Given coordinates Points A ; Points B ; Points C ; Function Call
import math NEW_LINE def calculateAngle ( x1 , y1 , z1 , x2 , y2 , z2 , x3 , y3 , z3 ) : NEW_LINE INDENT ABx = x1 - x2 ; NEW_LINE ABy = y1 - y2 ; NEW_LINE ABz = z1 - z2 ; NEW_LINE BCx = x3 - x2 ; NEW_LINE BCy = y3 - y2 ; NEW_LINE BCz = z3 - z2 ; NEW_LINE dotProduct = ( ABx * BCx + ABy * BCy + ABz * BCz ) ; NEW_LINE magnitudeAB = ( ABx * ABx + ABy * ABy + ABz * ABz ) ; NEW_LINE magnitudeBC = ( BCx * BCx + BCy * BCy + BCz * BCz ) ; NEW_LINE angle = dotProduct ; NEW_LINE angle /= math . sqrt ( magnitudeAB * magnitudeBC ) ; NEW_LINE angle = ( angle * 180 ) / 3.14 ; NEW_LINE print ( round ( abs ( angle ) , 4 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x1 , y1 , z1 = 1 , 3 , 3 ; NEW_LINE x2 , y2 , z2 = 3 , 4 , 5 ; NEW_LINE x3 , y3 , z3 = 5 , 6 , 9 ; NEW_LINE calculateAngle ( x1 , y1 , z1 , x2 , y2 , z2 , x3 , y3 , z3 ) ; NEW_LINE DEDENT
Distance between end points of Hour and minute hand at given time | Python3 implementation to find the distance between the end points of the hour and minute hand ; Function to find the angle between Hour hand and minute hand ; Validate the input ; Calculate the angles moved by hour and minute hands with reference to 12 : 00 ; Find the difference between two angles ; Return the smaller angle of two possible angles ; Function to calculate cos value of angle c ; Converting degrees to radian ; Maps the sum along the series ; Holds the actual value of sin ( n ) ; Function to distance between the endpoints of the hour and minute hand ; Time ; Length of hour hand ; Length of minute hand ; calling Function for finding angle between hour hand and minute hand ; Function for finding distance between end points of minute hand and hour hand
import math NEW_LINE def calcAngle ( h , m ) : NEW_LINE INDENT if ( h < 0 or m < 0 or h > 12 or m > 60 ) : NEW_LINE INDENT print ( " Wrong ▁ input " ) NEW_LINE DEDENT if ( h == 12 ) : NEW_LINE INDENT h = 0 NEW_LINE DEDENT if ( m == 60 ) : NEW_LINE INDENT m = 0 NEW_LINE DEDENT hour_angle = 0.5 * ( h * 60 + m ) NEW_LINE minute_angle = 6 * m NEW_LINE angle = abs ( hour_angle - minute_angle ) NEW_LINE angle = min ( 360 - angle , angle ) NEW_LINE return angle NEW_LINE DEDENT def cal_cos ( n ) : NEW_LINE INDENT accuracy = 0.0001 NEW_LINE n = n * ( 3.142 / 180.0 ) NEW_LINE x1 = 1 NEW_LINE cosx = x1 NEW_LINE cosval = math . cos ( n ) NEW_LINE i = 1 NEW_LINE while True : NEW_LINE INDENT denominator = 2 * i * ( 2 * i - 1 ) NEW_LINE x1 = - x1 * n * n / denominator NEW_LINE cosx = cosx + x1 NEW_LINE i = i + 1 NEW_LINE if accuracy > math . fabs ( cosval - cosx ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return cosx NEW_LINE DEDENT def distanceEndpoints ( a , b , c ) : NEW_LINE INDENT angle = cal_cos ( c ) NEW_LINE return math . sqrt ( ( a * a ) + ( b * b ) - 2 * a * b * angle ) NEW_LINE DEDENT hour = 3 NEW_LINE Min = 30 NEW_LINE hourHand = 3 NEW_LINE minHand = 4 NEW_LINE angle = calcAngle ( hour , Min ) NEW_LINE distance = distanceEndpoints ( minHand , hourHand , angle ) NEW_LINE print ( ' % .5f ' % distance ) NEW_LINE
Pentadecagonal Number | Function to find N - th pentadecagonal number ; Formula to calculate nth pentadecagonal number ; Driver code
def Pentadecagonal_num ( n ) : NEW_LINE INDENT return ( 13 * n * n - 11 * n ) / 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( int ( Pentadecagonal_num ( n ) ) ) NEW_LINE n = 10 NEW_LINE print ( int ( Pentadecagonal_num ( n ) ) ) NEW_LINE
Octadecagonal Number | Function to find N - th octadecagonal number ; Formula to calculate nth octadecagonal number ; Driver code
def Octadecagonal_num ( n ) : NEW_LINE INDENT return ( 16 * n * n - 14 * n ) / 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( int ( Octadecagonal_num ( n ) ) ) NEW_LINE n = 10 NEW_LINE print ( int ( Octadecagonal_num ( n ) ) ) NEW_LINE
Icositrigonal Number | Function to find N - th Icositrigonal number ; Formula to calculate nth Icositrigonal number ; Driver code
def IcositrigonalNum ( n ) : NEW_LINE INDENT return ( 21 * n * n - 19 * n ) / 2 ; NEW_LINE DEDENT n = 3 NEW_LINE print ( IcositrigonalNum ( n ) ) NEW_LINE n = 10 NEW_LINE print ( IcositrigonalNum ( n ) ) NEW_LINE
Find the percentage change in the area of a Rectangle | Function to calculate percentage change in area of rectangle ; Driver code
def calculate_change ( length , breadth ) : NEW_LINE INDENT change = 0 NEW_LINE change = length + breadth + ( ( length * breadth ) // 100 ) NEW_LINE return change NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT cL = 20 NEW_LINE cB = - 10 NEW_LINE cA = calculate_change ( cL , cB ) NEW_LINE print ( cA ) NEW_LINE DEDENT
Minimum number of Circular obstacles required to obstruct the path in a Grid | Function to find the minimum number of obstacles required ; Find the minimum rangee required to put obstacles ; Sorting the radius ; If val is less than zero then we have find the number of obstacles required ; Driver code
def solve ( n , m , obstacles , rangee ) : NEW_LINE INDENT val = min ( n , m ) NEW_LINE rangee = sorted ( rangee ) NEW_LINE c = 1 NEW_LINE for i in range ( obstacles - 1 , - 1 , - 1 ) : NEW_LINE INDENT rangee [ i ] = 2 * rangee [ i ] NEW_LINE val -= rangee [ i ] NEW_LINE if ( val <= 0 ) : NEW_LINE INDENT return c NEW_LINE DEDENT else : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT if ( val > 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT n = 4 NEW_LINE m = 5 NEW_LINE obstacles = 3 NEW_LINE rangee = [ 1.0 , 1.25 , 1.15 ] NEW_LINE print ( solve ( n , m , obstacles , rangee ) ) NEW_LINE
Program to calculate area of a rhombus whose one side and diagonal are given | function to calculate the area of the rhombus ; Second diagonal ; area of rhombus ; return the area ; driver code
def area ( d1 , a ) : NEW_LINE INDENT d2 = ( 4 * ( a ** 2 ) - d1 ** 2 ) ** 0.5 NEW_LINE area = 0.5 * d1 * d2 NEW_LINE return ( area ) NEW_LINE DEDENT d = 7.07 NEW_LINE a = 5 NEW_LINE print ( area ( d , a ) ) NEW_LINE
Check whether two points ( x1 , y1 ) and ( x2 , y2 ) lie on same side of a given line or not | Function to check if two points lie on the same side or not ; fx1 = 0 Variable to store a * x1 + b * y1 - c fx2 = 0 Variable to store a * x2 + b * y2 - c ; If fx1 and fx2 have same sign ; Driver code
def pointsAreOnSameSideOfLine ( a , b , c , x1 , y1 , x2 , y2 ) : NEW_LINE INDENT fx1 = a * x1 + b * y1 - c NEW_LINE fx2 = a * x2 + b * y2 - c NEW_LINE if ( ( fx1 * fx2 ) > 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT a , b , c = 1 , 1 , 1 NEW_LINE x1 , y1 = 1 , 1 NEW_LINE x2 , y2 = 2 , 1 NEW_LINE if ( pointsAreOnSameSideOfLine ( a , b , c , x1 , y1 , x2 , y2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Percentage increase in volume of the cube if a side of cube is increased by a given percentage | Python program to find percentage increase in the volume of the cube if a side of cube is increased by a given percentage ; Driver code
def newvol ( x ) : NEW_LINE INDENT print ( " percentage ▁ increase " " in ▁ the ▁ volume ▁ of ▁ the ▁ cube ▁ is ▁ " , ( ( x ** ( 3 ) ) / 10000 + 3 * x + ( 3 * ( x ** ( 2 ) ) ) / 100 ) , " % " ) ; NEW_LINE DEDENT x = 10 ; NEW_LINE newvol ( x ) ; NEW_LINE
Number of triangles formed by joining vertices of n | Function to find the number of triangles ; print the number of triangles having two side common ; print the number of triangles having no side common ; initialize the number of sides of a polygon
def findTriangles ( n ) : NEW_LINE INDENT num = n NEW_LINE print ( num , end = " ▁ " ) NEW_LINE print ( num * ( num - 4 ) * ( num - 5 ) // 6 ) NEW_LINE DEDENT n = 6 ; NEW_LINE findTriangles ( n ) NEW_LINE
Find the radii of the circles which are lined in a row , and distance between the centers of first and last circle is given | Python program to find radii of the circles which are lined in a row and distance between the centers of first and last circle is given ; Driver code
def radius ( n , d ) : NEW_LINE INDENT print ( " The ▁ radius ▁ of ▁ each ▁ circle ▁ is ▁ " , d / ( 2 * n - 2 ) ) ; NEW_LINE DEDENT d = 42 ; n = 4 ; NEW_LINE radius ( n , d ) ; NEW_LINE
Find the side of the squares which are lined in a row , and distance between the centers of first and last square is given | Python program to find side of the squares which are lined in a row and distance between the centers of first and last squares is given ; Driver code
def radius ( n , d ) : NEW_LINE INDENT print ( " The ▁ side ▁ of ▁ each ▁ square ▁ is ▁ " , d / ( n - 1 ) ) ; NEW_LINE DEDENT d = 42 ; n = 4 ; NEW_LINE radius ( n , d ) ; NEW_LINE