Anagram test for two strings in python -
this question:
write function named test_for_anagrams receives 2 strings parameters, both of consist of alphabetic characters , returns true if 2 strings anagrams, false otherwise. 2 strings anagrams if 1 string can constructed rearranging characters in other string using characters in original string once. example, strings "orchestra" , "carthorse" anagrams because each 1 can constructed rearranging characters in other 1 using characters in 1 of them once. note capitalization not matter here i.e. lower case character can considered same upper case character.
my code:
def test_for_anagrams (str_1, str_2): str_1 = str_1.lower() str_2 = str_2.lower() print(len(str_1), len(str_2)) count = 0 if (len(str_1) != len(str_2)): return (false) else: in range(0, len(str_1)): j in range(0, len(str_2)): if(str_1[i] == str_2[j]): count += 1 if (count == len(str_1)): return (true) else: return (false) #main program str_1 = input("enter string 1: ") str_2 = input("enter string 2: ") result = test_for_anagrams (str_1, str_2) print (result)
the problem here when enter strings orchestra
, carthorse
, gives me result false
. same strings the eyes
, they see
. appreciated.
i'm new python, excuse me if i'm wrong
i believe can done in different approach: sort given strings , compare them.
def anagram(a, b): # string list str1 = list(a.lower()) str2 = list(b.lower()) #sort list str1.sort() str2.sort() #join list string str1 = ''.join(str1) str2 = ''.join(str2) return str1 == str2 print(anagram('orchestra', 'carthorse'))
Comments
Post a Comment