Check if two strings are k | Python 3 program for the above approach ; Function to check k anagram of two strings ; First Condition : If both the strings have different length , then they cannot form anagram ; Converting str1 to Character Array arr1 ; Converting str2 to Character Array arr2 ; Sort arr1 in increasing order ; Sort arr2 in increasing order ; Iterate till str1 . length ( ) ; Condition if arr1 [ i ] is not equal to arr2 [ i ] then add it to list ; Condition to check if strings for K - anagram or not ; Driver Code ; Function Call
import sys NEW_LINE def kAnagrams ( str1 , str2 , k ) : NEW_LINE INDENT flag = 0 NEW_LINE list1 = [ ] NEW_LINE if ( len ( str1 ) != len ( str2 ) ) : NEW_LINE INDENT sys . exit ( ) NEW_LINE DEDENT arr1 = list ( str1 ) NEW_LINE arr2 = list ( str2 ) NEW_LINE arr1 . sort ( ) NEW_LINE arr2 . sort ( ) NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT if ( arr1 [ i ] != arr2 [ i ] ) : NEW_LINE INDENT list1 . append ( arr2 [ i ] ) NEW_LINE DEDENT DEDENT if ( len ( list1 ) <= k ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT if ( flag == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " fodr " NEW_LINE str2 = " gork " NEW_LINE k = 2 NEW_LINE kAnagrams ( str1 , str2 , k ) NEW_LINE if ( kAnagrams ( str1 , str2 , k ) == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT