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 ) occur... | 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 +... |
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 ... | 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 le... |
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_LIN... |
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 answe... | 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_LI... |
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 cha... | 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 I... |
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_L... |
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... |
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 v... | 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 IN... |
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 DE... |
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 ) : ... |
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 ... |
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_LIN... |
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 equa... | 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 +... |
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 ] == ... |
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 ... |
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 . ; I... | 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 [ en... |
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_LI... |
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 c... | 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 ... |
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 vowe... | 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... |
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 ] ) ,... |
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... | 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 NE... |
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 ) : ... |
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 ; Checki... | 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 ... |
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_... |
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' ... |
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 en... |
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_... |
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 factoria... | 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 rang... |
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 ... | 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 NE... |
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 ;... | 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 ... |
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 ... | 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 ( ... |
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... |
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... |
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 s... | 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 ]... |
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... |
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... |
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... | 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 ' )... |
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 , retu... | 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 ... |
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... | 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 = "12abc2... |
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 ... | 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_co... |
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 i... |
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 al... | 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... |
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 ... | 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 ... |
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 ... | 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 ... |
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... | 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 = in... |
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 ; E... | 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 =... |
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 ( St... |
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 a... | 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 DED... |
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 Tr... |
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 ... | 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 pri... |
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 ; Otherwis... | 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 D... |
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 ; I... | 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 ( ... |
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 prim... | 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 ] = Fals... |
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... | 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 r... |
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... | 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 INDE... |
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 ... | 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 DE... |
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 " Fina... | 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 gr... |
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 ... | 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 ... |
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 v... | 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 a... |
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 , ldma... | 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 ) ) ... |
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... | 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 ) ... |
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 sta... | 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 con... |
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 ) ] Her... | 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 +... |
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 ... | 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 + ( ... |
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 ; i... | 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 ... |
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 numb... | 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 ret... |
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 p... | 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 " ... |
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... | 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 = ... |
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 seco... | 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 ... |
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... | 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 β +... |
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... | 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 ) :... |
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 respecti... | 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 ] ... |
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... | 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 ... |
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... | 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 IND... |
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 - ordin... | 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 focu... |
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 co... | 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 ] * ... |
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 ort... | 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 ... |
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 po... | 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 ( ... |
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 ; Give... | 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_L... |
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 ... |
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 p... | 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 ... |
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 a... | 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 mag... |
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 1... | 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 ... |
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 )... |
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_L... |
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 ... |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.